在 ANTLR 中,如何指定特定的重复次数? [英] In ANTLR, how do you specify a specific number of repetitions?
问题描述
我使用 ANTLR 来指定包含不能超过 254 个字符的行(不包括行尾)的文件格式.我如何在语法中对此进行编码,做不到:
I'm using ANTLR to specify a file format that contains lines that cannot exceed 254 characters (excluding line endings). How do I encode this in the grammer, short of doing:
line : CHAR? CHAR? CHAR? CHAR? ... (254 times)
推荐答案
这可以通过使用 语义谓词.
首先以这样一种方式写你的语法,不管你的行有多长.一个示例如下所示:
First write your grammar in such a way that it does not matter how long your lines are. An example would look like this:
grammar Test;
parse
: line* EOF
;
line
: Char+ (LineBreak | EOF)
| LineBreak // empty line!
;
LineBreak : '\r'? '\n' | '\r' ;
Char : ~('\r' | '\n') ;
然后将谓词"添加到line
规则中:
and then add the "predicate" to the line
rule:
grammar Test;
@parser::members {
public static void main(String[] args) throws Exception {
String source = "abcde\nfghij\nklm\nnopqrst";
ANTLRStringStream in = new ANTLRStringStream(source);
TestLexer lexer = new TestLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
TestParser parser = new TestParser(tokens);
parser.parse();
}
}
parse
: line* EOF
;
line
: (c+=Char)+ {$c.size()<=5}? (LineBreak | EOF)
| LineBreak // empty line!
;
LineBreak : '\r'? '\n' | '\r' ;
Char : ~('\r' | '\n') ;
c+=Char
将构造一个包含行中所有字符的 ArrayList
.当 ArrayList
的大小超过 5 时,{$c.size()<=5}?
导致抛出异常.
The c+=Char
will construct an ArrayList
containing all characters in the line. The {$c.size()<=5}?
causes to throw an exception when the ArrayList
's size exceeds 5.
我还在解析器中添加了一个 main 方法,以便您可以自己测试:
I also added a main method in the parser so you can test it yourself:
// *nix/MacOSX
java -cp antlr-3.2.jar org.antlr.Tool Test.g
javac -cp antlr-3.2.jar *.java
java -cp .:antlr-3.2.jar TestParser
// Windows
java -cp antlr-3.2.jar org.antlr.Tool Test.g
javac -cp antlr-3.2.jar *.java
java -cp .;antlr-3.2.jar TestParser
将输出:
line 0:-1 rule line failed predicate: {$c.size()<=5}?
HTH
这篇关于在 ANTLR 中,如何指定特定的重复次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!