-
Hi ! What is the equivalent of peg.js labels ? Let's say for example I want to convert the following Peg.js rule
This rule uses two labels in the grammar : What is the best way to do it in PetitParser ? I would like to use such a feature because in many rules I've got optional parts, and so it would make my task easier. Also I'm using the same structure as in the examples (prolog, json)
Regards |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
PetitParser doesn't use code generation (like peg.js). This would enable things like labels, but also comes at the cost of introducing another language and making it impossible to arbitrarily mix Dart and parser code. This might change hopefully soon when Dart gets support for static metaprogramming. In the meantime a sequence of parsers generates a list of parse results that you can access by index, i.e. Parser additive() => (ref0(multiplicative) & char("+") & ref0(additive)).map((values) => values[0] + values[2])
/ ref(multiplicative); If this is a common pattern, I recommend to extract it to a helper method, i.e. Parser term(Parser left, Parser op, Parser right, int Function(int left, int right) callback) {
return (left & op & right).map((values) => callback(values[0], values[2])) / ref(left);
}
Parser additive() => term(ref0(multiplicative), char("+"), ref0(additive), (left, right) => values[0] + values[2]); Also note that for expressions there is an expression-builder that does exactly this out of the box: ...
builder.group()
..left(char('+').trim(), (a, op, b) => a + b)
... |
Beta Was this translation helpful? Give feedback.
-
Yes, that's correct. The optional parsers get a fixed entry in the resulting list. By default the resulting absent value will be |
Beta Was this translation helpful? Give feedback.
Yes, that's correct. The optional parsers get a fixed entry in the resulting list. By default the resulting absent value will be
null
, but there is also the option to specify any other default value, see the documentation.