The lexer tries to match as much as possible. Therefore you will need to change the IDs
rule into a parser rule instead:
ids
: ID+
;
Space
: [ \t] -> skip
;
Or if you're going to keep spaces:
ids
: ID (Space ID)*
;
سؤال
I would like to create a MiniLang with friendly function name
This is my sample script and expected statement
// actual // expected
set a = true; // 'set a' -> IDs // 'set' -> Set, 'a' -> IDS
Set name ('hello'); // 'Set name' -> IDs // 'Set name' -> IDs
set b = my friendly variable; // 'set b' -> IDs // 'set' -> Set, 'b' -> IDS
set my variable = 10; // 'set my variable' -> IDs // 'set' -> Set, 'my variable' -> IDs
Calculate sum (1, 2, 4); // 'Calculate sum' -> IDs // 'Calculate sum' -> IDs
I would like some reserved keywords will be matched before IDs (identifier with multi-words). But ANTLR4 matches IDs only. I try to define keywords before IDs but not effect.
How to define rule for keyword of statement be matched before IDs
Thanks!
This is my grammar
grammar MiniLang;
document
: (stmt NL*)+ EOF
;
stmt
: Set Space+ IDs Space* '=' Space* expr Space* ';' # SetStatement
| IDs Space* '(' Space* (expr (Space*(',' expr))*)? Space* ')' Space* ';' # FunctionCall
;
expr
: atom
;
atom
: IDs
| Number
| String
;
Set
: 'set'
;
Space
: ' '
;
Number
: [0-9]+
;
ID
: [a-zA-Z][a-zA-Z0-9]*
;
IDs
: ID (Space ID)*
;
String
: ['] (~['\r\n\\] | EscapeSequence)* [']
;
EscapeSequence
: '\\' [']
;
NL
: [\r\n]
;
المحلول
The lexer tries to match as much as possible. Therefore you will need to change the IDs
rule into a parser rule instead:
ids
: ID+
;
Space
: [ \t] -> skip
;
Or if you're going to keep spaces:
ids
: ID (Space ID)*
;