flutterdarthl7-fhirpetitparser

PetitParser and Parentheses


Sorry, I ran into another question about using PetitParser. I've figured out my recursive issues, but now I have a problem with parentheses. If I need to be able to parse the following two expressions:

  1. '(use = "official").empty()'
  2. '(( 5 + 5 ) * 5) + 5'

I've tried doing something like the following:

final expression = (char('(') & any().starGreedy(char(')')).flatten() & char(')')).map((value) => ParenthesesParser(value));

But that doesnt' work on the first expression. If I try this:

final expression = (char('(') & any().starLazy(char(')')).flatten() & char(')')).map((value) => ParenthesesParser(value));

It doesn't work on the second expression. Any suggestions on how to parse both?


Solution

  • I think neither of the parsers does what you want: The first parser, the greedy one with starGreedy, will consume up to the last closing parenthesis. The second parser, the lazy one with starLazy, will consume up to the first closing parenthesis.

    To parse a balanced parenthesis you need recursion, so that each opening parenthesis is followed by a matching closing one:

    final inner = undefined();
    final parser = char('(') & inner.star().flatten() & char(')');
    inner.set(parser | pattern('^)'));
    

    In the snippet above, the inner parser is recursively trying to either parse another parenthesis pair, or otherwise it simply consumes any character that is not a closing parenthesis.