kach / nearley

📜🔜🌲 Simple, fast, powerful parser toolkit for JavaScript.
https://nearley.js.org
MIT License
3.57k stars 232 forks source link

Does Nearley allow named parameters in grammar rules? #536

Open jarble opened 3 years ago

jarble commented 3 years ago

In some parser generators (such as PEG.js), it's possible to declare parameters in a grammar rule, and then use them in the parser's output:

add
  = (left:mul "+" right:add / "sum of " left:mul " and " right:add) { return left + right; }
  / mul

I wish I could also do this in Nearley, so that the parser's output could be defined more conveniently:

add
  -> (left:mul "+" right:add | "sum of " left:mul " and " right:add) 
       {% return left + right; %}
  | mul

Does Nearley allow variables to be defined in this way, like PEG.js?

bandaloo commented 3 years ago

This is what I miss most from PEG.js. I guess what the authors want you to do is to decompose the arguments in the arrow function:

expression ->
    number "+" number {% ([fst, _, snd]) => fst + snd %}

(Above example is taken from this.)

kach commented 3 years ago

This was on the "to do" list for a while, but never really got done. I think a better solution, actually, is a syntactic notation that lets you explicitly include/exclude pieces of the rule from what gets reported in the d array. That way if you have a long rule with many pieces but only one or two "important" pieces, you wouldn't need to fish around for the index into the array passed to the postprocessor.