Reputation: 4595
I am trying to define a grammar that allows for
[Foo]-[Bar]-[Baz][X]-[Y][Z]
I want to parse this as one set.
I currently have
grammar Sample;
items : (item association? item?)*;
item : LBRACK ID RBRACK;
association : ASSOCIATION;
RBRACK : ']';
LBRACK : '[';
ASSOCIATION : '-';
ID : ('a'..'z' | 'A'..'Z' | '_')*;
But this gives an error
warning(200): Sample.g:3:30: Decision can match input such as
"LBRACK ID RBRACK" using multiple alternatives: 1, 2
As a result, alternative(s) 2 were disabled for that input
And as a diagram I get
And I get this railroad diagram
How can I fix this?
Upvotes: 1
Views: 276
Reputation: 74267
You could try something like this:
ID : ('a'..'z'|'A'..'Z'|'_')* ;
item : '[' ID ']' ;
dependency : item ( '-' item )+ ;
list : ( item | dependency )+
;
Upvotes: 1
Reputation: 170158
Given the input [Foo]-[Bar]-[Baz][X]-[Y][Z]
, the following:
chunk : items+ EOF;
items : item (ASSOCIATION item)* ;
item : '[' ID ']' ;
RBRACK : ']';
LBRACK : '[';
ASSOCIATION : '-';
ID : ('a'..'z' | 'A'..'Z' | '_')*;
SPACE : (' ' | '\t' | '\r' | '\n'){skip();};
produces the following parse tree:
Upvotes: 1
Reputation: 74267
Try something like
items : ( '-'? item )* ;
item : '[' ID ']' ;
ID : ('a'..'z'|'A'..'Z'|'_') ;
which will allow a leading '-' or empty input
or
items : item? ( '-'? item )* ;
item : '[' ID ']' ;
ID : ('a'..'z'|'A'..'Z'|'_') ;
which won't allow a leading '-', but also allows empty input
Upvotes: 1