简体   繁体   中英

Antlr4 Parse Number

I want write expression like springEl to practice.

When I input #user.age>3 is right.

But I input #user.age>3ww or #user.age>3ww && #user.age<2 the parser not hint any error. I do not think #user.age>3ww is right syntax.

How to change grammar to let the parser hint 3ww is error?

my part antlr4 grammar

grammar FlowExpr;

statement : expr;

expr
    :   expr (Mul|Div) expr
    |   expr (Add|Sub) expr
    |   expr BooleanOperator expr
    |   expr And expr
    |   expr Or expr
    |   Not expr
    |   object
    ;

object
    :   boolean
    |   invoker
    |   entity
    |   number
    |   String
    ;
entity : ObjectSymbol Identifier;
boolean : 'true'|'false';
invoker : entity attribute+;
attribute : Dot Identifier;
number
    :   Integer
    |   Float
    ;
Identifier :  Letter (Letter|JavaIDDigit)* ;
Integer : '-'? INT ;
Float : '-'? INT Dot [0-9]*;

Commas : ',';

BooleanOperator
    :   '>'|'>='|'<'|'<='|'=='|'!=';
Not:'!';
Dot : '.';
ObjectSymbol : '#';
WS  :   [ \t\n\r]+ -> skip ;

enter image description here

The input 2w is being tokenised as an Integer - and Identifier token. Then the number parser rule consumes the Integer token and then stops parsing (it matches exactly 1 Integer token, which is what you told it to do).

If you want to force the parser to consume all the tokens produces by the lexer, you need it to do so by adding an EOF (the built-in end of file/input token). You's usually have 1 entry-rule that contains this EOF :

grammar t;

entryPoint
    : number EOF
    ;

number
    :   Integer
    |   Float
    ;
fragment INT :  '0'| [1-9][0-9]* ; 
Integer : '-'? INT ;
Float : '-'? INT Dot [0-9]*;
Dot : '.';
Identifier :  [a-zA-Z];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM