kschiess / parslet

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

Mechanism for matching optional keys in a transform rule #165

Open ravinggenius opened 8 years ago

ravinggenius commented 8 years ago

Having a way to mark certain keys as optional could go a long way towards reducing mostly redundant transform rules. Here's a simple example to show what I'm asking for.

Instead of two rules:

rule(integer: simple(:integer)) do |integer:|
  Nodes::Integer.new(integer, sign: :+)
end
rule(integer: simple(:integer), sign: simple(:sign)) do |integer:, sign:|
  Nodes::Integer.new(integer, sign: sign)
end

... I'd like to write a single rule to encapsulate the core logic:

rule(integer: simple(:integer), sign: simple(:sign, optional: :+)) do |integer:, sign:|
  Nodes::Integer.new(integer, sign: sign)
end

Notice the optional keyword passed into simple. The value of optional could be the default value to yield to the block if the key isn't present. Alternatively it could be a simple boolean to indicate an optional key, and it would be up to the block to handle the missing value. The optional argument should be available to sequence and subtree as well.

ravinggenius commented 8 years ago

Any interest in this?

kschiess commented 7 years ago

It sounds useful. Do you have a working solution for this that doesn't slow down all transformations? Seems to me that you have to do more checking at each stage.

ravinggenius commented 7 years ago

I don't have a working solution yet so I don't know what the performance impact would be. I wanted to see what you (@kschiess) thought before starting.

kschiess commented 7 years ago

It sounds useful.