Bruce Pierson
Bruce Pierson

Reputation: 587

ANTLR (v4) Arbitrary Rule Ordering

I'm parsing a JSON-like structure that looks something like this:

items {
    item {
        name : 'Name',
        value : 'abc',
        type : String
    }
}

The parser rule for item might look like this:

item
    : name ',' value ',' type // I want these to be able to be in any order
    ;
name
    : NAME ':' Str
    ;
value
    : VALUE ':' atom
    ;
type
    : TYPE ':' data_type
    ;

How would I write the item rule such that the order of the key : value pairs is unimportant, and the parser would only check for the presence of the rule? That is, value could come before name, etc.

EDIT

I should clarify that I know I could do this:

item
    : item_item*
    ;
item_item
    : name
    | value
    | type
    ;

But the problem with that is that the item rule needs to limit each rule to only one instance. Using this technique, I could end up with any number of name rules, for example.

Upvotes: 0

Views: 80

Answers (1)

CoronA
CoronA

Reputation: 8075

The naive brute force approach would be to solve the problem in syntactic analysis (avoid this):

item
  : name ',' value ',' type
  | name ',' type ',' value
  | type ',' name ',' value
  | ...
  ;

This leeds to a large parser spec and unmaintainable visitor/listener code.

Better: Use a simple parser rule and a semantic predicate to validate:

item
  : i+=item_item ',' i+=item_item ',' i+=item_item  {containsNVT($i)}?
  ;
item_item
  : name
  | value
  | type
  ;

You can place the code to validate that all three items are specified containsNVT($i) inline or in a parser super class.

Upvotes: 2

Related Questions