Finding duplicate sub-expressions in calculator grammar

A

andrew

i've written a parser in perl for a simple arithmetic grammar
{+,-,*,/,funtion ()} where each operation is potentially expensive to
evaluate. the parser outputs an AST tree that is stored for each of a set
of spreadsheet-like cells that can then be re-evaluated with different
inputs.

currently, if there are expressions like:

(A+B)+f(A+B)
A+B+A+B

the sub-expression A+B gets evaluated more than once when evaluating the
AST tree for that expression. i'd like them to be evaluated only once as
doing A+B can be expensive.

is there a clever way to pre-parse each expression with a regexp to make a
list of identical subexpressions (maybe making a list of expressions with
temporary variables, to be evaluated in succession, like C=A+B, C+f(C))?

can any compiler, like gcc, optimize for this?

andrew.
 
J

John Bokma

andrew said:
i've written a parser in perl for a simple arithmetic grammar
{+,-,*,/,funtion ()} where each operation is potentially expensive to
evaluate. the parser outputs an AST tree that is stored for each of a
set of spreadsheet-like cells that can then be re-evaluated with
different inputs.

currently, if there are expressions like:

(A+B)+f(A+B)
A+B+A+B

the sub-expression A+B gets evaluated more than once when evaluating
the AST tree for that expression. i'd like them to be evaluated only
once as doing A+B can be expensive.

is there a clever way to pre-parse each expression with a regexp to
make a list of identical subexpressions

if (A+B) == (B+A) holds, regexp is certainly not the way to go.

Parse the expression into a tree and read documentation on common sub
expression elimintation.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,161
Messages
2,570,892
Members
47,430
Latest member
7dog123

Latest Threads

Top