kschiess / parslet

A small PEG based parser library. See the Hacking page in the Wiki as well.
kschiess.github.com/parslet
MIT License
809 stars 95 forks source link

Support a custom reducer when using infix_expression #158

Closed chrismwendt closed 8 years ago

chrismwendt commented 8 years ago

This adds support for a custom reducer when using infix_expression. This allows you to change the way the tree is generated:

p = infix_expression(str('a'), [str('-'), 1, :right]) { |l,o,r| {:and=>[l,r]} }
p.parse("a-a-a")
# => {:and=>["a", {:and=>["a", "a"]}]}
# instead of {:l=>"a", :o=>"-", :r=>{:l=>"a", :o=>"-", :r=>"a"}}

This is more convenient that using Transforms because the reducer here is bundled with the parser and will follow the parser wherever the parser is used (more composable). Also, the reducer will only be applied to exactly the nodes of the tree where an infix expression occurs (not the whole tree).

kschiess commented 8 years ago

Good idea. Can you add an example of usage in the comments? This is otherwise ready for merge.

chrismwendt commented 8 years ago

@kschiess Thanks, and yep, I added an example.

kschiess commented 8 years ago

Thanks for this!