问题
I've been using ANTLRwork 1.5 these days, together with antlr runtime 3.5. Here is a weird thing i found: Antlr is generating this kind of java code for me:
public final BLABLABLAParser.addExpression_return addExpression() throws {
blablabla...
}
notice that this function throws nothing, and this is invalid in java. So I need to correct these mistakes manually.
Anyone knows why?
here is the sample grammar, it's directly taken from the book Language implementation patterns.
// 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;}
;
回答1:
Edit: This is a bug in ANTLRWorks 1.5 that has already been fixed for the next release.
#5: ANTLRworks fails to generate proper Java Code
I used the exact configuration you described above, with a copy/pasted grammar. The signature generated for the rule you mention was the following:
// $ANTLR start "addExpression"
// C:\\dev\\Cymbol.g:72:1: addExpression : postfixExpression ( '+' ^ postfixExpression )* ;
public final CymbolParser.addExpression_return addExpression() throws RecognitionException {
Can you post the first line of the generated file? It should start with // $ANTLR 3.5
like the following:
// $ANTLR 3.5 C:\\dev\\Cymbol.g 2013-02-13 09:55:44
来源:https://stackoverflow.com/questions/14753989/antlr-generating-invalid-java-exceptions-throws-code