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 31053cd
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/Sema.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2280,9 +2280,12 @@ pub fn resolveFinalDeclValue(
});
};
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(sema.pt.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: []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:26: error: global variable contains reference to comptime var

0 comments on commit 31053cd

Please sign in to comment.