Commit c036f83fa0

Jacob Young <jacobly0@users.noreply.github.com>
2023-06-26 00:50:58
Value: fix incorrect types returned from readFromMemory
1 parent cc2daae
Changed files (3)
src/Sema.zig
@@ -30579,7 +30579,7 @@ fn analyzeLoad(
 
     if (try sema.resolveDefinedValue(block, ptr_src, ptr)) |ptr_val| {
         if (try sema.pointerDeref(block, src, ptr_val, ptr_ty)) |elem_val| {
-            return sema.addConstant(try mod.getCoerced(elem_val, elem_ty));
+            return sema.addConstant(elem_val);
         }
     }
 
src/value.zig
@@ -946,12 +946,24 @@ pub const Value = struct {
             },
             .Pointer => {
                 assert(!ty.isSlice(mod)); // No well defined layout.
-                return readFromMemory(Type.usize, mod, buffer, arena);
+                const int_val = try readFromMemory(Type.usize, mod, buffer, arena);
+                return (try mod.intern(.{ .ptr = .{
+                    .ty = ty.toIntern(),
+                    .addr = .{ .int = int_val.toIntern() },
+                } })).toValue();
             },
             .Optional => {
                 assert(ty.isPtrLikeOptional(mod));
-                const child = ty.optionalChild(mod);
-                return readFromMemory(child, mod, buffer, arena);
+                const child_ty = ty.optionalChild(mod);
+                const child_val = try readFromMemory(child_ty, mod, buffer, arena);
+                return (try mod.intern(.{ .opt = .{
+                    .ty = ty.toIntern(),
+                    .val = switch (child_val.orderAgainstZero(mod)) {
+                        .lt => unreachable,
+                        .eq => .none,
+                        .gt => child_val.toIntern(),
+                    },
+                } })).toValue();
             },
             else => @panic("TODO implement readFromMemory for more types"),
         }
test/behavior/comptime_memory.zig
@@ -438,3 +438,15 @@ test "type pun extern struct" {
     @as(*u8, @ptrCast(&s)).* = 72;
     try testing.expectEqual(@as(u8, 72), s.f);
 }
+
+test "type pun @ptrFromInt" {
+    const p: *u8 = @ptrFromInt(42);
+    // note that expectEqual hides the bug
+    try testing.expect(@as(*const [*]u8, @ptrCast(&p)).* == @as([*]u8, @ptrFromInt(42)));
+}
+
+test "type pun null pointer-like optional" {
+    const p: ?*u8 = null;
+    // note that expectEqual hides the bug
+    try testing.expect(@as(*const ?*i8, @ptrCast(&p)).* == null);
+}