diff --git a/compiler/sempass2.nim b/compiler/sempass2.nim index f1e2e69cbe..7b2be510f9 100644 --- a/compiler/sempass2.nim +++ b/compiler/sempass2.nim @@ -1308,6 +1308,8 @@ proc allowCStringConv(n: PNode): bool = proc track(tracked: PEffects, n: PNode) = case n.kind + of nkTypeOfExpr: + discard "typeof() never evaluates its operand; not a definite-assignment use" of nkSym: useVar(tracked, n) if n.sym.typ != nil and tfHasAsgn in n.sym.typ.flags: diff --git a/tests/init/t25857.nim b/tests/init/t25857.nim new file mode 100644 index 0000000000..5e71481f5e --- /dev/null +++ b/tests/init/t25857.nim @@ -0,0 +1,19 @@ +discard """ + output: "1" +""" + +# Regression for #25857: `typeof(result)` inside `result`'s initializer must not be +# treated as a use-before-initialization of `result`. `typeof` is a type query and +# never evaluates its operand, so this compiles and runs. +# (Before the fix this errored: "'result' requires explicit initialization" on +# {.requiresInit.} return types, breaking the `ok(typeof(result), v)` idiom.) + +type Box[T] {.requiresInit.} = object + v: T + +func make[T](_: typedesc[Box[T]], v: T): Box[T] = Box[T](v: v) + +proc f(): Box[int] = + make(typeof(result), 1) + +echo f().v