Re: [Pyparsing] Operator Precedence and Associativity.
Brought to you by:
ptmcg
From: Paolo L. <p....@hy...> - 2006-09-12 15:57:01
|
Hi Ralph, Ralph Corderoy wrote: > whereas I'd like the left associativity explicit, i.e. > > + > / \ > 1 + 2 + 3 ==> + 3 > / \ > 1 2 > > I can achieve this with a right-associative operator, e.g. exponent, but > how do I do this for left-associative ones whilst avoiding endless > left-recursion? I think you have no other choice but to rearrange ParseResults by setting a specific parse action for the expression: from pyparsing import * plus = Literal('+') num = Word(nums) def left_associative_regroup(s,l,t): new_t = ParseResults( [ t[0], t[2] ] ) for item in t[3:]: if item != "+": new_t = ParseResults( [new_t, item] ) return new_t expr = num + ZeroOrMore( plus + num ) expr.setParseAction(left_associative_regroup) print expr.parseString("1 + 2 + 3 + 4 + 5") > I wonder if PyParsing would benefit from being able to define operator > tables, similar to K&R's, giving the tokens, precedence, and > associativity, and being able to plumb that into the rest of the > recursive descent parser at some point? It's not trivial at all. From http://en.wikipedia.org/wiki/Left_recursion "A formal grammar that contains left recursion cannot be parsed by a recursive descent parser" PyParsing qualifies as recursive descent parser. I think it would rather be possible to build Specilized Constructs such as LeftAssociativeOperator(term=Word(nums), operator=Literal('+') ) but those would only cope with immediate left recursion... Hope this helps Ciao Paolo |