Re: Constant expression evaluation?

Christian Bau <>
16 May 2003 21:57:39 -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: Christian Bau <>
Newsgroups: comp.compilers
Date: 16 May 2003 21:57:39 -0400
Organization: Compilers Central
References: 03-05-089
Keywords: optimize
Posted-Date: 16 May 2003 21:57:39 EDT

  Paul Davis <> wrote:

> 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 '*'. The expression doesn't get evaluated to '6'
> till a later time, which is effectively 'runtime' (this is a
> sort-of-interpreted language). My problem is therefore that the
> front-end compiler doesn't know that this is a constant expression,
> and so rejects it as an error because it's not a 'constant'. The Bison
> action code for expressions doesn't calculate the value of an
> expression: it simply pushes the elements of the expression onto the
> required stack.

Write a bit of code that tries to simplify stacks. For example, if your
stack looks like

      +, <expr1>, <expr2>

then you check whether <expr1> is a constant and if not, then you try to
simplify it to a constant. If you succeed, then you know where <expr2>
is because now your stack looks like

      +, constant, <expr2>

so you check whether <expr2> is a constant and if not you try to
simplify it to a constant. If that succeeds you have

      +, constant1, constant2

and replace that with the constant (constant1 + constant2).

That code is invoked every time you require a constant, but you can use
it everywhere. Using trees instead of stacks makes many things easier.

Post a followup to this message

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