繁体   English   中英

预期返回5个令牌时,ANTLR3 lexer返回一个令牌

[英]ANTLR3 lexer returns one token when expecting to return 5 tokens

您好,我正在尝试构建一个简单的词法分析器来标记以';'开头的行 字符。

这是我的词法分析器语法:

lexer grammar TestLex;

options {
  language = Java;
  filter = true;
}

@header {
  package com.ualberta.slmyers.cmput415.assign1;
}

IR              :   LINE+           
                ;

LINE            :   SEMICOLON (~NEWLINE)* NEWLINE
                ;

SEMICOLON       : ';'                   
                ;
NEWLINE         : '\n'              
                ;
WS              : (' ' | '\t')+ 
                  {$channel = HIDDEN;}
                ;

这是我的Java类来运行我的词法分析器:

package com.ualberta.slmyers.cmput415.assign1;

import java.io.IOException;

import org.antlr.runtime.*;

public class Test {

public static void main(String[] args) throws RecognitionException,
        IOException {

    // create an instance of the lexer
    TestLex lexer = new TestLex(
            new ANTLRFileStream(
                    "/home/linux/workspace/Cmput415Assign1/src/com/ualberta/slmyers/cmput415/assign1/test3.s"));

    // wrap a token-stream around the lexer
    CommonTokenStream tokens = new CommonTokenStream(lexer);

    // when using ANTLR v3.3 or v3.4, un-comment the next line:
    tokens.fill();

    // traverse the tokens and print them to see if the correct tokens are
    // created
    int n = 1;
    for (Object o : tokens.getTokens()) {
        CommonToken token = (CommonToken) o;
        System.out.println("token(" + n + ") = "
                + token.getText().replace("\n", "\\n"));
        n++;
    }
}

}

归功于: http : //bkiers.blogspot.ca/2011/03/2-introduction-to-antlr.html ,以获取上面的改编代码。

这是我的测试文件:

; token 1
; token 2
; token 3
; token 4

请注意,最后一个“ 4”后面有换行符。

这是我的输出:

token(1) = ; token 1\n; token 2\n; token 3\n; token 4\n
token(2) = <EOF>

我期望这作为我的输出:

token(1) = ; token 1\n
token(2) = ; token 2\n
token(3) = ; token 3\n
token(4) = ; token 4\n
token(5) = <EOF>

好的,我发现问题出在这一行:

IR          :   LINE+           
            ;

它返回了一个由多行组成的令牌。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM