3

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

p.matsinopoulos
  • 7,655
  • 6
  • 44
  • 92

1 Answers1

0

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.

cliffordheath
  • 2,536
  • 15
  • 16
  • Unfortunately. This does not work. It raises an error which I describe in the README of the problem-demo project here: https://github.com/pmatsinopoulos/treetop_tutorial – p.matsinopoulos Jan 20 '16 at 12:12
  • You get that error because ComparisonOperator must be a module, not a class. A class can work in some limited cases (leaf nodes), but a module is the general solution. – cliffordheath Jan 21 '16 at 02:45
  • And why does it work if I have 1 symbol only? In my example the nodes are terminating/leaf nodes. Also, see this example here: http://glaucocustodio.com/2014/11/10/natural-language-parsing-with-ruby/ It uses a Class. Not a Module. – p.matsinopoulos Jan 21 '16 at 07:55
  • It must be a module any time Treetop has already created a SyntaxNode - so it can mix in that module. – cliffordheath Jan 21 '16 at 09:25