Home > Software engineering >  How the define parser rule for empty array in Antlr 4.0
How the define parser rule for empty array in Antlr 4.0

Time:02-11

I have the following set of rules in my Antlr grammar file:

//myidl.g4

grammar myidl;

integerLiteral:
    value = DecimalLiteral # decimalNumberExpr
    | value = HexadecimalLiteral # hexadecimalNumberExpr
    ;

DecimalLiteral: DIGIT ;

HexadecimalLiteral: ('0x' | '0X') HEXADECIMALDIGIT ;

fragment DIGIT: [0-9];

fragment HEXADECIMALDIGIT: [0-9a-fA-F];

array:
    '[' ( integerLiteral ( ',' integerLiteral )* )* ']' // how to allow empty arrays like "[]"?
    ;

The resulting parser works fine for arrays with elements, for example "[0x00]". But when defining an empty array "[]", i get the error: no viable alternative at input '[]'

The funny thing is that when defining the empty array with a space, like "[ ]", the parser eats it without error. Can somebody tell me whats wrong with my rules, and how to adjust the rules to allow empty arrays definition without spaces, "[]"?

I use ANTLR Parser Generator Version 4.9.2

EDIT: It turns out that I was using an old version of the parser due to configuration issue. |=( The above rules work just fine.

CodePudding user response:

You probably have defined a token in your lexer grammar that matches []:

SOME_RULE
 : '[]'
 ;

remove that rule.

CodePudding user response:

The grammar copied above works correctly in my opinion. must match [] and not [ ] (with space).

As already suggested check the tokens and if you have imported other lexer check that you don't have token like '[]'.

The following grammar:

    grammar myidl;
        
    integerLiteral: DecimalLiteral | HexadecimalLiteral;
    
    DecimalLiteral: DIGIT ;
    
    HexadecimalLiteral: ('0x' | '0X') HEXADECIMALDIGIT ;
    
    fragment DIGIT: [0-9];
    
    fragment HEXADECIMALDIGIT: [0-9a-fA-F];
    
    array:
        '[' ( integerLiteral ( ',' integerLiteral )* )* ']';
        
    WS  : [ \t] -> skip ;     

match:

  • [0x00]
  • []
  • [ ]
  • Related