I am trying to design a small compiler as a form of practice. I have not read yet into intermediate code optimization or anything regarding optimization yet.
So far I have a FLEX/BISON files describing the grammar and I have the expressions working fine. While doing this I thinking that I should have like a constant expression and repeat all the additive and multiplicative expressions for their constant equivalent and compute their values while parsing it.
So I was wondering if this is the right thing to do? Or should I let the code optimization (when I read into them) handle stuff like that?
You can probably do a better job during code optimization. For example, 3 + a + 39
is optimizable to a + 42
(for unsigned integer arithmetic, anyway), but it's not easy to detect during the parse.
More interesting constant-folding is a result of your flow analysis detecting that a variable has a known constant value. That is definitely hard to do during the parse.
So on the whole, it's probably better to just let the parser parse, and perform optimizations during and after semantic analysis.