Skip to content
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

use of undefined only compiler error if const, not var #10752

Closed
mitchellh opened this issue Feb 1, 2022 · 2 comments
Closed

use of undefined only compiler error if const, not var #10752

mitchellh opened this issue Feb 1, 2022 · 2 comments

Comments

@mitchellh
Copy link
Contributor

Zig Version

0.10.0-dev.500+66cf011aa

Steps to Reproduce

  1. Save the following code as bug.zig
  2. zig run bug.zig -- passes
  3. Change var to const
  4. zig run bug.zig -- compiler error
const std = @import("std");

pub fn main() !void {
    var x: bool = undefined;
    if (!x) {
        std.log.info("YES", .{});
    }
}

Expected Behavior

Compiler error regardless of var vs const usage, since either way you're comptime-provably using an undefined value.

Actual Behavior

Compiler error only if const.

@mitchellh mitchellh added the bug Observed behavior contradicts documented or intended behavior label Feb 1, 2022
@andrewrk
Copy link
Member

andrewrk commented Feb 1, 2022

This is actually working as designed because Zig is not able to prove that x is undefined in the var case.

This case looks easy to prove, and indeed it is, but we could construct an arbitrarily difficult problem for which solving it would be the halting problem. Currently Zig's analysis stops at var. So, on the line with the if expression, the !x is an undefined value, and then if (undefined) is unchecked undefined behavior due to branching on an undefined value.

The issue for adding a safety check for this kind of undefined behavior is #63.

I don't think we have a proposal issue open for advanced control flow analysis which would attempt to prove that an undefined value gets branched on, such as in this case. If you'd like to transform this issue into such a proposal, feel free to do so. Just edit your issue and title and I'll add the appropriate labels.

@andrewrk andrewrk removed the bug Observed behavior contradicts documented or intended behavior label Feb 1, 2022
@mitchellh
Copy link
Contributor Author

Ah #63 was what I was looking for. Yeah sorry I figured the comptime angle wasn’t exhaustively solvable but was unsure about the simple case. Runtime made a lot more sense. Thanks!

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

2 participants