underscored_calls.nim 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2020 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This is an internal helper module. Do not use.
  10. import macros
  11. proc underscoredCall(n, arg0: NimNode): NimNode =
  12. proc underscorePos(n: NimNode): int =
  13. for i in 1 ..< n.len:
  14. if n[i].eqIdent("_"): return i
  15. return 0
  16. if n.kind in nnkCallKinds:
  17. result = copyNimNode(n)
  18. result.add n[0]
  19. let u = underscorePos(n)
  20. for i in 1..u-1: result.add n[i]
  21. result.add arg0
  22. for i in u+1..n.len-1: result.add n[i]
  23. elif n.kind in {nnkAsgn, nnkExprEqExpr}:
  24. var field = n[0]
  25. if n[0].kind == nnkDotExpr and n[0][0].eqIdent("_"):
  26. # handle _.field = ...
  27. field = n[0][1]
  28. result = newDotExpr(arg0, field).newAssignment n[1]
  29. else:
  30. # handle e.g. 'x.dup(sort)'
  31. result = newNimNode(nnkCall, n)
  32. result.add n
  33. result.add arg0
  34. proc underscoredCalls*(result, calls, arg0: NimNode) =
  35. expectKind calls, {nnkArgList, nnkStmtList, nnkStmtListExpr}
  36. for call in calls:
  37. if call.kind in {nnkStmtList, nnkStmtListExpr}:
  38. underscoredCalls(result, call, arg0)
  39. else:
  40. result.add underscoredCall(call, arg0)