Re: [Pyparsing] Operator Precedence and Associativity.
Brought to you by:
ptmcg
From: Paul M. <pa...@al...> - 2006-10-11 14:03:20
|
> -----Original Message----- > From: Ralph Corderoy [mailto:ra...@in...] > Sent: Wednesday, October 11, 2006 7:08 AM > To: Paul McGuire > Cc: pyp...@li... > Subject: Re: [Pyparsing] Operator Precedence and Associativity. > > > Hi Paul, > > > Well, why not?! Check this out! > > > > def operatorGrammar( baseExpr, opList ): > > ret = Forward() > > lastExpr = baseExpr | ( Suppress('(') + ret + > Suppress(')') ) ... > > That's impressive and exactly what I was after. You may want > to consider formalising it as part of pyparsing since > recursive descent parsers often use operator precedence > parsers for that part of things. > > Thanks! > > > Ralph. > Ralph - Note that this does not *quite* do the LR-style recursive descent you were looking for. That is to say, 9 + 2 + 3 parses as: [[9, '+', 2, '+', 3]] and not as: [[[9, '+', 2], '+', 3]] which is what I think you were looking for originally. On the whole, though, it seems quite interesting. It took me about 2 minutes to do the following boolean expression grammar: boolExpr = operatorGrammar( Word(alphas), [ ("not",1,"R"), ("or",2,"L"), ("and",2,"L"), ]) test = ["p and not q", "not not p", "not(p and q)", "q or not p and r", "q or not (p and r)" ] for t in test: print t,'\n',boolExpr.parseString(t),'\n' Giving: p and not q [['p', 'and', ['not', 'q']]] not not p [['not', ['not', 'p']]] not(p and q) [['not', ['p', 'and', 'q']]] q or not p and r [[['q', 'or', ['not', 'p']], 'and', 'r']] q or not (p and r) [['q', 'or', ['not', ['p', 'and', 'r']]]] I need to give this a little more thought as far as including it into "core" pyparsing (as opposed to say, just making it another example - the examples directory is sort of becoming its own Pyparsing Cookbook). I want to make sure I get the API right. For instance, I might want to support a 4'th entry in each input tuple, representing a parse action to be attached to the internally generated pyparsing expression. -- Paul |