Skip to content

Commit 5945ad4

Browse files
metagnnarimiran
authored andcommitted
reset inTypeofContext in generic instantiations (#24229)
fixes #24228, refs #22022 As described in #24228 (comment), instantiating generic routines inside `typeof` causes all code inside to be treated as being in a typeof context, and thus preventing compile time proc folding, causing issues when code is generated for the instantiated routine. Now, instantiated generic procs are treated as never being inside a `typeof` context. This is probably an arbitrary special case and more issues with the `typeof` behavior from #22022 are likely. Ideally this behavior would be removed but it's necessary to accomodate the current [proc `declval` in the package `stew`](status-im/nim-stew#190), at least without changes to `compileTime` that would either break other code (making it not eagerly fold by default) or still require a change in stew (adding an option to disable the eager folding). Alternatively we could also make the eager folding opt-in only for generic compileTime procs so that #22022 breaks nothing whatsoever, but a universal solution would be better. Edit: Done in #24230 via experimental switch (cherry picked from commit ea9811a)
1 parent 7f113dc commit 5945ad4

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

compiler/seminst.nim

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -371,7 +371,11 @@ proc generateInstance(c: PContext, fn: PSym, pt: LayeredIdTable,
371371
if c.instCounter > 50:
372372
globalError(c.config, info, "generic instantiation too nested")
373373
inc c.instCounter
374-
defer: dec c.instCounter
374+
let currentTypeofContext = c.inTypeofContext
375+
c.inTypeofContext = 0
376+
defer:
377+
dec c.instCounter
378+
c.inTypeofContext = currentTypeofContext
375379
# careful! we copy the whole AST including the possibly nil body!
376380
var n = copyTree(fn.ast)
377381
# NOTE: for access of private fields within generics from a different module

tests/vm/tgenericcompiletimeproc.nim

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,24 @@ block: # issue #24150, related regression
3434
discard compiles(y(w int))
3535
proc s(): int {.compileTime.} = discard
3636
discard s()
37+
38+
block: # issue #24228, also related regression
39+
proc d(_: static[string]) = discard $0
40+
proc m(_: static[string]) = d("")
41+
iterator v(): int {.closure.} =
42+
template a(n: untyped) =
43+
when typeof(n) is void:
44+
n
45+
else:
46+
n
47+
a(m(""))
48+
let _ = v
49+
50+
block: # issue #24228 simplified
51+
proc d[T]() =
52+
let x = $0
53+
proc v() =
54+
when typeof(d[string]()) is void:
55+
d[string]()
56+
v()
57+

0 commit comments

Comments
 (0)