2

我正在学习 jflex,并编写了一个最简单的 jflex 代码,它生成了一个字符#

import com.intellij.lexer.FlexLexer;
import com.intellij.psi.tree.IElementType;

%%

%class PubspecLexer
%implements FlexLexer
%unicode
%type IElementType
%function advance
%debug

Comment = "#"

%%

{Comment} { System.out.println("Found comment!"); return PubTokenTypes.Comment; }
.                                        { return PubTokenTypes.BadCharacter; }

然后我生成一个PubspecLexer类,并尝试它:

public static void main(String[] args) throws IOException {
    PubspecLexer lexer = new PubspecLexer(new StringReader("#!!!!!"));
    for (int i = 0; i < 3; i++) {
        IElementType token = lexer.advance();
        System.out.println(token);
    }
}

但它打印 3null秒:

null
null
null

为什么它既不返回Comment也不返回BadCharacter

4

1 回答 1

4

这不是 jflex 的问题,实际上是因为 idea-flex 改变了原来的用法。

在使用 jflex 编写 intellij-idea 插件时,我们使用的是打了补丁的“JFlex.jar”和“idea-flex.skeleton”,后面定义zzRefill方法为:

private boolean zzRefill() throws java.io.IOException {
    return true;
}

而不是原来的:

private boolean zzRefill() throws java.io.IOException {

  // ... ignore some code 

  /* finally: fill the buffer with new input */
  int numRead = zzReader.read(zzBuffer, zzEndRead,
                                          zzBuffer.length-zzEndRead);
  // ... ignore some code

  // numRead < 0
  return true;
}

注意代码中有一个 a zzReader,它保存了#!!!!!我传入的字符串。但在idea-flex 版本中,它从未使用过。

所以要使用idea-flex版本,我应该像这样使用它:

public class MyLexer extends FlexAdapter {
    public MyLexer() {
        super(new PubspecLexer((Reader) null));
    }
}

然后:

public static void main(String[] args) {
    String input = "#!!!!!";
    MyLexer lexer = new MyLexer();
    lexer.start(input);
    for (int i = 0; i < 3; i++) {
        System.out.println(lexer.getTokenType());
        lexer.advance();
    }
}

哪个打印:

match: --#--
action [19] { System.out.println("Found comment!"); return PubTokenTypes.Comment(); }
Found comment!
Pub:Comment
match: --!--
action [20] { return PubTokenTypes.BadCharacter(); }
Pub:BadCharacter
match: --!--
action [20] { return PubTokenTypes.BadCharacter(); }
Pub:BadCharacter
于 2014-04-13T09:29:59.507 回答