Token keyword antlr parser id

How to handle the case when the 'for' token is used in two different situations in the language for parsing? For example, the operator and as a "parameter" in the following example:

echo for print example
for i in {0..10..2}
  do
     echo "Welcome $i times"
 done

Conclusion:

for print example
Welcome 0 times
Welcome 2 times
Welcome 4 times
Welcome 6 times
Welcome 8 times
Welcome 10 times

Thank.

+3
source share
3 answers

The only way I see how you could do this is to define a rule Echoin your lexical grammar that matches the characters Echo, followed by all the other characters except \rand \n:

Echo
  :  'echo' ~('\r' | '\n')+
  ;

, , (, for).

:

grammar Test;

parse
  :  (echo | for)*
  ;

echo
  :  Echo (NewLine | EOF)
  ;

for 
  :  For Identifier In range NewLine
     Do NewLine
     echo
     Done (NewLine | EOF)
  ;

range
  :  '{' Integer '..' Integer ('..' Integer)? '}'
  ;

Echo
  :  'echo' ~('\r' | '\n')+
  ;

For  : 'for';
In   : 'in';
Do   : 'do';
Done : 'done';

Identifier
  :  ('a'..'z' | 'A'..'Z' | '_') ('a'..'z' | 'A'..'Z' | '_' | '0'..'9')*
  ;

Integer
  :  '0'..'9'+
  ;

NewLine
  :  '\r' '\n'
  |  '\n'
  |  '\r'
  ;

Space
  :  (' ' | '\t') {skip();}
  ;

:

echo for print example
for i in {0..10..2}
do
  echo "Welcome $i times"
done
echo the end for now!

:

alt text http://img571.imageshack.us/img571/5713/grammar.png

( , !)

.

+1

, , - :

TOKEN_REF
    :   'A'..'Z' ('a'..'z'|'A'..'Z'|'_'|'0'..'9')*
    ;

, , - :

'print' (TOKEN_REF)*

for "", :

'for' INT 'in' SOMETHING
0

, lexer , for.

ANTLR.

0

Source: https://habr.com/ru/post/1743021/


All Articles