Re: Constant expression evaluation?

"Dierk Ohlerich" <>
16 May 2003 21:58:32 -0400

          From comp.compilers

Related articles
Constant expression evaluation? (Paul Davis) (2003-05-14)
Re: Constant expression evaluation? (Christian Bau) (2003-05-16)
Re: Constant expression evaluation? (Dierk Ohlerich) (2003-05-16)
Re: Constant expression evaluation? (Clint Olsen) (2003-05-18)
Re: Constant expression evaluation? (Niksa Orlic) (2003-05-29)
Re: Constant expression evaluation? (david lindauer) (2003-05-29)
| List of all articles for this month |

From: "Dierk Ohlerich" <>
Newsgroups: comp.compilers
Date: 16 May 2003 21:58:32 -0400
Organization: Compilers Central
References: 03-05-089
Keywords: optimize
Posted-Date: 16 May 2003 21:58:32 EDT

> I'm hoping to add constant expressions to a simple compiler I've
> written, but it looks like some of my early design decisions will make
> this difficult. I'd appreciate some ideas on better ways to do this.
> Currently, I've got various places, like declarations, where the
> syntax requires a constant. It wasn't obvious that expressions would
> be needed, but it now looks like I need them. For example:
> property A = 6; // this is what I've got
> property B = 2*3; // this is what I need
> My expression evaluator (in Bison) currently creates a set of stacks
> (the actual stack depends on context) which are later processed by an
> RPN calculator. So, when I get '2*3', I push 2 on the stack, followed
> by 3, followed by '*'.

First I Create A Parse Tree. The Syntax Allows Full Expressions Everywhere.

Then I Optimise Away All Nodes That Have Only Constant Childs. There Are A
Few Lines Of Code For Every Operator, Like "If Left Node Is Constant And
Right Node Is Constant Then Calculate Result And Change This Node To
Constant". This Gets More Ugly If You Support Floats And Integers.

Then I Create The Code From The Parse Tree. Here I Generate The Error
Message If Someone Does Things Like "Int A[Sin(3.141)];".

So Actually The "Constant Folding" Is Done During Optimisation, And
This Is A Very Simple Optimisation. Even If You Planned For A
Non-Optimising Compiler, Having A Phase Where You Can Do
Transformation Before The Actual Code Is Generated Usually Pays
Off. And You Get More Advanced Optimisations, Like "If(0)" For A Few
Lines Of Code.

Dierk "Chaos" Ohlerich VCC-Entertainment

Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.