Commit 2c434cddd6

Andrew Kelley <andrew@ziglang.org>
2022-03-16 00:41:10
AstGen: add missing coercion for const locals
A const local which had its init expression write to the result pointer, but then gets elided to directly initialize, was missing the coercion to the type annotation.
1 parent d4a0d5f
Changed files (3)
lib
std
src
test
behavior
lib/std/special/compiler_rt.zig
@@ -303,10 +303,8 @@ comptime {
 
     const __floatunsisf = @import("compiler_rt/floatunsisf.zig").__floatunsisf;
     @export(__floatunsisf, .{ .name = "__floatunsisf", .linkage = linkage });
-    if (builtin.zig_backend == .stage1) { // TODO it's crashing on a switch expression
-        const __floatundisf = @import("compiler_rt/floatundisf.zig").__floatundisf;
-        @export(__floatundisf, .{ .name = "__floatundisf", .linkage = linkage });
-    }
+    const __floatundisf = @import("compiler_rt/floatundisf.zig").__floatundisf;
+    @export(__floatundisf, .{ .name = "__floatundisf", .linkage = linkage });
     const __floatunsidf = @import("compiler_rt/floatunsidf.zig").__floatunsidf;
     @export(__floatunsidf, .{ .name = "__floatunsidf", .linkage = linkage });
     const __floatundidf = @import("compiler_rt/floatundidf.zig").__floatundidf;
src/AstGen.zig
@@ -2762,11 +2762,18 @@ fn varDecl(
                 }
                 gz.instructions.items.len = dst;
 
+                // In case the result location did not do the coercion
+                // for us so we must do it here.
+                const coerced_init = if (opt_type_inst != .none)
+                    try gz.addBin(.as, opt_type_inst, init_inst)
+                else
+                    init_inst;
+
                 if (!gz.force_comptime) {
                     _ = try gz.add(.{ .tag = .dbg_var_val, .data = .{
                         .str_op = .{
                             .str = ident_name,
-                            .operand = init_inst,
+                            .operand = coerced_init,
                         },
                     } });
                 }
@@ -2776,7 +2783,7 @@ fn varDecl(
                     .parent = scope,
                     .gen_zir = gz,
                     .name = ident_name,
-                    .inst = init_inst,
+                    .inst = coerced_init,
                     .token_src = name_token,
                     .id_cat = .@"local constant",
                 };
test/behavior/eval.zig
@@ -766,3 +766,14 @@ test "two comptime calls with array default initialized to undefined" {
         S.CrossTarget.parse();
     }
 }
+
+test "const type-annotated local initialized with function call has correct type" {
+    const S = struct {
+        fn foo() comptime_int {
+            return 1234;
+        }
+    };
+    const x: u64 = S.foo();
+    try expect(@TypeOf(x) == u64);
+    try expect(x == 1234);
+}