[Pyparsing] Visitor pattern in pyparsing
Brought to you by:
ptmcg
From: Paul M. <pt...@au...> - 2009-09-27 12:42:56
|
As I've read more about Visitors, I think this pattern may actually be more applicable to the results that might be returned from the parsing process. In the case of a parser that returns some structured tokens, a Visitor might be created that walks this list, pretty-printing the output, or evaluating some generated expression execution objects. Unfortunately, pyparsing has little control over what kinds of objects will be found. The overall object returned is always a ParseResults object, but the items within the ParseResults' list are likely to be just Python strings. They could also be ints, floats, or even user-defined objects, if the user created parse actions that did some kind of type conversion. So to visit the results, each matched item or group would have to be wrapped in some kind of "visitable" object, most likely created in a parse action. I have implemented something *like* this, for example in the SimpleBool.py example - here every matching expression returns an instance of a subclass of BoolOperand, which implements its own version of __nonzero__. After parsing, the parseResults are evaluated by calling bool(item) for each item in the results - bool(x) calls x.__nonzero__ in Python2.x. So for visiting parsed results, I may have to just add another example to the examples directory, showing how to use the Visitor pattern on the matched tokens. -- Paul |