#comptime generated code unwrapping

1 messages · Page 1 of 1 (latest)

tight hinge
#

I'm picking up zig and was wondering if there is a tool to view what code actually comes out of comptime? Searched around a bit and couldn't really find anything. Currently it's not quite intuitive to me what ifs and switches evaluate to with comptime.

teal flame
#

there isn't, as comptime is just part of the semantic analysis pass, it isn't a preprocessor
comptime is just a way to evalaute zig code while it's building, is there a particular example that is confusing?

tight hinge
#

I guess the ziglings comptime7 example is as simple as it gets when I get confused. (Removed comments)

    const instructions = "+3 *5 -2 *2";
    var value: u32 = 0;
    comptime var i = 0;
    inline while (i < instructions.len) : (i += 3) {
        const digit = instructions[i + 1] - '0';
        switch (instructions[i]) {
            '+' => value += digit,
            '-' => value -= digit,
            '*' => value *= digit,
            else => unreachable,
        }
    }

I understand what the code does here, obviously. The example they provide states

appear anywhere in the compiled program because it's
not used by it!

Which is what I can't quite wrap my head around when this gets introduced. What is, at the end of the day, the internal representation of this code? Like, what is my computer doing at runtime here?

#

Is the entire program basically boiled down to this?

var value: u32 = 0;
value += 3;
value *= 5;
value -= 2;
value *= 2;
teal flame
#

so the inline while has each iteration evaluated and placed as runtime, genearlized over that iteration's i
so we have the four steps, i = 0, 3, 6, 9
on each one, we see that

const digit = instructions[i + 1] - '0'

becomes

const digit = instructions[{1, 4, 7, 10}] - '0'

which in turn, as instructions is comptime known also is indexed at compile time, and the - '0' can also be done at compile time
the switch has a comptime known argument for all the cases, so it is also evaluated at compile time, resulting in the expression in the branch
so yes, that is exactly what the code is boiled into