Skip to content

bug: Comptime variable assignment in branch with runtime condition #8462

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
felipepiovezan opened this issue Apr 7, 2021 · 2 comments
Closed
Milestone

Comments

@felipepiovezan
Copy link

felipepiovezan commented Apr 7, 2021

What

An assignment to a comptime variable is predicated by a run-time value, but the compiler doesn't emit an error.
Instead, it uses "program" order and performs assignments on all branches. In particular, flipping the branch
condition and inverting the branch blocks should produce an equivalent program, but it doesn't.

(This could be me misinterpreting the comptime documentation)

Code that reproduces the issue

Godbolt link

export fn foo(arg:i32) i32 {
   comptime var x = 0;
   x = 10000;
   if (arg > 0) { x = 1;}
   else {x = 2;}
   return x;
}

const std = @import("std");

pub fn main() !void {
    std.debug.print("foo(-1) = {}!\n", .{foo(-1)});
    std.debug.print("foo(1) = {}!\n", .{foo(1)});
    std.debug.print("foo(-1) = {}!\n", .{comptime foo(-1)});
    std.debug.print("foo(1) = {}!\n", .{comptime foo(1)});
}

Produced output

foo(-1) = 2!
foo(1) = 2!
foo(-1) = 2!
foo(1) = 1!

Expected output

// first print => error: writing to comptime variable on a path that depends on a runtime value
/// second print => error: writing to comptime variable on a path that depends on a runtime value
foo(-1) = 2!
foo(1) = 1!

Tags searched before filing this issue

comptime variable branch

Tested with Zig versions:

  • trunk (version available at the time of writing on Godbolt)
  • .7
  • .6
@SpexGuy
Copy link
Contributor

SpexGuy commented Apr 7, 2021

Thanks for the report! We have a plan to fix this, see #1470.

@felipepiovezan
Copy link
Author

Neat, thanks for looking into it! I'll close this as a duplicate!

@andrewrk andrewrk added this to the 0.8.0 milestone Jun 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants