genasts.nim 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. ## This module implements AST generation using captured variables for macros.
  2. import std/macros
  3. type GenAstOpt* = enum
  4. kDirtyTemplate,
  5. # When set, uses a dirty template in implementation of `genAst`. This
  6. # is occasionally useful as workaround for issues such as #8220, see
  7. # `strformat limitations <strformat.html#limitations>`_ for details.
  8. # Default is unset, to avoid hijacking of uncaptured local symbols by
  9. # symbols in caller scope.
  10. kNoNewLit,
  11. # don't call call newLit automatically in `genAst` capture parameters
  12. macro genAstOpt*(options: static set[GenAstOpt], args: varargs[untyped]): untyped =
  13. ## Accepts a list of captured variables `a=b` or `a` and a block and returns the
  14. ## AST that represents it. Local `{.inject.}` symbols (e.g. procs) are captured
  15. ## unless `kDirtyTemplate in options`.
  16. runnableExamples:
  17. # This example shows how one could write a simplified version of `unittest.check`.
  18. import std/[macros, strutils]
  19. macro check2(cond: bool): untyped =
  20. assert cond.kind == nnkInfix, "$# not implemented" % $cond.kind
  21. result = genAst(cond, s = repr(cond), lhs = cond[1], rhs = cond[2]):
  22. # each local symbol we access must be explicitly captured
  23. if not cond:
  24. raiseAssert "'$#'' failed: lhs: '$#', rhs: '$#'" % [s, $lhs, $rhs]
  25. let a = 3
  26. check2 a*2 == a+3
  27. if false: check2 a*2 < a+1 # would error with: 'a * 2 < a + 1'' failed: lhs: '6', rhs: '4'
  28. runnableExamples:
  29. # This example goes in more details about the capture semantics.
  30. macro fun(a: string, b: static bool): untyped =
  31. let c = 'z'
  32. var d = 11 # implicitly {.gensym.} and needs to be captured for use in `genAst`.
  33. proc localFun(): auto = 12 # implicitly {.inject.}, doesn't need to be captured.
  34. genAst(a, b, c = true):
  35. # `a`, `b` are captured explicitly, `c` is a local definition masking `c = 'z'`.
  36. const b2 = b # macro static param `b` is forwarded here as a static param.
  37. # `echo d` would give: `var not init` because `d` is not captured.
  38. (a & a, b, c, localFun()) # localFun can be called without capture.
  39. assert fun("ab", false) == ("abab", false, true, 12)
  40. let params = newTree(nnkFormalParams, newEmptyNode())
  41. let pragmas =
  42. if kDirtyTemplate in options:
  43. nnkPragma.newTree(ident"dirty")
  44. else:
  45. newEmptyNode()
  46. template newLitMaybe(a): untyped =
  47. when (a is type) or (typeof(a) is (proc | iterator | func | NimNode)):
  48. a # `proc` actually also covers template, macro
  49. else: newLit(a)
  50. # using `_` as workaround, see https://github.com/nim-lang/Nim/issues/2465#issuecomment-511076669
  51. let name = genSym(nskTemplate, "_fun")
  52. let call = newCall(name)
  53. for a in args[0..^2]:
  54. var varName: NimNode
  55. var varVal: NimNode
  56. case a.kind
  57. of nnkExprEqExpr:
  58. varName = a[0]
  59. varVal = a[1]
  60. of nnkIdent:
  61. varName = a
  62. varVal = a
  63. else: error("invalid argument kind: " & $a.kind, a)
  64. if kNoNewLit notin options: varVal = newCall(bindSym"newLitMaybe", varVal)
  65. params.add newTree(nnkIdentDefs, varName, newEmptyNode(), newEmptyNode())
  66. call.add varVal
  67. result = newStmtList()
  68. result.add nnkTemplateDef.newTree(
  69. name,
  70. newEmptyNode(),
  71. newEmptyNode(),
  72. params,
  73. pragmas,
  74. newEmptyNode(),
  75. args[^1])
  76. result.add newCall(bindSym"getAst", call)
  77. template genAst*(args: varargs[untyped]): untyped =
  78. ## Convenience wrapper around `genAstOpt`.
  79. genAstOpt({}, args)