How can I associate many alternatives to same class when defining a grammar node with treetop?

64 views Asked by At

I have the following simple grammar:

grammar MyGrammar
  rule comparison_operator
    '=' / '>' <ComparisonOperator>
  end
end

When I'm parsing the string >, it returns successfully with:

ComparisonOperator

When I'm parsing the string =, it returns without syntax error, but does not associate the string matched to a ComparisonOperator instance, but only to a

Treetop::Runtime::SyntaxNode

If I reverse the order of the characters in the grammar...

grammar MyGrammar
  rule comparison_operator
    '>' / '=' <ComparisonOperator>
  end
end

then it works ok for = but does not work ok for >.

If I associate every symbol to ComparisonOperator

grammar MyGrammar
  rule comparison_operator
    '>' <ComparisonOperator> / '=' <ComparisonOperator>
  end
end

then it works ok for both, but I do not find that very intuitive. And it becomes cumbersome if one has a lot of symbol alternatives.

Is there a way to associate the ComparisonOperator to all alternatives in a more simple way?

Update: I have added a new Github repository with all the code that demonstrates this problem here: https://github.com/pmatsinopoulos/treetop_tutorial

1

There are 1 answers

4
cliffordheath On

Simply put parentheses around the alternatives, so the ComparisonOperator applies to either:

grammar MyGrammar
  rule comparison_operator
    ('>' / '=') <ComparisonOperator>
  end
end

The parentheses creates a sequence containing the alternates, and the class associates with that sequence.