From 3ed9155f10b725e6d24c01f5ecbebf359f3599a7 Mon Sep 17 00:00:00 2001 From: David Rubin Date: Mon, 26 May 2025 12:20:14 -0700 Subject: [PATCH] Sema: simplify comptime `@intFromPtr` logic --- src/Sema.zig | 22 ++++++------------- .../int_from_ptr_to_optional.zig | 13 +++++++++++ 2 files changed, 20 insertions(+), 15 deletions(-) create mode 100644 test/cases/compile_errors/int_from_ptr_to_optional.zig diff --git a/src/Sema.zig b/src/Sema.zig index 60f857ace7..e7f47a1791 100644 --- a/src/Sema.zig +++ b/src/Sema.zig @@ -2287,19 +2287,6 @@ fn resolveValueResolveLazy(sema: *Sema, inst: Air.Inst.Ref) CompileError!?Value return try sema.resolveLazyValue((try sema.resolveValue(inst)) orelse return null); } -/// Like `resolveValue`, but any pointer value which does not correspond -/// to a comptime-known integer (e.g. a decl pointer) returns `null`. -/// Lazy values are recursively resolved. -fn resolveValueIntable(sema: *Sema, inst: Air.Inst.Ref) CompileError!?Value { - const val = (try sema.resolveValue(inst)) orelse return null; - if (sema.pt.zcu.intern_pool.getBackingAddrTag(val.toIntern())) |addr| switch (addr) { - .nav, .uav, .comptime_alloc, .comptime_field => return null, - .int => {}, - .eu_payload, .opt_payload, .arr_elem, .field => unreachable, - }; - return try sema.resolveLazyValue(val); -} - /// Value Tag may be `undef` or `variable`. pub fn resolveFinalDeclValue( sema: *Sema, @@ -10144,14 +10131,19 @@ fn zirIntFromPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError! } const len = if (is_vector) operand_ty.vectorLen(zcu) else undefined; const dest_ty: Type = if (is_vector) try pt.vectorType(.{ .child = .usize_type, .len = len }) else .usize; - if (try sema.resolveValueIntable(operand)) |operand_val| ct: { + + if (try sema.resolveValue(operand)) |operand_val| ct: { if (!is_vector) { if (operand_val.isUndef(zcu)) { return Air.internedToRef((try pt.undefValue(Type.usize)).toIntern()); } + const addr = try operand_val.getUnsignedIntSema(pt) orelse { + // Wasn't an integer pointer. This is a runtime operation. + break :ct; + }; return Air.internedToRef((try pt.intValue( Type.usize, - (try operand_val.toUnsignedIntSema(pt)), + addr, )).toIntern()); } const new_elems = try sema.arena.alloc(InternPool.Index, len); diff --git a/test/cases/compile_errors/int_from_ptr_to_optional.zig b/test/cases/compile_errors/int_from_ptr_to_optional.zig new file mode 100644 index 0000000000..8456e70ede --- /dev/null +++ b/test/cases/compile_errors/int_from_ptr_to_optional.zig @@ -0,0 +1,13 @@ +comptime { + const num: usize = 4; + const y: ?*const usize = # + _ = @intFromPtr(y); +} + +// error +// backend=stage2 +// target=native +// +// :4:9: error: unable to evaluate comptime expression +// :4:21: note: operation is runtime due to this operand +// :1:1: note: 'comptime' keyword forces comptime evaluation