【问题标题】:What's wrong with this simplest jflex code?这个最简单的 jflex 代码有什么问题?
【发布时间】:2014-04-12 14:52:22
【问题描述】:

我在学习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);
    }
}

但它打印 3 nulls:

null
null
null

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

【问题讨论】:

    标签: jflex


    【解决方案1】:

    不是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;
    }
    

    请注意,代码中有一个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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-16
      • 2015-09-30
      • 2017-07-12
      相关资源
      最近更新 更多