编程语言
首页 > 编程语言> > 生成无效java异常的ANTLR会抛出代码

生成无效java异常的ANTLR会抛出代码

作者:互联网

这些天我一直在使用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;}
    ;

解决方法:

编辑:这是ANTLRWorks 1.5中的一个错误,已经为下一个版本修复了.
#5: ANTLRworks fails to generate proper Java Code

我使用了上面描述的确切配置,并使用了复制/粘贴语法.为您提到的规则生成的签名如下:

// $ANTLR start "addExpression"
// C:\\dev\\Cymbol.g:72:1: addExpression : postfixExpression ( '+' ^ postfixExpression )* ;
public final CymbolParser.addExpression_return addExpression() throws RecognitionException {

你可以发布生成文件的第一行吗?它应该以// $ANTLR 3.5开头,如下所示:

// $ANTLR 3.5 C:\\dev\\Cymbol.g 2013-02-13 09:55:44

标签:java,antlr3,antlrworks
来源: https://codeday.me/bug/20190709/1411353.html