Inform - Support - Patches

About Patches  

Compiler  
Library  

DM4 Errata  

Issue C62102

Constant folding is broken
Submitted by: Torbjörn Andersson     Appeared in: Compiler 6.20 or before     Fixed in: Compiler 6.30
Problem

Constant folding in Inform, i.e. the process of evaluating constant arithmetic expression at compile-time, appears to be severely broken. For instance, the following program:

  [ Main; print_ret -10 / 5; ];

will print 13105 rather than -2. The problem does not apply just to division -- pretty much any constant folding will fail once you involve negative numbers.

The problem, I believe, is that while folding constants Inform will also translate the result into 16-bit Z-machine values. So what happens above is that -10 (the operator "unary minus" applied to the constant 10) is folded to the Z-machine representation of -10 (the constant). But when you pad these 16 bits with zeroes to make a 32-bit value, you don't get -10, but 65526. Divide by 5 and you get, approximately, 13105.

Solution

I see two possible ways of fixing this. Either the values have to be converted back into native format before doing the constant folding, or the constant folding has to be rewritten to work with Z-machine values. A quick and dirty way of doing the former would be to add two lines to expressp.c, around line 825, like this:

            if ((o1.marker == 0) && (o2.marker == 0)
            && ((o1.type == SHORT_CONSTANT_OT)||(o1.type == LONG_CONSTANT_OT))
            && ((o2.type == SHORT_CONSTANT_OT)||(o2.type == LONG_CONSTANT_OT)))
            {
  -->           if (o1.value > 0x7fff) o1.value -= 0x10000;
  -->           if (o2.value > 0x7fff) o2.value -= 0x10000;
                switch(t.value)
                {
                    case PLUS_OP: x = o1.value + o2.value; goto FoldConstantC;

However, I have no idea if this is sufficient, or if it breaks anything else in the process. It wouldn't surprise me the least if it did.


Last updated 17 April 2013. This web site has not been fully supported since April 2008. Information may be out of date. This page was originally managed by Roger Firth.