fixes a bug for 'dup' and 'with'; they can now handle nested statement lists that can result from macros

This commit is contained in:
Araq 2020-03-17 11:22:20 +01:00
commit b737bb4be0
3 changed files with 22 additions and 25 deletions

View file

@ -216,14 +216,7 @@ when (NimMajor, NimMinor) >= (1, 1):
result = newNimNode(nnkStmtListExpr, arg) result = newNimNode(nnkStmtListExpr, arg)
let tmp = genSym(nskVar, "dupResult") let tmp = genSym(nskVar, "dupResult")
result.add newVarStmt(tmp, arg) result.add newVarStmt(tmp, arg)
expectKind calls, nnkArgList underscoredCalls(result, calls, tmp)
let body =
if calls.len == 1 and calls[0].kind in {nnkStmtList, nnkStmtListExpr}:
calls[0]
else:
calls
for call in body:
result.add underscoredCall(call, tmp)
result.add tmp result.add tmp

View file

@ -12,21 +12,17 @@
import macros import macros
proc underscoredCall*(n, arg0: NimNode): NimNode = proc underscoredCall(n, arg0: NimNode): NimNode =
proc underscorePos(n: NimNode): int = proc underscorePos(n: NimNode): int =
for i in 1 ..< n.len: for i in 1 ..< n.len:
if n[i].eqIdent("_"): return i if n[i].eqIdent("_"): return i
return -1 return 0
if n.kind in nnkCallKinds: if n.kind in nnkCallKinds:
result = copyNimNode(n) result = copyNimNode(n)
result.add n[0] result.add n[0]
let u = underscorePos(n) let u = underscorePos(n)
if u < 0:
result.add arg0
for i in 1..n.len-1: result.add n[i]
else:
for i in 1..u-1: result.add n[i] for i in 1..u-1: result.add n[i]
result.add arg0 result.add arg0
for i in u+1..n.len-1: result.add n[i] for i in u+1..n.len-1: result.add n[i]
@ -36,3 +32,18 @@ proc underscoredCall*(n, arg0: NimNode): NimNode =
result.add n result.add n
result.add arg0 result.add arg0
proc underscoredCalls*(result, calls, arg0: NimNode) =
proc handleStmtList(result, n, arg0: NimNode) =
for a in n:
if a.kind in {nnkStmtList, nnkStmtListExpr}:
handleStmtList(result, a, arg0)
else:
result.add underscoredCall(a, arg0)
expectKind calls, nnkArgList
if calls.len == 1 and calls[0].kind in {nnkStmtList, nnkStmtListExpr}:
# the 'macro: body' syntax is used:
handleStmtList(result, calls[0], arg0)
else:
for call in calls:
result.add underscoredCall(call, arg0)

View file

@ -35,14 +35,7 @@ macro with*(arg: typed; calls: varargs[untyped]): untyped =
doAssert a == 43 doAssert a == 43
result = newNimNode(nnkStmtList, arg) result = newNimNode(nnkStmtList, arg)
expectKind calls, nnkArgList underscoredCalls(result, calls, arg)
let body =
if calls.len == 1 and calls[0].kind in {nnkStmtList, nnkStmtListExpr}:
calls[0]
else:
calls
for call in body:
result.add underscoredCall(call, arg)
when isMainModule: when isMainModule:
type type