olle
olle

Reputation: 4595

antlr grammar for [Foo]-[Bar]-[Baz][X]-[Y][Z]

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 enter image description here

And I get this railroad diagram

enter image description here

How can I fix this?

Upvotes: 1

Views: 276

Answers (3)

Nicholas Carey
Nicholas Carey

Reputation: 74267

You could try something like this:

ID        : ('a'..'z'|'A'..'Z'|'_')* ;
item      : '[' ID ']' ;
dependency : item ( '-' item )+ ;
list      : ( item | dependency )+
          ;

Upvotes: 1

Bart Kiers
Bart Kiers

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:

enter image description here

Upvotes: 1

Nicholas Carey
Nicholas Carey

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

Related Questions