在ANTLR中解析DECAF语法

时间:2015-01-14 18:28:54

标签: antlr grammar

我正在使用Antlr为DECAF创建解析器 语法DECAF;

//********* LEXER ******************
LETTER: ('a'..'z'|'A'..'Z') ;
DIGIT : '0'..'9' ;
ID : LETTER( LETTER | DIGIT)* ;
NUM: DIGIT(DIGIT)* ;
COMMENTS: '//' ~('\r' | '\n' )*  -> channel(HIDDEN);
WS : [ \t\r\n\f | ' '| '\r' | '\n' | '\t']+  ->channel(HIDDEN); 

CHAR: (LETTER|DIGIT|' '| '!' | '"' | '#' | '$' | '%' | '&' | '\'' | '(' | ')' | '*' | '+' 

| ',' | '-' | '.' | '/' | ':' | ';' | '<' | '=' | '>' | '?' | '@' | '[' | '\\' | ']' | '^' | '_' | '`'| '{' | '|' | '}' | '~' 
'\t'| '\n' | '\"' | '\'');


// ********** PARSER *****************

program : 'class' 'Program' '{' (declaration)* '}'  ;

declaration: structDeclaration| varDeclaration | methodDeclaration  ;

varDeclaration: varType ID ';' | varType ID '[' NUM ']' ';'  ;

structDeclaration : 'struct' ID '{' (varDeclaration)* '}'  ;

varType: 'int' | 'char' | 'boolean' | 'struct' ID | structDeclaration | 'void'  ;

methodDeclaration : methodType ID '(' (parameter (',' parameter)*)* ')' block  ;

methodType : 'int' | 'char' | 'boolean' | 'void' ;

parameter : parameterType ID | parameterType ID '[' ']' ;

parameterType: 'int' | 'char' | 'boolean'  ;

block : '{' (varDeclaration)* (statement)* '}' ;

statement : 'if' '(' expression ')' block ( 'else' block )? 
           | 'while' '(' expression ')' block
           |'return' expressionA ';' 
           | methodCall ';' 
           | block  
           | location '=' expression 
           | (expression)? ';'  ;

expressionA: expression | ;


location : (ID|ID '[' expression ']') ('.' location)?  ;

expression : location | methodCall | literal | expression op expression | '-' expression | '!' expression | '('expression')'  ;

methodCall :    ID '(' arg1 ')' ;

arg1    :   arg2 | ;

arg2    :   (arg) (',' arg)* ;

arg :   expression;

op: arith_op | rel_op | eq_op | cond_op  ;

arith_op : '+' | '-' | '*' | '/' | '%' ;

rel_op : '<' | '>' | '<=' | '>=' ;

eq_op : '==' | '!=' ;

cond_op : '&&' | '||' ;

literal : int_literal | char_literal | bool_literal ;

int_literal : NUM ;

char_literal : '\'' CHAR '\'' ;

bool_literal : 'true' | 'false' ;

当我给它输入时:

    class Program {

    void main(){

        return 3+5 ;
    }
    }

解析树未正确构建,因为它未将3 + 5识别为表达式。导致问题的语法有什么问题吗?

1 个答案:

答案 0 :(得分:2)

Lexer规则从上到下匹配。当2个或更多词法分析器规则匹配相同数量的字符时,首先定义的字符将 win 。因此,单个数字整数将匹配为DIGIT而不是NUM

请尝试解析以下内容:

class Program {
    void main(){    
        return 33 + 55 ;
    }
}

将被解析得很好。这是因为3355 匹配为NUM,因为NUM现在可以匹配2个字符(DIGIT只有1个,所以NUM 获胜)。

要解决此问题,请将DIGIT设为片段(以及LETTER):

fragment LETTER: ('a'..'z'|'A'..'Z') ;
fragment DIGIT : '0'..'9' ;
ID : LETTER( LETTER | DIGIT)* ;
NUM: DIGIT(DIGIT)* ;

Lexer片段仅在其他词法分析器规则内部使用,并且永远不会成为他们自己的令牌。

其他一些事项:您的WS规则匹配太多(现在它也匹配|'),它应该是:

WS : [ \t\r\n\f]+  ->channel(HIDDEN);

并且您不应该在解析器中匹配char文字:在词法分析器中执行:

CHAR : '\'' ( ~['\r\n\\] | '\\' ['\\] ) '\'';

如果不这样做,将无法正确解析以下内容:

class Program {
    void main(){
        return '1';
    }
}

因为1会被标记为NUM而不是CHAR