[sugar] handle HiddenDeref in capture, error at CT if unsupported nnk (#20680)

* [sugar] handle HiddenDeref in capture, error at CT if unsupported nnk

Instead of running into trouble of the `.strVal` access failing, it's
better to error at CT.

* [tests] remove unnecessary import in test case

* improve ident extraction & extend test cases

* [tests] improve tests for `capture` of different types & act. check
This commit is contained in:
Vindaar 2022-11-10 21:42:53 +01:00 • committed by GitHub
commit cc2b0f0172
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 73 additions and 3 deletions

View file

@ -231,9 +231,19 @@ macro capture*(locals: varargs[typed], body: untyped): untyped {.since: (1, 1).}
let locals = if locals.len == 1 and locals[0].kind == nnkBracket: locals[0]
else: locals
for arg in locals:
if arg.strVal == "result":
error("The variable name cannot be `result`!", arg)
params.add(newIdentDefs(ident(arg.strVal), freshIdentNodes getTypeInst arg))
proc getIdent(n: NimNode): NimNode =
case n.kind
of nnkIdent, nnkSym:
let nStr = n.strVal
if nStr == "result":
error("The variable name cannot be `result`!", n)
result = ident(nStr)
of nnkHiddenDeref: result = n[0].getIdent()
else:
error("The argument to be captured `" & n.repr & "` is not a pure identifier. " &
"It is an unsupported `" & $n.kind & "` node.", n)
let argName = getIdent(arg)
params.add(newIdentDefs(argName, freshIdentNodes getTypeInst arg))
result = newNimNode(nnkCall)
result.add(newProc(newEmptyNode(), params, body, nnkLambda))
for arg in locals: result.add(arg)