Skip to content

Commit 95857d6

Browse files
committed
Sema: add missing runtime value validation to global mutable variables
Resolves: #20365
1 parent 3624356 commit 95857d6

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

src/Sema.zig

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2274,15 +2274,20 @@ pub fn resolveFinalDeclValue(
22742274
src: LazySrcLoc,
22752275
air_ref: Air.Inst.Ref,
22762276
) CompileError!Value {
2277+
const zcu = sema.pt.zcu;
2278+
22772279
const val = try sema.resolveValueAllowVariables(air_ref) orelse {
22782280
return sema.failWithNeededComptime(block, src, .{
22792281
.needed_comptime_reason = "global variable initializer must be comptime-known",
22802282
});
22812283
};
22822284
if (val.isGenericPoison()) return error.GenericPoison;
2283-
if (val.canMutateComptimeVarState(sema.pt.zcu)) {
2285+
2286+
const init_val: Value = if (val.getVariable(zcu)) |v| .fromInterned(v.init) else val;
2287+
if (init_val.canMutateComptimeVarState(zcu)) {
22842288
return sema.fail(block, src, "global variable contains reference to comptime var", .{});
22852289
}
2290+
22862291
return val;
22872292
}
22882293

test/cases/compile_errors/comptime_var_referenced_by_decl.zig

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,12 @@ export const g: *const *const u32 = g: {
3838
break :g &aggregate[0];
3939
};
4040

41+
// Mutable globals should have the same restrictions as const globals.
42+
export var h: *[1]u32 = h: {
43+
var x: [1]u32 = .{123};
44+
break :h &x;
45+
};
46+
4147
// error
4248
//
4349
// :1:27: error: global variable contains reference to comptime var
@@ -47,3 +53,4 @@ export const g: *const *const u32 = g: {
4753
// :22:24: error: global variable contains reference to comptime var
4854
// :28:33: error: global variable contains reference to comptime var
4955
// :34:40: error: global variable contains reference to comptime var
56+
// :42:28: error: global variable contains reference to comptime var

0 commit comments

Comments
 (0)