Let's say I want to be able to parse an arbitrary expression like
f(f( a + f(a * b * f(c))))
where a, b,c are variables, and f is some function. I want to make a parse tree.
Last night I thought of a very unorthodox way to do this.
I know about yacc/lex, pyparsing, and Python's ast. However, for what I have in mind this is all I need:
Python supports overloading operators.
Python has an "eval" ability to dynamically run code.
My idea is to create Python objects for f, a, b, c, and then *eval* the expression as if it were Python code(!)
The objects I create will have their operators overloaded so that a+b, for example, returns an expression like ['+', a, b].
And in the end, I'll get a parse tree just like I wanted.
Here's an example that supports addition, multiplication, and functions taking any number of arguments. (Adding the rest of the operators is simple).
I could even use this to write a compiler -- I wrote another script to turn the tree into this,
I'm currently working on a way to conserve the temporary variables used here, because there is probably a way to reuse them after they aren't needed. What I do is go down to the bottom of the tree, find something that can be evaluated, and replace that deepest node with a temporary variable. I then repeat that process until the whole tree has been "flattened".
The code has been added to GitHub here under the GPLv3.