1
你好,我试图建立一个简单的词法分析器来标记行以';'开头,字符。ANTLR3词法分析器返回一个标记,当期望返回5个标记
这是我的词法语法:
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>