Skip to content

Commit

Permalink
Sema: add missing runtime value validation to global mutable variables
Browse files Browse the repository at this point in the history
Resolves: #20365
  • Loading branch information
mlugg committed Oct 7, 2024
1 parent 3624356 commit 95857d6
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/Sema.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2274,15 +2274,20 @@ pub fn resolveFinalDeclValue(
src: LazySrcLoc,
air_ref: Air.Inst.Ref,
) CompileError!Value {
const zcu = sema.pt.zcu;

const val = try sema.resolveValueAllowVariables(air_ref) orelse {
return sema.failWithNeededComptime(block, src, .{
.needed_comptime_reason = "global variable initializer must be comptime-known",
});
};
if (val.isGenericPoison()) return error.GenericPoison;
if (val.canMutateComptimeVarState(sema.pt.zcu)) {

const init_val: Value = if (val.getVariable(zcu)) |v| .fromInterned(v.init) else val;
if (init_val.canMutateComptimeVarState(zcu)) {
return sema.fail(block, src, "global variable contains reference to comptime var", .{});
}

return val;
}

Expand Down
7 changes: 7 additions & 0 deletions test/cases/compile_errors/comptime_var_referenced_by_decl.zig
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ export const g: *const *const u32 = g: {
break :g &aggregate[0];
};

// Mutable globals should have the same restrictions as const globals.
export var h: *[1]u32 = h: {
var x: [1]u32 = .{123};
break :h &x;
};

// error
//
// :1:27: error: global variable contains reference to comptime var
Expand All @@ -47,3 +53,4 @@ export const g: *const *const u32 = g: {
// :22:24: error: global variable contains reference to comptime var
// :28:33: error: global variable contains reference to comptime var
// :34:40: error: global variable contains reference to comptime var
// :42:28: error: global variable contains reference to comptime var

0 comments on commit 95857d6

Please sign in to comment.