ANTLR 4选项

1 选项

可以在语法和规则级别上配置选项,以改变生成的代码。

1
options { name1=value1; ... nameN=valueN; } // ANTLR not target language syntax

value可以是识别符、全限定识别符a.b.c、字符串、花括号包围的多行字符串或整数等。

2 语法选项

所有的语法都可以使用选项。在结合的语法中,除语言相关的外仅与生成的解析器相关。

选项可以通过语法文件设置,可以通过命令行-D参数设置(具有更高优先级)。命令行参数详见ANTLR Tool Command Line Options

(1) superClass

指定Parser或Lexer的父类。

1
2
3
4
5
6
7
8
$ cat Hi.g4
grammar Hi;
a : 'hi' ;
$ antlr4 -DsuperClass=XX Hi.g4
$ grep 'public class' HiParser.java
public class HiParser extends XX {
$ grep 'public class' HiLexer.java
public class HiLexer extends Lexer {

(2) language

允许时,更新指定语言的代码。

1
2
$ antlr4 -Dlanguage=C MyGrammar.g4
error(31): ANTLR cannot generate C code as of version 4.0

(3) tokenVocab

按照出现顺序,为文件中的记号分配编号时,使用该选项指定顺序在哪个文件之后。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$ cat SomeLexer.g4
lexer grammar SomeLexer;
ID : [a-z]+ ;
$ cat R.g4
parser grammar R;
options {tokenVocab=SomeLexer;}
tokens {A,B,C} // normally, these would be token types 1, 2, 3
a : ID ;
$ antlr4 SomeLexer.g4
$ cat SomeLexer.tokens
ID=1
$ antlr4 R.g4
$ cat R.tokens
A=2
B=3
C=4
ID=1

(4) TokenLabelType

通常用于生成引用记号的变量。

如果向解析器或词法器传入了一个用于生成自定义记号的TokenFactory,应该为特殊的类型设置该选项,确保上下文对象知道这个类型。

1
2
3
4
5
6
7
$ cat T2.g4
grammar T2;
options {TokenLabelType=MyToken;}
a : x=ID ;
$ antlr4 T2.g4
$ grep MyToken T2Parser.java
public MyToken x;

(5) contextSuperClass

指定解析树内部节点的父类,默认为ParserRuleContext。

应该最小化提取RuleContext。

Java可以使用org.antlr.v4.runtime.RuleContextWithAltNum。其添加了字段altNumber和相关规则节点的alt方法。

3 规则选项

当前没有可用的规则级别的选项,但是支持以下语法用于未来支持:

1
2
3
4
rulename
options {...}
: ...
;

4 规则元素选项

规则元素选项格式:T<name=value>

当前只支持assoc选项,可以使用left或right作为参数。

以下示例中,左侧递归规则指定了^指数操作符。

1
2
3
4
5
6
7
8
9
10
grammar ExprLR;

expr : expr '^'<assoc=right> expr
| expr '*' expr // match subexpressions joined with '*' operator
| expr '+' expr // match subexpressions joined with '+' operator
| INT // matches simple integer atom
;

INT : '0'..'9'+ ;
WS : [ \n]+ -> skip ;

语义谓词也可以接受选项。

当前仅支持fail选项,用于在语义失败时输出信息,接收双引号包围的字符串,或者构建字符串的动作。

1
2
3
4
ints[int max]
locals [int i=1]
: INT ( ',' {$i++;} {$i<=$max}?<fail={"exceeded max "+$max}> INT )*
;

此外,动作中也可以执行返回字符串的函数{...}?<fail={doSomethingAndReturnAString()}>

参考资料