Skip to content

Commit a507895

Browse files
committed
fix #13524: magics with untyped params (eg astToStr) now work inside generics
1 parent 1056f9e commit a507895

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

compiler/semgnrc.nim

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,14 @@ proc semGenericStmt(c: PContext, n: PNode,
226226
var mixinContext = false
227227
if s != nil:
228228
incl(s.flags, sfUsed)
229-
mixinContext = s.magic in {mDefined, mDefinedInScope, mCompiles}
229+
# more robust/future proof than:
230+
# mixinContext = s.magic in {mDefined, mDefinedInScope, mCompiles, mAstToStr}
231+
if s.magic != mNone and s.typ != nil:
232+
for i in 1..<s.typ.len:
233+
if s.typ[i].kind == tyUntyped:
234+
mixinContext = true
235+
break
236+
230237
let sc = symChoice(c, fn, s, if s.isMixedIn: scForceOpen else: scOpen)
231238
case s.kind
232239
of skMacro:
@@ -283,6 +290,10 @@ proc semGenericStmt(c: PContext, n: PNode,
283290
# is not exported and yet the generic 'threadProcWrapper' works correctly.
284291
let flags = if mixinContext: flags+{withinMixin} else: flags
285292
for i in first..<result.safeLen:
293+
let flags = if mixinContext: flags+{withinMixin} else: flags
294+
# instead, would be better to only set `withinMixin` for arguments of
295+
# kind tyUntyped, eg `if s.typ[i].kind == tyUntyped:`, however, this
296+
# currentl doesn't work
286297
result[i] = semGenericStmt(c, result[i], flags, ctx)
287298
of nkCurlyExpr:
288299
result = newNodeI(nkCall, n.info)

lib/system.nim

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1629,7 +1629,7 @@ else:
16291629
result[i+1] = y[i]
16301630

16311631

1632-
proc astToStr*[T](x: T): string {.magic: "AstToStr", noSideEffect.}
1632+
proc astToStr*(x: untyped): string {.magic: "AstToStr", noSideEffect.}
16331633
## Converts the AST of `x` into a string representation. This is very useful
16341634
## for debugging.
16351635

tests/generics/t13525.nim

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# https://github.com/nim-lang/Nim/issues/13524
2+
template fun(field): untyped = astToStr(field)
3+
proc test1(): string = fun(nonexistant1)
4+
proc test2[T](): string = fun(nonexistant2) # used to cause: Error: undeclared identifier: 'nonexistant2'
5+
doAssert test1() == "nonexistant1"
6+
doAssert test2[int]() == "nonexistant2"

0 commit comments

Comments
 (0)