这些天我一直在使用 ANTLRwork 1.5,以及 antlr runtime 3.5。这是我发现的一件奇怪的事情:Antlr 正在为我生成这种 java 代码:
public final BLABLABLAParser.addExpression_return addExpression() throws {
blablabla...
}
注意这个函数什么都不抛出,这在java中是无效的。所以我需要手动纠正这些错误。
有谁知道为什么?
这是示例语法,它直接取自《语言实现模式》一书。
// START: header
// START: header
grammar Cymbol; // my grammar is called Cymbol
options {
output = AST;
ASTLabelType = CommonTree;
}
tokens{
METHOD_DECL;
ARG_DECL;
BLOCK;
VAR_DECL;
CALL;
ELIST;
EXPR;
}
// define a SymbolTable field in generated parser
compilationUnit // pass symbol table to start rule
: (methodDeclaration | varDeclaration)+ // recognize at least one variable declaration
;
// END: header
methodDeclaration
: type ID '(' formalParameters? ')' block
-> ^(METHOD_DECL type ID formalParameters? block)
;
formalParameters
: type ID (',' type ID)* -> ^(ARG_DECL type ID)+
;
// START: type
type
: 'float'
| 'int'
| 'void'
;
// END: type
block : '{' statement* '}' -> ^(BLOCK statement*)
;
// START: decl
varDeclaration
: type ID ('=' expression)? ';' -> ^(VAR_DECL type ID expression?)// E.g., "int i = 2;", "int i;"
;
// END: decl
statement
: block
| varDeclaration
| 'return' expression? ';' -> ^('return' expression?)
| postfixExpression
(
'=' expression -> ^('=' postfixExpression expression)
| -> ^(EXPR postfixExpression)
) ';'
;
expressionList
: expression(',' expression)* -> ^(ELIST expression+)
| -> ELIST
;
expression
: addExpression -> ^(EXPR addExpression)
;
addExpression
: postfixExpression('+'^ postfixExpression)*
;
postfixExpression
: primary (lp='('^ expressionList ')'! {$lp.setType(CALL);})*
;
// START: primary
primary
: ID // reference variable in an expression
| INT
| '(' expression ')' -> expression
;
// END: primary
// LEXER RULES
ID : LETTER (LETTER | '0'..'9')*
;
fragment
LETTER : ('a'..'z' | 'A'..'Z')
;
INT : '0'..'9'+
;
WS : (' '|'\r'|'\t'|'\n') {$channel=HIDDEN;}
;
SL_COMMENT
: '//' ~('\r'|'\n')* '\r'? '\n' {$channel=HIDDEN;}
;