Babel-Bridge
Babel-Bridge copied to clipboard
Feature Request
Shane this gem is awesome, it is saving me lots of time in developing a small dsl.
I was wondering if, when defining a rule, it is possible to actually name the pattern elements in a way similar to the following:
rule :x, first: /a_regex/, second: 'a string', third: /a_regex/ do
def evaluate
matches[:first].do_something
end
Otherwise one has to keep in mind the positions taken by empty terminal nodes to get the right index (e.g.: the index for the third element is matches[4] ) and it can be bothersome.
Thank you for sharing this gem, great job indeed!
That's not a bad idea. It might be worth considering in the future.
In the mean time there is a good alternative available now. I recommend making a small rule for each pattern you want to access in your block. Then use the named rule and refer to it by name in you block.
There is a good example here:
https://github.com/shanebdavis/Babel-Bridge/blob/master/examples/json/json_parser2.rb
Your example could be rewritten to:
rule :x, :first, :second, :third do
def evaluate
first.do_something
end
end
rule :first, /a_regex/
rule :second, 'a string'
rule :third, /a_regex/
FYI: You don't need to use "matches[:first]". Named rules get their own accessor methods. Also note that if you use the same named rule more than once or use it in a "many" clause, each match of that rule will be stored in an array which is returned by that rule's accessor.
Hi, thanks for the tips!
In such a a case
rule :x, :method, :arg, :arg, :arg #which should be rule :x, :method, many(:arg)
will the arg method return an array of args? or should I revert to using matches?
I have a question regarding rule matching precedence, but I did not find a google group for babel_bridge; where should I ask it?
Thanks a lot
Short: arg will return an array of args.
Details:
matches always returns all sub-elements that were matched as an array. Note that if one of your elements is optional, matches does not leave a gap for it in the array. Therefor the location of matches after a missed optional match will all be at a lower index.
If you use a named rule more than once (or in a "many" clause or both), then all matches for that named rule will also appear in the array returned by the attr_accessor created for that rule's name.
In your example, the arg method on the parse tree node created by rule x will return a length-three array where you will find the matches for all args at indexes 0, 1 and 2.