[Question] Making ANTLR Parser Rule

33 views
Skip to first unread message

Kyeongwhan Min

unread,
May 22, 2024, 1:11:09 AMMay 22
to antlr-discussion
I wrote rule in Expr.g4 Like this.

grammar Expr;

// parser rules
prog : ((decl)* expr?';' ?NEWLINE)*;
decl : 'def' func=FUNC_NAME (param=ID)* '=' e=expr 'endef';
expr : '~(' expr ')'                            # negateExpr
     | '(' expr ')'                             # parensExpr
     | left=expr op=('*'|'/') right=expr        # infixExpr
     | left=expr op=('+'|'-') right=expr        # infixExpr
     | 'let' var=ID '=' e1=expr 'in' e2=expr    # letinExpr
     | func=FUNC_NAME '(' (expr ','?)* ')'      # callExpr
     | value=num                                # numberExpr
     | ID                                       # varExpr
     ;
num  : '-'? INT   #INT
     | '-'? REAL  #REAL
     ;

OP_ADD: '+';
OP_SUB: '-';
OP_MUL: '*';
OP_DIV: '/';
OP_ASSIGN: '=';

// lexer rules
NEWLINE: [\r\n]+ ;
INT: [0-9]+ ;          // should handle negatives
REAL: [0-9]+'.'[0-9]* ; // should handle signs(+/-)
ID: '_'?[a-zA-Z]+'_'?[a-zA-Z]* ;
FUNC_NAME: [a-zA-Z][a-zA-Z0-9]* ;
WS: [ \t\r\n]+ -> skip ;

But the result was not I wanted.
스크린샷 2024-05-22 140405.png

I thought ID was preceding rule of FUNC_NAME so, I changed the order.

// lexer rules
NEWLINE: [\r\n]+ ;
INT: [0-9]+ ;          // should handle negatives
REAL: [0-9]+'.'[0-9]* ; // should handle signs(+/-)
FUNC_NAME: [a-zA-Z][a-zA-Z0-9]* ;
ID: '_'?[a-zA-Z]+'_'?[a-zA-Z]* ;
WS: [ \t\r\n]+ -> skip ;

Like above. However, it wasn't worked that I looked for.
스크린샷 2024-05-22 140616.png

How can I resolve this problem?

Desirable output that I want is like below screenshot : 
스크린샷 2024-05-22 140809.png
(The screenshot is edited using MS Paint)
Reply all
Reply to author
Forward
0 new messages