macros.nim 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. include "system/inclrtl"
  10. import std/private/since
  11. when defined(nimPreviewSlimSystem):
  12. import std/[assertions, formatfloat]
  13. ## This module contains the interface to the compiler's abstract syntax
  14. ## tree (`AST`:idx:). Macros operate on this tree.
  15. ##
  16. ## See also:
  17. ## * `macros tutorial <tut3.html>`_
  18. ## * `macros section in Nim manual <manual.html#macros>`_
  19. ## .. include:: ../../doc/astspec.txt
  20. # If you look for the implementation of the magic symbol
  21. # ``{.magic: "Foo".}``, search for `mFoo` and `opcFoo`.
  22. type
  23. NimNodeKind* = enum
  24. nnkNone, nnkEmpty, nnkIdent, nnkSym,
  25. nnkType, nnkCharLit, nnkIntLit, nnkInt8Lit,
  26. nnkInt16Lit, nnkInt32Lit, nnkInt64Lit, nnkUIntLit, nnkUInt8Lit,
  27. nnkUInt16Lit, nnkUInt32Lit, nnkUInt64Lit, nnkFloatLit,
  28. nnkFloat32Lit, nnkFloat64Lit, nnkFloat128Lit, nnkStrLit, nnkRStrLit,
  29. nnkTripleStrLit, nnkNilLit, nnkComesFrom, nnkDotCall,
  30. nnkCommand, nnkCall, nnkCallStrLit, nnkInfix,
  31. nnkPrefix, nnkPostfix, nnkHiddenCallConv,
  32. nnkExprEqExpr,
  33. nnkExprColonExpr, nnkIdentDefs, nnkVarTuple,
  34. nnkPar, nnkObjConstr, nnkCurly, nnkCurlyExpr,
  35. nnkBracket, nnkBracketExpr, nnkPragmaExpr, nnkRange,
  36. nnkDotExpr, nnkCheckedFieldExpr, nnkDerefExpr, nnkIfExpr,
  37. nnkElifExpr, nnkElseExpr, nnkLambda, nnkDo, nnkAccQuoted,
  38. nnkTableConstr, nnkBind,
  39. nnkClosedSymChoice,
  40. nnkOpenSymChoice,
  41. nnkHiddenStdConv,
  42. nnkHiddenSubConv, nnkConv, nnkCast, nnkStaticExpr,
  43. nnkAddr, nnkHiddenAddr, nnkHiddenDeref, nnkObjDownConv,
  44. nnkObjUpConv, nnkChckRangeF, nnkChckRange64, nnkChckRange,
  45. nnkStringToCString, nnkCStringToString, nnkAsgn,
  46. nnkFastAsgn, nnkGenericParams, nnkFormalParams, nnkOfInherit,
  47. nnkImportAs, nnkProcDef, nnkMethodDef, nnkConverterDef,
  48. nnkMacroDef, nnkTemplateDef, nnkIteratorDef, nnkOfBranch,
  49. nnkElifBranch, nnkExceptBranch, nnkElse,
  50. nnkAsmStmt, nnkPragma, nnkPragmaBlock, nnkIfStmt, nnkWhenStmt,
  51. nnkForStmt, nnkParForStmt, nnkWhileStmt, nnkCaseStmt,
  52. nnkTypeSection, nnkVarSection, nnkLetSection, nnkConstSection,
  53. nnkConstDef, nnkTypeDef,
  54. nnkYieldStmt, nnkDefer, nnkTryStmt, nnkFinally, nnkRaiseStmt,
  55. nnkReturnStmt, nnkBreakStmt, nnkContinueStmt, nnkBlockStmt, nnkStaticStmt,
  56. nnkDiscardStmt, nnkStmtList,
  57. nnkImportStmt,
  58. nnkImportExceptStmt,
  59. nnkExportStmt,
  60. nnkExportExceptStmt,
  61. nnkFromStmt,
  62. nnkIncludeStmt,
  63. nnkBindStmt, nnkMixinStmt, nnkUsingStmt,
  64. nnkCommentStmt, nnkStmtListExpr, nnkBlockExpr,
  65. nnkStmtListType, nnkBlockType,
  66. nnkWith, nnkWithout,
  67. nnkTypeOfExpr, nnkObjectTy,
  68. nnkTupleTy, nnkTupleClassTy, nnkTypeClassTy, nnkStaticTy,
  69. nnkRecList, nnkRecCase, nnkRecWhen,
  70. nnkRefTy, nnkPtrTy, nnkVarTy,
  71. nnkConstTy, nnkOutTy,
  72. nnkDistinctTy,
  73. nnkProcTy,
  74. nnkIteratorTy, # iterator type
  75. nnkSinkAsgn,
  76. nnkEnumTy,
  77. nnkEnumFieldDef,
  78. nnkArgList, nnkPattern
  79. nnkHiddenTryStmt,
  80. nnkClosure,
  81. nnkGotoState,
  82. nnkState,
  83. nnkBreakState,
  84. nnkFuncDef,
  85. nnkTupleConstr,
  86. nnkError, ## erroneous AST node
  87. NimNodeKinds* = set[NimNodeKind]
  88. NimTypeKind* = enum # some types are no longer used, see ast.nim
  89. ntyNone, ntyBool, ntyChar, ntyEmpty,
  90. ntyAlias, ntyNil, ntyExpr, ntyStmt,
  91. ntyTypeDesc, ntyGenericInvocation, ntyGenericBody, ntyGenericInst,
  92. ntyGenericParam, ntyDistinct, ntyEnum, ntyOrdinal,
  93. ntyArray, ntyObject, ntyTuple, ntySet,
  94. ntyRange, ntyPtr, ntyRef, ntyVar,
  95. ntySequence, ntyProc, ntyPointer, ntyOpenArray,
  96. ntyString, ntyCString, ntyForward, ntyInt,
  97. ntyInt8, ntyInt16, ntyInt32, ntyInt64,
  98. ntyFloat, ntyFloat32, ntyFloat64, ntyFloat128,
  99. ntyUInt, ntyUInt8, ntyUInt16, ntyUInt32, ntyUInt64,
  100. ntyUnused0, ntyUnused1, ntyUnused2,
  101. ntyVarargs,
  102. ntyUncheckedArray,
  103. ntyError,
  104. ntyBuiltinTypeClass, ntyUserTypeClass, ntyUserTypeClassInst,
  105. ntyCompositeTypeClass, ntyInferred, ntyAnd, ntyOr, ntyNot,
  106. ntyAnything, ntyStatic, ntyFromExpr, ntyOptDeprecated, ntyVoid
  107. TNimTypeKinds* {.deprecated.} = set[NimTypeKind]
  108. NimSymKind* = enum
  109. nskUnknown, nskConditional, nskDynLib, nskParam,
  110. nskGenericParam, nskTemp, nskModule, nskType, nskVar, nskLet,
  111. nskConst, nskResult,
  112. nskProc, nskFunc, nskMethod, nskIterator,
  113. nskConverter, nskMacro, nskTemplate, nskField,
  114. nskEnumField, nskForVar, nskLabel,
  115. nskStub
  116. TNimSymKinds* {.deprecated.} = set[NimSymKind]
  117. const
  118. nnkMutableTy* {.deprecated.} = nnkOutTy
  119. nnkSharedTy* {.deprecated.} = nnkSinkAsgn
  120. type
  121. NimIdent* {.deprecated.} = object of RootObj
  122. ## Represents a Nim identifier in the AST. **Note**: This is only
  123. ## rarely useful, for identifier construction from a string
  124. ## use `ident"abc"`.
  125. NimSymObj = object # hidden
  126. NimSym* {.deprecated.} = ref NimSymObj
  127. ## Represents a Nim *symbol* in the compiler; a *symbol* is a looked-up
  128. ## *ident*.
  129. const
  130. nnkLiterals* = {nnkCharLit..nnkNilLit}
  131. nnkCallKinds* = {nnkCall, nnkInfix, nnkPrefix, nnkPostfix, nnkCommand,
  132. nnkCallStrLit}
  133. nnkPragmaCallKinds = {nnkExprColonExpr, nnkCall, nnkCallStrLit}
  134. {.push warnings: off.}
  135. proc toNimIdent*(s: string): NimIdent {.magic: "StrToIdent", noSideEffect, deprecated:
  136. "Deprecated since version 0.18.0: Use 'ident' or 'newIdentNode' instead.".}
  137. ## Constructs an identifier from the string `s`.
  138. proc `==`*(a, b: NimIdent): bool {.magic: "EqIdent", noSideEffect, deprecated:
  139. "Deprecated since version 0.18.1; Use '==' on 'NimNode' instead.".}
  140. ## Compares two Nim identifiers.
  141. proc `==`*(a, b: NimNode): bool {.magic: "EqNimrodNode", noSideEffect.}
  142. ## Compare two Nim nodes. Return true if nodes are structurally
  143. ## equivalent. This means two independently created nodes can be equal.
  144. proc `==`*(a, b: NimSym): bool {.magic: "EqNimrodNode", noSideEffect, deprecated:
  145. "Deprecated since version 0.18.1; Use '==(NimNode, NimNode)' instead.".}
  146. ## Compares two Nim symbols.
  147. {.pop.}
  148. proc sameType*(a, b: NimNode): bool {.magic: "SameNodeType", noSideEffect.} =
  149. ## Compares two Nim nodes' types. Return true if the types are the same,
  150. ## e.g. true when comparing alias with original type.
  151. discard
  152. proc len*(n: NimNode): int {.magic: "NLen", noSideEffect.}
  153. ## Returns the number of children of `n`.
  154. proc `[]`*(n: NimNode, i: int): NimNode {.magic: "NChild", noSideEffect.}
  155. ## Get `n`'s `i`'th child.
  156. proc `[]`*(n: NimNode, i: BackwardsIndex): NimNode = n[n.len - i.int]
  157. ## Get `n`'s `i`'th child.
  158. template `^^`(n: NimNode, i: untyped): untyped =
  159. (when i is BackwardsIndex: n.len - int(i) else: int(i))
  160. proc `[]`*[T, U: Ordinal](n: NimNode, x: HSlice[T, U]): seq[NimNode] =
  161. ## Slice operation for NimNode.
  162. ## Returns a seq of child of `n` who inclusive range `[n[x.a], n[x.b]]`.
  163. let xa = n ^^ x.a
  164. let L = (n ^^ x.b) - xa + 1
  165. result = newSeq[NimNode](L)
  166. for i in 0..<L:
  167. result[i] = n[i + xa]
  168. proc `[]=`*(n: NimNode, i: int, child: NimNode) {.magic: "NSetChild",
  169. noSideEffect.}
  170. ## Set `n`'s `i`'th child to `child`.
  171. proc `[]=`*(n: NimNode, i: BackwardsIndex, child: NimNode) =
  172. ## Set `n`'s `i`'th child to `child`.
  173. n[n.len - i.int] = child
  174. template `or`*(x, y: NimNode): NimNode =
  175. ## Evaluate `x` and when it is not an empty node, return
  176. ## it. Otherwise evaluate to `y`. Can be used to chain several
  177. ## expressions to get the first expression that is not empty.
  178. ## ```
  179. ## let node = mightBeEmpty() or mightAlsoBeEmpty() or fallbackNode
  180. ## ```
  181. let arg = x
  182. if arg != nil and arg.kind != nnkEmpty:
  183. arg
  184. else:
  185. y
  186. proc add*(father, child: NimNode): NimNode {.magic: "NAdd", discardable,
  187. noSideEffect.}
  188. ## Adds the `child` to the `father` node. Returns the
  189. ## father node so that calls can be nested.
  190. proc add*(father: NimNode, children: varargs[NimNode]): NimNode {.
  191. magic: "NAddMultiple", discardable, noSideEffect.}
  192. ## Adds each child of `children` to the `father` node.
  193. ## Returns the `father` node so that calls can be nested.
  194. proc del*(father: NimNode, idx = 0, n = 1) {.magic: "NDel", noSideEffect.}
  195. ## Deletes `n` children of `father` starting at index `idx`.
  196. proc kind*(n: NimNode): NimNodeKind {.magic: "NKind", noSideEffect.}
  197. ## Returns the `kind` of the node `n`.
  198. proc intVal*(n: NimNode): BiggestInt {.magic: "NIntVal", noSideEffect.}
  199. ## Returns an integer value from any integer literal or enum field symbol.
  200. proc floatVal*(n: NimNode): BiggestFloat {.magic: "NFloatVal", noSideEffect.}
  201. ## Returns a float from any floating point literal.
  202. proc symKind*(symbol: NimNode): NimSymKind {.magic: "NSymKind", noSideEffect.}
  203. proc getImpl*(symbol: NimNode): NimNode {.magic: "GetImpl", noSideEffect.}
  204. ## Returns a copy of the declaration of a symbol or `nil`.
  205. proc strVal*(n: NimNode): string {.magic: "NStrVal", noSideEffect.}
  206. ## Returns the string value of an identifier, symbol, comment, or string literal.
  207. ##
  208. ## See also:
  209. ## * `strVal= proc<#strVal=,NimNode,string>`_ for setting the string value.
  210. {.push warnings: off.} # silence `deprecated`
  211. proc ident*(n: NimNode): NimIdent {.magic: "NIdent", noSideEffect, deprecated:
  212. "Deprecated since version 0.18.1; All functionality is defined on 'NimNode'.".}
  213. proc symbol*(n: NimNode): NimSym {.magic: "NSymbol", noSideEffect, deprecated:
  214. "Deprecated since version 0.18.1; All functionality is defined on 'NimNode'.".}
  215. proc getImpl*(s: NimSym): NimNode {.magic: "GetImpl", noSideEffect, deprecated: "use `getImpl: NimNode -> NimNode` instead".}
  216. proc `$`*(i: NimIdent): string {.magic: "NStrVal", noSideEffect, deprecated:
  217. "Deprecated since version 0.18.1; Use 'strVal' instead.".}
  218. ## Converts a Nim identifier to a string.
  219. proc `$`*(s: NimSym): string {.magic: "NStrVal", noSideEffect, deprecated:
  220. "Deprecated since version 0.18.1; Use 'strVal' instead.".}
  221. ## Converts a Nim symbol to a string.
  222. {.pop.}
  223. when (NimMajor, NimMinor, NimPatch) >= (1, 3, 5) or defined(nimSymImplTransform):
  224. proc getImplTransformed*(symbol: NimNode): NimNode {.magic: "GetImplTransf", noSideEffect.}
  225. ## For a typed proc returns the AST after transformation pass; this is useful
  226. ## for debugging how the compiler transforms code (e.g.: `defer`, `for`) but
  227. ## note that code transformations are implementation dependent and subject to change.
  228. ## See an example in `tests/macros/tmacros_various.nim`.
  229. proc owner*(sym: NimNode): NimNode {.magic: "SymOwner", noSideEffect.}
  230. ## Accepts a node of kind `nnkSym` and returns its owner's symbol.
  231. ## The meaning of 'owner' depends on `sym`'s `NimSymKind` and declaration
  232. ## context. For top level declarations this is an `nskModule` symbol,
  233. ## for proc local variables an `nskProc` symbol, for enum/object fields an
  234. ## `nskType` symbol, etc. For symbols without an owner, `nil` is returned.
  235. ##
  236. ## See also:
  237. ## * `symKind proc<#symKind,NimNode>`_ to get the kind of a symbol
  238. ## * `getImpl proc<#getImpl,NimNode>`_ to get the declaration of a symbol
  239. proc isInstantiationOf*(instanceProcSym, genProcSym: NimNode): bool {.magic: "SymIsInstantiationOf", noSideEffect.}
  240. ## Checks if a proc symbol is an instance of the generic proc symbol.
  241. ## Useful to check proc symbols against generic symbols
  242. ## returned by `bindSym`.
  243. proc getType*(n: NimNode): NimNode {.magic: "NGetType", noSideEffect.}
  244. ## With 'getType' you can access the node's `type`:idx:. A Nim type is
  245. ## mapped to a Nim AST too, so it's slightly confusing but it means the same
  246. ## API can be used to traverse types. Recursive types are flattened for you
  247. ## so there is no danger of infinite recursions during traversal. To
  248. ## resolve recursive types, you have to call 'getType' again. To see what
  249. ## kind of type it is, call `typeKind` on getType's result.
  250. proc getType*(n: typedesc): NimNode {.magic: "NGetType", noSideEffect.}
  251. ## Version of `getType` which takes a `typedesc`.
  252. proc typeKind*(n: NimNode): NimTypeKind {.magic: "NGetType", noSideEffect.}
  253. ## Returns the type kind of the node 'n' that should represent a type, that
  254. ## means the node should have been obtained via `getType`.
  255. proc getTypeInst*(n: NimNode): NimNode {.magic: "NGetType", noSideEffect.} =
  256. ## Returns the `type`:idx: of a node in a form matching the way the
  257. ## type instance was declared in the code.
  258. runnableExamples:
  259. type
  260. Vec[N: static[int], T] = object
  261. arr: array[N, T]
  262. Vec4[T] = Vec[4, T]
  263. Vec4f = Vec4[float32]
  264. var a: Vec4f
  265. var b: Vec4[float32]
  266. var c: Vec[4, float32]
  267. macro dumpTypeInst(x: typed): untyped =
  268. newLit(x.getTypeInst.repr)
  269. doAssert(dumpTypeInst(a) == "Vec4f")
  270. doAssert(dumpTypeInst(b) == "Vec4[float32]")
  271. doAssert(dumpTypeInst(c) == "Vec[4, float32]")
  272. proc getTypeInst*(n: typedesc): NimNode {.magic: "NGetType", noSideEffect.}
  273. ## Version of `getTypeInst` which takes a `typedesc`.
  274. proc getTypeImpl*(n: NimNode): NimNode {.magic: "NGetType", noSideEffect.} =
  275. ## Returns the `type`:idx: of a node in a form matching the implementation
  276. ## of the type. Any intermediate aliases are expanded to arrive at the final
  277. ## type implementation. You can instead use `getImpl` on a symbol if you
  278. ## want to find the intermediate aliases.
  279. runnableExamples:
  280. type
  281. Vec[N: static[int], T] = object
  282. arr: array[N, T]
  283. Vec4[T] = Vec[4, T]
  284. Vec4f = Vec4[float32]
  285. var a: Vec4f
  286. var b: Vec4[float32]
  287. var c: Vec[4, float32]
  288. macro dumpTypeImpl(x: typed): untyped =
  289. newLit(x.getTypeImpl.repr)
  290. let t = """
  291. object
  292. arr: array[0 .. 3, float32]
  293. """
  294. doAssert(dumpTypeImpl(a) == t)
  295. doAssert(dumpTypeImpl(b) == t)
  296. doAssert(dumpTypeImpl(c) == t)
  297. proc signatureHash*(n: NimNode): string {.magic: "NSigHash", noSideEffect.}
  298. ## Returns a stable identifier derived from the signature of a symbol.
  299. ## The signature combines many factors such as the type of the symbol,
  300. ## the owning module of the symbol and others. The same identifier is
  301. ## used in the back-end to produce the mangled symbol name.
  302. proc symBodyHash*(s: NimNode): string {.noSideEffect.} =
  303. ## Returns a stable digest for symbols derived not only from type signature
  304. ## and owning module, but also implementation body. All procs/variables used in
  305. ## the implementation of this symbol are hashed recursively as well, including
  306. ## magics from system module.
  307. discard
  308. proc getTypeImpl*(n: typedesc): NimNode {.magic: "NGetType", noSideEffect.}
  309. ## Version of `getTypeImpl` which takes a `typedesc`.
  310. proc `intVal=`*(n: NimNode, val: BiggestInt) {.magic: "NSetIntVal", noSideEffect.}
  311. proc `floatVal=`*(n: NimNode, val: BiggestFloat) {.magic: "NSetFloatVal", noSideEffect.}
  312. {.push warnings: off.}
  313. proc `symbol=`*(n: NimNode, val: NimSym) {.magic: "NSetSymbol", noSideEffect, deprecated:
  314. "Deprecated since version 0.18.1; Generate a new 'NimNode' with 'genSym' instead.".}
  315. proc `ident=`*(n: NimNode, val: NimIdent) {.magic: "NSetIdent", noSideEffect, deprecated:
  316. "Deprecated since version 0.18.1; Generate a new 'NimNode' with 'ident(string)' instead.".}
  317. {.pop.}
  318. proc `strVal=`*(n: NimNode, val: string) {.magic: "NSetStrVal", noSideEffect.}
  319. ## Sets the string value of a string literal or comment.
  320. ## Setting `strVal` is disallowed for `nnkIdent` and `nnkSym` nodes; a new node
  321. ## must be created using `ident` or `bindSym` instead.
  322. ##
  323. ## See also:
  324. ## * `strVal proc<#strVal,NimNode>`_ for getting the string value.
  325. ## * `ident proc<#ident,string>`_ for creating an identifier.
  326. ## * `bindSym proc<#bindSym%2C%2CBindSymRule>`_ for binding a symbol.
  327. proc newNimNode*(kind: NimNodeKind,
  328. lineInfoFrom: NimNode = nil): NimNode
  329. {.magic: "NNewNimNode", noSideEffect.}
  330. ## Creates a new AST node of the specified kind.
  331. ##
  332. ## The `lineInfoFrom` parameter is used for line information when the
  333. ## produced code crashes. You should ensure that it is set to a node that
  334. ## you are transforming.
  335. proc copyNimNode*(n: NimNode): NimNode {.magic: "NCopyNimNode", noSideEffect.} =
  336. ## Creates a new AST node by copying the node `n`. Note that unlike `copyNimTree`,
  337. ## child nodes of `n` are not copied.
  338. runnableExamples:
  339. macro foo(x: typed) =
  340. var s = copyNimNode(x)
  341. doAssert s.len == 0
  342. doAssert s.kind == nnkStmtList
  343. foo:
  344. let x = 12
  345. echo x
  346. proc copyNimTree*(n: NimNode): NimNode {.magic: "NCopyNimTree", noSideEffect.} =
  347. ## Creates a new AST node by recursively copying the node `n`. Note that
  348. ## unlike `copyNimNode`, this copies `n`, the children of `n`, etc.
  349. runnableExamples:
  350. macro foo(x: typed) =
  351. var s = copyNimTree(x)
  352. doAssert s.len == 2
  353. doAssert s.kind == nnkStmtList
  354. foo:
  355. let x = 12
  356. echo x
  357. proc error*(msg: string, n: NimNode = nil) {.magic: "NError", benign.}
  358. ## Writes an error message at compile time. The optional `n: NimNode`
  359. ## parameter is used as the source for file and line number information in
  360. ## the compilation error message.
  361. proc warning*(msg: string, n: NimNode = nil) {.magic: "NWarning", benign.}
  362. ## Writes a warning message at compile time.
  363. proc hint*(msg: string, n: NimNode = nil) {.magic: "NHint", benign.}
  364. ## Writes a hint message at compile time.
  365. proc newStrLitNode*(s: string): NimNode {.noSideEffect.} =
  366. ## Creates a string literal node from `s`.
  367. result = newNimNode(nnkStrLit)
  368. result.strVal = s
  369. proc newCommentStmtNode*(s: string): NimNode {.noSideEffect.} =
  370. ## Creates a comment statement node.
  371. result = newNimNode(nnkCommentStmt)
  372. result.strVal = s
  373. proc newIntLitNode*(i: BiggestInt): NimNode =
  374. ## Creates an int literal node from `i`.
  375. result = newNimNode(nnkIntLit)
  376. result.intVal = i
  377. proc newFloatLitNode*(f: BiggestFloat): NimNode =
  378. ## Creates a float literal node from `f`.
  379. result = newNimNode(nnkFloatLit)
  380. result.floatVal = f
  381. {.push warnings: off.}
  382. proc newIdentNode*(i: NimIdent): NimNode {.deprecated: "use ident(string)".} =
  383. ## Creates an identifier node from `i`.
  384. result = newNimNode(nnkIdent)
  385. result.ident = i
  386. {.pop.}
  387. proc newIdentNode*(i: string): NimNode {.magic: "StrToIdent", noSideEffect.}
  388. ## Creates an identifier node from `i`. It is simply an alias for
  389. ## `ident(string)`. Use that, it's shorter.
  390. proc ident*(name: string): NimNode {.magic: "StrToIdent", noSideEffect.}
  391. ## Create a new ident node from a string.
  392. type
  393. BindSymRule* = enum ## Specifies how `bindSym` behaves. The difference
  394. ## between open and closed symbols can be found in
  395. ## `<manual.html#symbol-lookup-in-generics-open-and-closed-symbols>`_
  396. brClosed, ## only the symbols in current scope are bound
  397. brOpen, ## open for overloaded symbols, but may be a single
  398. ## symbol if not ambiguous (the rules match that of
  399. ## binding in generics)
  400. brForceOpen ## same as brOpen, but it will always be open even
  401. ## if not ambiguous (this cannot be achieved with
  402. ## any other means in the language currently)
  403. proc bindSym*(ident: string | NimNode, rule: BindSymRule = brClosed): NimNode {.
  404. magic: "NBindSym", noSideEffect.}
  405. ## Creates a node that binds `ident` to a symbol node. The bound symbol
  406. ## may be an overloaded symbol.
  407. ## if `ident` is a NimNode, it must have `nnkIdent` kind.
  408. ## If `rule == brClosed` either an `nnkClosedSymChoice` tree is
  409. ## returned or `nnkSym` if the symbol is not ambiguous.
  410. ## If `rule == brOpen` either an `nnkOpenSymChoice` tree is
  411. ## returned or `nnkSym` if the symbol is not ambiguous.
  412. ## If `rule == brForceOpen` always an `nnkOpenSymChoice` tree is
  413. ## returned even if the symbol is not ambiguous.
  414. ##
  415. ## See the `manual <manual.html#macros-bindsym>`_ for more details.
  416. proc genSym*(kind: NimSymKind = nskLet; ident = ""): NimNode {.
  417. magic: "NGenSym", noSideEffect.}
  418. ## Generates a fresh symbol that is guaranteed to be unique. The symbol
  419. ## needs to occur in a declaration context.
  420. proc callsite*(): NimNode {.magic: "NCallSite", benign, deprecated:
  421. "Deprecated since v0.18.1; use `varargs[untyped]` in the macro prototype instead".}
  422. ## Returns the AST of the invocation expression that invoked this macro.
  423. # see https://github.com/nim-lang/RFCs/issues/387 as candidate replacement.
  424. proc toStrLit*(n: NimNode): NimNode =
  425. ## Converts the AST `n` to the concrete Nim code and wraps that
  426. ## in a string literal node.
  427. return newStrLitNode(repr(n))
  428. type
  429. LineInfo* = object
  430. filename*: string
  431. line*,column*: int
  432. proc `$`*(arg: LineInfo): string =
  433. ## Return a string representation in the form `filepath(line, column)`.
  434. # BUG: without `result = `, gives compile error
  435. result = arg.filename & "(" & $arg.line & ", " & $arg.column & ")"
  436. #proc lineinfo*(n: NimNode): LineInfo {.magic: "NLineInfo", noSideEffect.}
  437. # ## returns the position the node appears in the original source file
  438. # ## in the form filename(line, col)
  439. proc getLine(arg: NimNode): int {.magic: "NLineInfo", noSideEffect.}
  440. proc getColumn(arg: NimNode): int {.magic: "NLineInfo", noSideEffect.}
  441. proc getFile(arg: NimNode): string {.magic: "NLineInfo", noSideEffect.}
  442. proc copyLineInfo*(arg: NimNode, info: NimNode) {.magic: "NLineInfo", noSideEffect.}
  443. ## Copy lineinfo from `info`.
  444. proc lineInfoObj*(n: NimNode): LineInfo =
  445. ## Returns `LineInfo` of `n`, using absolute path for `filename`.
  446. result = LineInfo(filename: n.getFile, line: n.getLine, column: n.getColumn)
  447. proc lineInfo*(arg: NimNode): string =
  448. ## Return line info in the form `filepath(line, column)`.
  449. $arg.lineInfoObj
  450. proc internalParseExpr(s, filename: string): NimNode {.
  451. magic: "ParseExprToAst", noSideEffect.}
  452. proc internalParseStmt(s, filename: string): NimNode {.
  453. magic: "ParseStmtToAst", noSideEffect.}
  454. proc internalErrorFlag*(): string {.magic: "NError", noSideEffect.}
  455. ## Some builtins set an error flag. This is then turned into a proper
  456. ## exception. **Note**: Ordinary application code should not call this.
  457. proc parseExpr*(s: string; filename: string = ""): NimNode {.noSideEffect.} =
  458. ## Compiles the passed string to its AST representation.
  459. ## Expects a single expression. Raises `ValueError` for parsing errors.
  460. ## A filename can be given for more informative errors.
  461. result = internalParseExpr(s, filename)
  462. let x = internalErrorFlag()
  463. if x.len > 0: raise newException(ValueError, x)
  464. proc parseStmt*(s: string; filename: string = ""): NimNode {.noSideEffect.} =
  465. ## Compiles the passed string to its AST representation.
  466. ## Expects one or more statements. Raises `ValueError` for parsing errors.
  467. ## A filename can be given for more informative errors.
  468. result = internalParseStmt(s, filename)
  469. let x = internalErrorFlag()
  470. if x.len > 0: raise newException(ValueError, x)
  471. proc getAst*(macroOrTemplate: untyped): NimNode {.magic: "ExpandToAst", noSideEffect.}
  472. ## Obtains the AST nodes returned from a macro or template invocation.
  473. ## See also `genasts.genAst`.
  474. ## Example:
  475. ## ```
  476. ## macro FooMacro() =
  477. ## var ast = getAst(BarTemplate())
  478. ## ```
  479. proc quote*(bl: typed, op = "``"): NimNode {.magic: "QuoteAst", noSideEffect.} =
  480. ## Quasi-quoting operator.
  481. ## Accepts an expression or a block and returns the AST that represents it.
  482. ## Within the quoted AST, you are able to interpolate NimNode expressions
  483. ## from the surrounding scope. If no operator is given, quoting is done using
  484. ## backticks. Otherwise, the given operator must be used as a prefix operator
  485. ## for any interpolated expression. The original meaning of the interpolation
  486. ## operator may be obtained by escaping it (by prefixing it with itself) when used
  487. ## as a unary operator:
  488. ## e.g. `@` is escaped as `@@`, `&%` is escaped as `&%&%` and so on; see examples.
  489. ##
  490. ## A custom operator interpolation needs accent quoted (``) whenever it resolves
  491. ## to a symbol.
  492. ##
  493. ## See also `genasts <genasts.html>`_ which avoids some issues with `quote`.
  494. runnableExamples:
  495. macro check(ex: untyped) =
  496. # this is a simplified version of the check macro from the
  497. # unittest module.
  498. # If there is a failed check, we want to make it easy for
  499. # the user to jump to the faulty line in the code, so we
  500. # get the line info here:
  501. var info = ex.lineinfo
  502. # We will also display the code string of the failed check:
  503. var expString = ex.toStrLit
  504. # Finally we compose the code to implement the check:
  505. result = quote do:
  506. if not `ex`:
  507. echo `info` & ": Check failed: " & `expString`
  508. check 1 + 1 == 2
  509. runnableExamples:
  510. # example showing how to define a symbol that requires backtick without
  511. # quoting it.
  512. var destroyCalled = false
  513. macro bar() =
  514. let s = newTree(nnkAccQuoted, ident"=destroy")
  515. # let s = ident"`=destroy`" # this would not work
  516. result = quote do:
  517. type Foo = object
  518. # proc `=destroy`(a: var Foo) = destroyCalled = true # this would not work
  519. proc `s`(a: var Foo) = destroyCalled = true
  520. block:
  521. let a = Foo()
  522. bar()
  523. doAssert destroyCalled
  524. runnableExamples:
  525. # custom `op`
  526. var destroyCalled = false
  527. macro bar(ident) =
  528. var x = 1.5
  529. result = quote("@") do:
  530. type Foo = object
  531. let `@ident` = 0 # custom op interpolated symbols need quoted (``)
  532. proc `=destroy`(a: var Foo) =
  533. doAssert @x == 1.5
  534. doAssert compiles(@x == 1.5)
  535. let b1 = @[1,2]
  536. let b2 = @@[1,2]
  537. doAssert $b1 == "[1, 2]"
  538. doAssert $b2 == "@[1, 2]"
  539. destroyCalled = true
  540. block:
  541. let a = Foo()
  542. bar(someident)
  543. doAssert destroyCalled
  544. proc `&%`(x: int): int = 1
  545. proc `&%`(x, y: int): int = 2
  546. macro bar2() =
  547. var x = 3
  548. result = quote("&%") do:
  549. var y = &%x # quoting operator
  550. doAssert &%&%y == 1 # unary operator => need to escape
  551. doAssert y &% y == 2 # binary operator => no need to escape
  552. doAssert y == 3
  553. bar2()
  554. proc expectKind*(n: NimNode, k: NimNodeKind) =
  555. ## Checks that `n` is of kind `k`. If this is not the case,
  556. ## compilation aborts with an error message. This is useful for writing
  557. ## macros that check the AST that is passed to them.
  558. if n.kind != k: error("Expected a node of kind " & $k & ", got " & $n.kind, n)
  559. proc expectMinLen*(n: NimNode, min: int) =
  560. ## Checks that `n` has at least `min` children. If this is not the case,
  561. ## compilation aborts with an error message. This is useful for writing
  562. ## macros that check its number of arguments.
  563. if n.len < min: error("Expected a node with at least " & $min & " children, got " & $n.len, n)
  564. proc expectLen*(n: NimNode, len: int) =
  565. ## Checks that `n` has exactly `len` children. If this is not the case,
  566. ## compilation aborts with an error message. This is useful for writing
  567. ## macros that check its number of arguments.
  568. if n.len != len: error("Expected a node with " & $len & " children, got " & $n.len, n)
  569. proc expectLen*(n: NimNode, min, max: int) =
  570. ## Checks that `n` has a number of children in the range `min..max`.
  571. ## If this is not the case, compilation aborts with an error message.
  572. ## This is useful for writing macros that check its number of arguments.
  573. if n.len < min or n.len > max:
  574. error("Expected a node with " & $min & ".." & $max & " children, got " & $n.len, n)
  575. proc newTree*(kind: NimNodeKind,
  576. children: varargs[NimNode]): NimNode =
  577. ## Produces a new node with children.
  578. result = newNimNode(kind)
  579. result.add(children)
  580. proc newCall*(theProc: NimNode, args: varargs[NimNode]): NimNode =
  581. ## Produces a new call node. `theProc` is the proc that is called with
  582. ## the arguments `args[0..]`.
  583. result = newNimNode(nnkCall)
  584. result.add(theProc)
  585. result.add(args)
  586. {.push warnings: off.}
  587. proc newCall*(theProc: NimIdent, args: varargs[NimNode]): NimNode {.deprecated:
  588. "Deprecated since v0.18.1; use 'newCall(string, ...)' or 'newCall(NimNode, ...)' instead".} =
  589. ## Produces a new call node. `theProc` is the proc that is called with
  590. ## the arguments `args[0..]`.
  591. result = newNimNode(nnkCall)
  592. result.add(newIdentNode(theProc))
  593. result.add(args)
  594. {.pop.}
  595. proc newCall*(theProc: string,
  596. args: varargs[NimNode]): NimNode =
  597. ## Produces a new call node. `theProc` is the proc that is called with
  598. ## the arguments `args[0..]`.
  599. result = newNimNode(nnkCall)
  600. result.add(newIdentNode(theProc))
  601. result.add(args)
  602. proc newLit*(c: char): NimNode =
  603. ## Produces a new character literal node.
  604. result = newNimNode(nnkCharLit)
  605. result.intVal = ord(c)
  606. proc newLit*(i: int): NimNode =
  607. ## Produces a new integer literal node.
  608. result = newNimNode(nnkIntLit)
  609. result.intVal = i
  610. proc newLit*(i: int8): NimNode =
  611. ## Produces a new integer literal node.
  612. result = newNimNode(nnkInt8Lit)
  613. result.intVal = i
  614. proc newLit*(i: int16): NimNode =
  615. ## Produces a new integer literal node.
  616. result = newNimNode(nnkInt16Lit)
  617. result.intVal = i
  618. proc newLit*(i: int32): NimNode =
  619. ## Produces a new integer literal node.
  620. result = newNimNode(nnkInt32Lit)
  621. result.intVal = i
  622. proc newLit*(i: int64): NimNode =
  623. ## Produces a new integer literal node.
  624. result = newNimNode(nnkInt64Lit)
  625. result.intVal = i
  626. proc newLit*(i: uint): NimNode =
  627. ## Produces a new unsigned integer literal node.
  628. result = newNimNode(nnkUIntLit)
  629. result.intVal = BiggestInt(i)
  630. proc newLit*(i: uint8): NimNode =
  631. ## Produces a new unsigned integer literal node.
  632. result = newNimNode(nnkUInt8Lit)
  633. result.intVal = BiggestInt(i)
  634. proc newLit*(i: uint16): NimNode =
  635. ## Produces a new unsigned integer literal node.
  636. result = newNimNode(nnkUInt16Lit)
  637. result.intVal = BiggestInt(i)
  638. proc newLit*(i: uint32): NimNode =
  639. ## Produces a new unsigned integer literal node.
  640. result = newNimNode(nnkUInt32Lit)
  641. result.intVal = BiggestInt(i)
  642. proc newLit*(i: uint64): NimNode =
  643. ## Produces a new unsigned integer literal node.
  644. result = newNimNode(nnkUInt64Lit)
  645. result.intVal = BiggestInt(i)
  646. proc newLit*(b: bool): NimNode =
  647. ## Produces a new boolean literal node.
  648. result = if b: bindSym"true" else: bindSym"false"
  649. proc newLit*(s: string): NimNode =
  650. ## Produces a new string literal node.
  651. result = newNimNode(nnkStrLit)
  652. result.strVal = s
  653. when false:
  654. # the float type is not really a distinct type as described in https://github.com/nim-lang/Nim/issues/5875
  655. proc newLit*(f: float): NimNode =
  656. ## Produces a new float literal node.
  657. result = newNimNode(nnkFloatLit)
  658. result.floatVal = f
  659. proc newLit*(f: float32): NimNode =
  660. ## Produces a new float literal node.
  661. result = newNimNode(nnkFloat32Lit)
  662. result.floatVal = f
  663. proc newLit*(f: float64): NimNode =
  664. ## Produces a new float literal node.
  665. result = newNimNode(nnkFloat64Lit)
  666. result.floatVal = f
  667. when declared(float128):
  668. proc newLit*(f: float128): NimNode =
  669. ## Produces a new float literal node.
  670. result = newNimNode(nnkFloat128Lit)
  671. result.floatVal = f
  672. proc newLit*(arg: enum): NimNode =
  673. result = newCall(
  674. arg.typeof.getTypeInst[1],
  675. newLit(int(arg))
  676. )
  677. proc newLit*[N,T](arg: array[N,T]): NimNode
  678. proc newLit*[T](arg: seq[T]): NimNode
  679. proc newLit*[T](s: set[T]): NimNode
  680. proc newLit*[T: tuple](arg: T): NimNode
  681. proc newLit*(arg: object): NimNode =
  682. result = nnkObjConstr.newTree(arg.typeof.getTypeInst[1])
  683. for a, b in arg.fieldPairs:
  684. result.add nnkExprColonExpr.newTree( newIdentNode(a), newLit(b) )
  685. proc newLit*(arg: ref object): NimNode =
  686. ## produces a new ref type literal node.
  687. result = nnkObjConstr.newTree(arg.typeof.getTypeInst[1])
  688. for a, b in fieldPairs(arg[]):
  689. result.add nnkExprColonExpr.newTree(newIdentNode(a), newLit(b))
  690. proc newLit*[N,T](arg: array[N,T]): NimNode =
  691. result = nnkBracket.newTree
  692. for x in arg:
  693. result.add newLit(x)
  694. proc newLit*[T](arg: seq[T]): NimNode =
  695. let bracket = nnkBracket.newTree
  696. for x in arg:
  697. bracket.add newLit(x)
  698. result = nnkPrefix.newTree(
  699. bindSym"@",
  700. bracket
  701. )
  702. if arg.len == 0:
  703. # add type cast for empty seq
  704. var typ = getTypeInst(typeof(arg))[1]
  705. result = newCall(typ,result)
  706. proc newLit*[T](s: set[T]): NimNode =
  707. result = nnkCurly.newTree
  708. for x in s:
  709. result.add newLit(x)
  710. if result.len == 0:
  711. # add type cast for empty set
  712. var typ = getTypeInst(typeof(s))[1]
  713. result = newCall(typ,result)
  714. proc isNamedTuple(T: typedesc): bool {.magic: "TypeTrait".}
  715. ## See `typetraits.isNamedTuple`
  716. proc newLit*[T: tuple](arg: T): NimNode =
  717. ## use -d:nimHasWorkaround14720 to restore behavior prior to PR, forcing
  718. ## a named tuple even when `arg` is unnamed.
  719. result = nnkTupleConstr.newTree
  720. when defined(nimHasWorkaround14720) or isNamedTuple(T):
  721. for a, b in arg.fieldPairs:
  722. result.add nnkExprColonExpr.newTree(newIdentNode(a), newLit(b))
  723. else:
  724. for b in arg.fields:
  725. result.add newLit(b)
  726. proc nestList*(op: NimNode; pack: NimNode): NimNode =
  727. ## Nests the list `pack` into a tree of call expressions:
  728. ## `[a, b, c]` is transformed into `op(a, op(c, d))`.
  729. ## This is also known as fold expression.
  730. if pack.len < 1:
  731. error("`nestList` expects a node with at least 1 child")
  732. result = pack[^1]
  733. for i in countdown(pack.len - 2, 0):
  734. result = newCall(op, pack[i], result)
  735. proc nestList*(op: NimNode; pack: NimNode; init: NimNode): NimNode =
  736. ## Nests the list `pack` into a tree of call expressions:
  737. ## `[a, b, c]` is transformed into `op(a, op(c, d))`.
  738. ## This is also known as fold expression.
  739. result = init
  740. for i in countdown(pack.len - 1, 0):
  741. result = newCall(op, pack[i], result)
  742. proc eqIdent*(a: string; b: string): bool {.magic: "EqIdent", noSideEffect.}
  743. ## Style insensitive comparison.
  744. proc eqIdent*(a: NimNode; b: string): bool {.magic: "EqIdent", noSideEffect.}
  745. ## Style insensitive comparison. `a` can be an identifier or a
  746. ## symbol. `a` may be wrapped in an export marker
  747. ## (`nnkPostfix`) or quoted with backticks (`nnkAccQuoted`),
  748. ## these nodes will be unwrapped.
  749. proc eqIdent*(a: string; b: NimNode): bool {.magic: "EqIdent", noSideEffect.}
  750. ## Style insensitive comparison. `b` can be an identifier or a
  751. ## symbol. `b` may be wrapped in an export marker
  752. ## (`nnkPostfix`) or quoted with backticks (`nnkAccQuoted`),
  753. ## these nodes will be unwrapped.
  754. proc eqIdent*(a: NimNode; b: NimNode): bool {.magic: "EqIdent", noSideEffect.}
  755. ## Style insensitive comparison. `a` and `b` can be an
  756. ## identifier or a symbol. Both may be wrapped in an export marker
  757. ## (`nnkPostfix`) or quoted with backticks (`nnkAccQuoted`),
  758. ## these nodes will be unwrapped.
  759. const collapseSymChoice = not defined(nimLegacyMacrosCollapseSymChoice)
  760. proc treeTraverse(n: NimNode; res: var string; level = 0; isLisp = false, indented = false) {.benign.} =
  761. if level > 0:
  762. if indented:
  763. res.add("\n")
  764. for i in 0 .. level-1:
  765. if isLisp:
  766. res.add(" ") # dumpLisp indentation
  767. else:
  768. res.add(" ") # dumpTree indentation
  769. else:
  770. res.add(" ")
  771. if isLisp:
  772. res.add("(")
  773. res.add(($n.kind).substr(3))
  774. case n.kind
  775. of nnkEmpty, nnkNilLit:
  776. discard # same as nil node in this representation
  777. of nnkCharLit .. nnkInt64Lit:
  778. res.add(" " & $n.intVal)
  779. of nnkFloatLit .. nnkFloat64Lit:
  780. res.add(" " & $n.floatVal)
  781. of nnkStrLit .. nnkTripleStrLit, nnkCommentStmt, nnkIdent, nnkSym:
  782. res.add(" " & $n.strVal.newLit.repr)
  783. of nnkNone:
  784. assert false
  785. elif n.kind in {nnkOpenSymChoice, nnkClosedSymChoice} and collapseSymChoice:
  786. res.add(" " & $n.len)
  787. if n.len > 0:
  788. var allSameSymName = true
  789. for i in 0..<n.len:
  790. if n[i].kind != nnkSym or not eqIdent(n[i], n[0]):
  791. allSameSymName = false
  792. break
  793. if allSameSymName:
  794. res.add(" " & $n[0].strVal.newLit.repr)
  795. else:
  796. for j in 0 ..< n.len:
  797. n[j].treeTraverse(res, level+1, isLisp, indented)
  798. else:
  799. for j in 0 ..< n.len:
  800. n[j].treeTraverse(res, level+1, isLisp, indented)
  801. if isLisp:
  802. res.add(")")
  803. proc treeRepr*(n: NimNode): string {.benign.} =
  804. ## Convert the AST `n` to a human-readable tree-like string.
  805. ##
  806. ## See also `repr`, `lispRepr`_, and `astGenRepr`_.
  807. result = ""
  808. n.treeTraverse(result, isLisp = false, indented = true)
  809. proc lispRepr*(n: NimNode; indented = false): string {.benign.} =
  810. ## Convert the AST `n` to a human-readable lisp-like string.
  811. ##
  812. ## See also `repr`, `treeRepr`_, and `astGenRepr`_.
  813. result = ""
  814. n.treeTraverse(result, isLisp = true, indented = indented)
  815. proc astGenRepr*(n: NimNode): string {.benign.} =
  816. ## Convert the AST `n` to the code required to generate that AST.
  817. ##
  818. ## See also `repr`_, `treeRepr`_, and `lispRepr`_.
  819. const
  820. NodeKinds = {nnkEmpty, nnkIdent, nnkSym, nnkNone, nnkCommentStmt}
  821. LitKinds = {nnkCharLit..nnkInt64Lit, nnkFloatLit..nnkFloat64Lit, nnkStrLit..nnkTripleStrLit}
  822. proc traverse(res: var string, level: int, n: NimNode) {.benign.} =
  823. for i in 0..level-1: res.add " "
  824. if n.kind in NodeKinds:
  825. res.add("new" & ($n.kind).substr(3) & "Node(")
  826. elif n.kind in LitKinds:
  827. res.add("newLit(")
  828. elif n.kind == nnkNilLit:
  829. res.add("newNilLit()")
  830. else:
  831. res.add($n.kind)
  832. case n.kind
  833. of nnkEmpty, nnkNilLit: discard
  834. of nnkCharLit: res.add("'" & $chr(n.intVal) & "'")
  835. of nnkIntLit..nnkInt64Lit: res.add($n.intVal)
  836. of nnkFloatLit..nnkFloat64Lit: res.add($n.floatVal)
  837. of nnkStrLit..nnkTripleStrLit, nnkCommentStmt, nnkIdent, nnkSym:
  838. res.add(n.strVal.newLit.repr)
  839. of nnkNone: assert false
  840. elif n.kind in {nnkOpenSymChoice, nnkClosedSymChoice} and collapseSymChoice:
  841. res.add(", # unrepresentable symbols: " & $n.len)
  842. if n.len > 0:
  843. res.add(" " & n[0].strVal.newLit.repr)
  844. else:
  845. res.add(".newTree(")
  846. for j in 0..<n.len:
  847. res.add "\n"
  848. traverse(res, level + 1, n[j])
  849. if j != n.len-1:
  850. res.add(",")
  851. res.add("\n")
  852. for i in 0..level-1: res.add " "
  853. res.add(")")
  854. if n.kind in NodeKinds+LitKinds:
  855. res.add(")")
  856. result = ""
  857. traverse(result, 0, n)
  858. macro dumpTree*(s: untyped): untyped = echo s.treeRepr
  859. ## Accepts a block of nim code and prints the parsed abstract syntax
  860. ## tree using the `treeRepr` proc. Printing is done *at compile time*.
  861. ##
  862. ## You can use this as a tool to explore the Nim's abstract syntax
  863. ## tree and to discover what kind of nodes must be created to represent
  864. ## a certain expression/statement.
  865. ##
  866. ## For example:
  867. ## ```
  868. ## dumpTree:
  869. ## echo "Hello, World!"
  870. ## ```
  871. ##
  872. ## Outputs:
  873. ## ```
  874. ## StmtList
  875. ## Command
  876. ## Ident "echo"
  877. ## StrLit "Hello, World!"
  878. ## ```
  879. ##
  880. ## Also see `dumpAstGen` and `dumpLisp`.
  881. macro dumpLisp*(s: untyped): untyped = echo s.lispRepr(indented = true)
  882. ## Accepts a block of nim code and prints the parsed abstract syntax
  883. ## tree using the `lispRepr` proc. Printing is done *at compile time*.
  884. ##
  885. ## You can use this as a tool to explore the Nim's abstract syntax
  886. ## tree and to discover what kind of nodes must be created to represent
  887. ## a certain expression/statement.
  888. ##
  889. ## For example:
  890. ## ```
  891. ## dumpLisp:
  892. ## echo "Hello, World!"
  893. ## ```
  894. ##
  895. ## Outputs:
  896. ## ```
  897. ## (StmtList
  898. ## (Command
  899. ## (Ident "echo")
  900. ## (StrLit "Hello, World!")))
  901. ## ```
  902. ##
  903. ## Also see `dumpAstGen` and `dumpTree`.
  904. macro dumpAstGen*(s: untyped): untyped = echo s.astGenRepr
  905. ## Accepts a block of nim code and prints the parsed abstract syntax
  906. ## tree using the `astGenRepr` proc. Printing is done *at compile time*.
  907. ##
  908. ## You can use this as a tool to write macros quicker by writing example
  909. ## outputs and then copying the snippets into the macro for modification.
  910. ##
  911. ## For example:
  912. ## ```
  913. ## dumpAstGen:
  914. ## echo "Hello, World!"
  915. ## ```
  916. ##
  917. ## Outputs:
  918. ## ```
  919. ## nnkStmtList.newTree(
  920. ## nnkCommand.newTree(
  921. ## newIdentNode("echo"),
  922. ## newLit("Hello, World!")
  923. ## )
  924. ## )
  925. ## ```
  926. ##
  927. ## Also see `dumpTree` and `dumpLisp`.
  928. proc newEmptyNode*(): NimNode {.noSideEffect.} =
  929. ## Create a new empty node.
  930. result = newNimNode(nnkEmpty)
  931. proc newStmtList*(stmts: varargs[NimNode]): NimNode =
  932. ## Create a new statement list.
  933. result = newNimNode(nnkStmtList).add(stmts)
  934. proc newPar*(exprs: NimNode): NimNode =
  935. ## Create a new parentheses-enclosed expression.
  936. newNimNode(nnkPar).add(exprs)
  937. proc newPar*(exprs: varargs[NimNode]): NimNode {.deprecated:
  938. "don't use newPar/nnkPar to construct tuple expressions; use nnkTupleConstr instead".} =
  939. ## Create a new parentheses-enclosed expression.
  940. newNimNode(nnkPar).add(exprs)
  941. proc newBlockStmt*(label, body: NimNode): NimNode =
  942. ## Create a new block statement with label.
  943. return newNimNode(nnkBlockStmt).add(label, body)
  944. proc newBlockStmt*(body: NimNode): NimNode =
  945. ## Create a new block: stmt.
  946. return newNimNode(nnkBlockStmt).add(newEmptyNode(), body)
  947. proc newVarStmt*(name, value: NimNode): NimNode =
  948. ## Create a new var stmt.
  949. return newNimNode(nnkVarSection).add(
  950. newNimNode(nnkIdentDefs).add(name, newNimNode(nnkEmpty), value))
  951. proc newLetStmt*(name, value: NimNode): NimNode =
  952. ## Create a new let stmt.
  953. return newNimNode(nnkLetSection).add(
  954. newNimNode(nnkIdentDefs).add(name, newNimNode(nnkEmpty), value))
  955. proc newConstStmt*(name, value: NimNode): NimNode =
  956. ## Create a new const stmt.
  957. newNimNode(nnkConstSection).add(
  958. newNimNode(nnkConstDef).add(name, newNimNode(nnkEmpty), value))
  959. proc newAssignment*(lhs, rhs: NimNode): NimNode =
  960. return newNimNode(nnkAsgn).add(lhs, rhs)
  961. proc newDotExpr*(a, b: NimNode): NimNode =
  962. ## Create new dot expression.
  963. ## a.dot(b) -> `a.b`
  964. return newNimNode(nnkDotExpr).add(a, b)
  965. proc newColonExpr*(a, b: NimNode): NimNode =
  966. ## Create new colon expression.
  967. ## newColonExpr(a, b) -> `a: b`
  968. newNimNode(nnkExprColonExpr).add(a, b)
  969. proc newIdentDefs*(name, kind: NimNode;
  970. default = newEmptyNode()): NimNode =
  971. ## Creates a new `nnkIdentDefs` node of a specific kind and value.
  972. ##
  973. ## `nnkIdentDefs` need to have at least three children, but they can have
  974. ## more: first comes a list of identifiers followed by a type and value
  975. ## nodes. This helper proc creates a three node subtree, the first subnode
  976. ## being a single identifier name. Both the `kind` node and `default`
  977. ## (value) nodes may be empty depending on where the `nnkIdentDefs`
  978. ## appears: tuple or object definitions will have an empty `default` node,
  979. ## `let` or `var` blocks may have an empty `kind` node if the
  980. ## identifier is being assigned a value. Example:
  981. ##
  982. ## ```
  983. ## var varSection = newNimNode(nnkVarSection).add(
  984. ## newIdentDefs(ident("a"), ident("string")),
  985. ## newIdentDefs(ident("b"), newEmptyNode(), newLit(3)))
  986. ## # --> var
  987. ## # a: string
  988. ## # b = 3
  989. ## ```
  990. ##
  991. ## If you need to create multiple identifiers you need to use the lower level
  992. ## `newNimNode`:
  993. ## ```
  994. ## result = newNimNode(nnkIdentDefs).add(
  995. ## ident("a"), ident("b"), ident("c"), ident("string"),
  996. ## newStrLitNode("Hello"))
  997. ## ```
  998. newNimNode(nnkIdentDefs).add(name, kind, default)
  999. proc newNilLit*(): NimNode =
  1000. ## New nil literal shortcut.
  1001. result = newNimNode(nnkNilLit)
  1002. proc last*(node: NimNode): NimNode = node[node.len-1]
  1003. ## Return the last item in nodes children. Same as `node[^1]`.
  1004. const
  1005. RoutineNodes* = {nnkProcDef, nnkFuncDef, nnkMethodDef, nnkDo, nnkLambda,
  1006. nnkIteratorDef, nnkTemplateDef, nnkConverterDef, nnkMacroDef}
  1007. AtomicNodes* = {nnkNone..nnkNilLit}
  1008. CallNodes* = {nnkCall, nnkInfix, nnkPrefix, nnkPostfix, nnkCommand,
  1009. nnkCallStrLit, nnkHiddenCallConv}
  1010. proc expectKind*(n: NimNode; k: set[NimNodeKind]) =
  1011. ## Checks that `n` is of kind `k`. If this is not the case,
  1012. ## compilation aborts with an error message. This is useful for writing
  1013. ## macros that check the AST that is passed to them.
  1014. if n.kind notin k: error("Expected one of " & $k & ", got " & $n.kind, n)
  1015. proc newProc*(name = newEmptyNode();
  1016. params: openArray[NimNode] = [newEmptyNode()];
  1017. body: NimNode = newStmtList();
  1018. procType = nnkProcDef;
  1019. pragmas: NimNode = newEmptyNode()): NimNode =
  1020. ## Shortcut for creating a new proc.
  1021. ##
  1022. ## The `params` array must start with the return type of the proc,
  1023. ## followed by a list of IdentDefs which specify the params.
  1024. if procType notin RoutineNodes:
  1025. error("Expected one of " & $RoutineNodes & ", got " & $procType)
  1026. pragmas.expectKind({nnkEmpty, nnkPragma})
  1027. result = newNimNode(procType).add(
  1028. name,
  1029. newEmptyNode(),
  1030. newEmptyNode(),
  1031. newNimNode(nnkFormalParams).add(params),
  1032. pragmas,
  1033. newEmptyNode(),
  1034. body)
  1035. proc newIfStmt*(branches: varargs[tuple[cond, body: NimNode]]): NimNode =
  1036. ## Constructor for `if` statements.
  1037. ## ```
  1038. ## newIfStmt(
  1039. ## (Ident, StmtList),
  1040. ## ...
  1041. ## )
  1042. ## ```
  1043. result = newNimNode(nnkIfStmt)
  1044. if len(branches) < 1:
  1045. error("If statement must have at least one branch")
  1046. for i in branches:
  1047. result.add(newTree(nnkElifBranch, i.cond, i.body))
  1048. proc newEnum*(name: NimNode, fields: openArray[NimNode],
  1049. public, pure: bool): NimNode =
  1050. ## Creates a new enum. `name` must be an ident. Fields are allowed to be
  1051. ## either idents or EnumFieldDef:
  1052. ## ```
  1053. ## newEnum(
  1054. ## name = ident("Colors"),
  1055. ## fields = [ident("Blue"), ident("Red")],
  1056. ## public = true, pure = false)
  1057. ##
  1058. ## # type Colors* = Blue Red
  1059. ## ```
  1060. expectKind name, nnkIdent
  1061. if len(fields) < 1:
  1062. error("Enum must contain at least one field")
  1063. for field in fields:
  1064. expectKind field, {nnkIdent, nnkEnumFieldDef}
  1065. let enumBody = newNimNode(nnkEnumTy).add(newEmptyNode()).add(fields)
  1066. var typeDefArgs = [name, newEmptyNode(), enumBody]
  1067. if public:
  1068. let postNode = newNimNode(nnkPostfix).add(
  1069. newIdentNode("*"), typeDefArgs[0])
  1070. typeDefArgs[0] = postNode
  1071. if pure:
  1072. let pragmaNode = newNimNode(nnkPragmaExpr).add(
  1073. typeDefArgs[0],
  1074. add(newNimNode(nnkPragma), newIdentNode("pure")))
  1075. typeDefArgs[0] = pragmaNode
  1076. let
  1077. typeDef = add(newNimNode(nnkTypeDef), typeDefArgs)
  1078. typeSect = add(newNimNode(nnkTypeSection), typeDef)
  1079. return typeSect
  1080. proc copyChildrenTo*(src, dest: NimNode) =
  1081. ## Copy all children from `src` to `dest`.
  1082. for i in 0 ..< src.len:
  1083. dest.add src[i].copyNimTree
  1084. template expectRoutine(node: NimNode) =
  1085. expectKind(node, RoutineNodes)
  1086. proc name*(someProc: NimNode): NimNode =
  1087. someProc.expectRoutine
  1088. result = someProc[0]
  1089. if result.kind == nnkPostfix:
  1090. if result[1].kind == nnkAccQuoted:
  1091. result = result[1][0]
  1092. else:
  1093. result = result[1]
  1094. elif result.kind == nnkAccQuoted:
  1095. result = result[0]
  1096. proc `name=`*(someProc: NimNode; val: NimNode) =
  1097. someProc.expectRoutine
  1098. if someProc[0].kind == nnkPostfix:
  1099. someProc[0][1] = val
  1100. else: someProc[0] = val
  1101. proc params*(someProc: NimNode): NimNode =
  1102. if someProc.kind == nnkProcTy:
  1103. someProc[0]
  1104. else:
  1105. someProc.expectRoutine
  1106. someProc[3]
  1107. proc `params=`* (someProc: NimNode; params: NimNode) =
  1108. expectKind(params, nnkFormalParams)
  1109. if someProc.kind == nnkProcTy:
  1110. someProc[0] = params
  1111. else:
  1112. someProc.expectRoutine
  1113. someProc[3] = params
  1114. proc pragma*(someProc: NimNode): NimNode =
  1115. ## Get the pragma of a proc type.
  1116. ## These will be expanded.
  1117. if someProc.kind == nnkProcTy:
  1118. result = someProc[1]
  1119. else:
  1120. someProc.expectRoutine
  1121. result = someProc[4]
  1122. proc `pragma=`*(someProc: NimNode; val: NimNode) =
  1123. ## Set the pragma of a proc type.
  1124. expectKind(val, {nnkEmpty, nnkPragma})
  1125. if someProc.kind == nnkProcTy:
  1126. someProc[1] = val
  1127. else:
  1128. someProc.expectRoutine
  1129. someProc[4] = val
  1130. proc addPragma*(someProc, pragma: NimNode) =
  1131. ## Adds pragma to routine definition.
  1132. someProc.expectKind(RoutineNodes + {nnkProcTy})
  1133. var pragmaNode = someProc.pragma
  1134. if pragmaNode.isNil or pragmaNode.kind == nnkEmpty:
  1135. pragmaNode = newNimNode(nnkPragma)
  1136. someProc.pragma = pragmaNode
  1137. pragmaNode.add(pragma)
  1138. template badNodeKind(n, f) =
  1139. error("Invalid node kind " & $n.kind & " for macros.`" & $f & "`", n)
  1140. proc body*(someProc: NimNode): NimNode =
  1141. case someProc.kind:
  1142. of RoutineNodes:
  1143. return someProc[6]
  1144. of nnkBlockStmt, nnkWhileStmt:
  1145. return someProc[1]
  1146. of nnkForStmt:
  1147. return someProc.last
  1148. else:
  1149. badNodeKind someProc, "body"
  1150. proc `body=`*(someProc: NimNode, val: NimNode) =
  1151. case someProc.kind
  1152. of RoutineNodes:
  1153. someProc[6] = val
  1154. of nnkBlockStmt, nnkWhileStmt:
  1155. someProc[1] = val
  1156. of nnkForStmt:
  1157. someProc[len(someProc)-1] = val
  1158. else:
  1159. badNodeKind someProc, "body="
  1160. proc basename*(a: NimNode): NimNode =
  1161. ## Pull an identifier from prefix/postfix expressions.
  1162. case a.kind
  1163. of nnkIdent: result = a
  1164. of nnkPostfix, nnkPrefix: result = a[1]
  1165. of nnkPragmaExpr: result = basename(a[0])
  1166. else:
  1167. error("Do not know how to get basename of (" & treeRepr(a) & ")\n" &
  1168. repr(a), a)
  1169. proc `$`*(node: NimNode): string =
  1170. ## Get the string of an identifier node.
  1171. case node.kind
  1172. of nnkPostfix:
  1173. result = node.basename.strVal & "*"
  1174. of nnkStrLit..nnkTripleStrLit, nnkCommentStmt, nnkSym, nnkIdent:
  1175. result = node.strVal
  1176. of nnkOpenSymChoice, nnkClosedSymChoice:
  1177. result = $node[0]
  1178. of nnkAccQuoted:
  1179. result = ""
  1180. for i in 0 ..< node.len:
  1181. result.add(repr(node[i]))
  1182. else:
  1183. badNodeKind node, "$"
  1184. iterator items*(n: NimNode): NimNode {.inline.} =
  1185. ## Iterates over the children of the NimNode `n`.
  1186. for i in 0 ..< n.len:
  1187. yield n[i]
  1188. iterator pairs*(n: NimNode): (int, NimNode) {.inline.} =
  1189. ## Iterates over the children of the NimNode `n` and its indices.
  1190. for i in 0 ..< n.len:
  1191. yield (i, n[i])
  1192. iterator children*(n: NimNode): NimNode {.inline.} =
  1193. ## Iterates over the children of the NimNode `n`.
  1194. for i in 0 ..< n.len:
  1195. yield n[i]
  1196. template findChild*(n: NimNode; cond: untyped): NimNode {.dirty.} =
  1197. ## Find the first child node matching condition (or nil).
  1198. ## ```
  1199. ## var res = findChild(n, it.kind == nnkPostfix and
  1200. ## it.basename.ident == ident"foo")
  1201. ## ```
  1202. block:
  1203. var res: NimNode
  1204. for it in n.children:
  1205. if cond:
  1206. res = it
  1207. break
  1208. res
  1209. proc insert*(a: NimNode; pos: int; b: NimNode) =
  1210. ## Insert node `b` into node `a` at `pos`.
  1211. if len(a)-1 < pos:
  1212. # add some empty nodes first
  1213. for i in len(a)-1..pos-2:
  1214. a.add newEmptyNode()
  1215. a.add b
  1216. else:
  1217. # push the last item onto the list again
  1218. # and shift each item down to pos up one
  1219. a.add(a[a.len-1])
  1220. for i in countdown(len(a) - 3, pos):
  1221. a[i + 1] = a[i]
  1222. a[pos] = b
  1223. proc `basename=`*(a: NimNode; val: string) =
  1224. case a.kind
  1225. of nnkIdent:
  1226. a.strVal = val
  1227. of nnkPostfix, nnkPrefix:
  1228. a[1] = ident(val)
  1229. of nnkPragmaExpr: `basename=`(a[0], val)
  1230. else:
  1231. error("Do not know how to get basename of (" & treeRepr(a) & ")\n" &
  1232. repr(a), a)
  1233. proc postfix*(node: NimNode; op: string): NimNode =
  1234. newNimNode(nnkPostfix).add(ident(op), node)
  1235. proc prefix*(node: NimNode; op: string): NimNode =
  1236. newNimNode(nnkPrefix).add(ident(op), node)
  1237. proc infix*(a: NimNode; op: string;
  1238. b: NimNode): NimNode =
  1239. newNimNode(nnkInfix).add(ident(op), a, b)
  1240. proc unpackPostfix*(node: NimNode): tuple[node: NimNode; op: string] =
  1241. node.expectKind nnkPostfix
  1242. result = (node[1], $node[0])
  1243. proc unpackPrefix*(node: NimNode): tuple[node: NimNode; op: string] =
  1244. node.expectKind nnkPrefix
  1245. result = (node[1], $node[0])
  1246. proc unpackInfix*(node: NimNode): tuple[left: NimNode; op: string; right: NimNode] =
  1247. expectKind(node, nnkInfix)
  1248. result = (node[1], $node[0], node[2])
  1249. proc copy*(node: NimNode): NimNode =
  1250. ## An alias for `copyNimTree<#copyNimTree,NimNode>`_.
  1251. return node.copyNimTree()
  1252. proc expectIdent*(n: NimNode, name: string) {.since: (1,1).} =
  1253. ## Check that `eqIdent(n,name)` holds true. If this is not the
  1254. ## case, compilation aborts with an error message. This is useful
  1255. ## for writing macros that check the AST that is passed to them.
  1256. if not eqIdent(n, name):
  1257. error("Expected identifier to be `" & name & "` here", n)
  1258. proc hasArgOfName*(params: NimNode; name: string): bool =
  1259. ## Search `nnkFormalParams` for an argument.
  1260. expectKind(params, nnkFormalParams)
  1261. for i in 1..<params.len:
  1262. for j in 0..<params[i].len-2:
  1263. if name.eqIdent($params[i][j]):
  1264. return true
  1265. proc addIdentIfAbsent*(dest: NimNode, ident: string) =
  1266. ## Add `ident` to `dest` if it is not present. This is intended for use
  1267. ## with pragmas.
  1268. for node in dest.children:
  1269. case node.kind
  1270. of nnkIdent:
  1271. if ident.eqIdent($node): return
  1272. of nnkExprColonExpr:
  1273. if ident.eqIdent($node[0]): return
  1274. else: discard
  1275. dest.add(ident(ident))
  1276. proc boolVal*(n: NimNode): bool {.noSideEffect.} =
  1277. if n.kind == nnkIntLit: n.intVal != 0
  1278. else: n == bindSym"true" # hacky solution for now
  1279. when defined(nimMacrosGetNodeId):
  1280. proc nodeID*(n: NimNode): int {.magic: "NodeId".}
  1281. ## Returns the id of `n`, when the compiler has been compiled
  1282. ## with the flag `-d:useNodeids`, otherwise returns `-1`. This
  1283. ## proc is for the purpose to debug the compiler only.
  1284. macro expandMacros*(body: typed): untyped =
  1285. ## Expands one level of macro - useful for debugging.
  1286. ## Can be used to inspect what happens when a macro call is expanded,
  1287. ## without altering its result.
  1288. ##
  1289. ## For instance,
  1290. ##
  1291. ## ```
  1292. ## import std/[sugar, macros]
  1293. ##
  1294. ## let
  1295. ## x = 10
  1296. ## y = 20
  1297. ## expandMacros:
  1298. ## dump(x + y)
  1299. ## ```
  1300. ##
  1301. ## will actually dump `x + y`, but at the same time will print at
  1302. ## compile time the expansion of the `dump` macro, which in this
  1303. ## case is `debugEcho ["x + y", " = ", x + y]`.
  1304. echo body.toStrLit
  1305. result = body
  1306. proc extractTypeImpl(n: NimNode): NimNode =
  1307. ## attempts to extract the type definition of the given symbol
  1308. case n.kind
  1309. of nnkSym: # can extract an impl
  1310. result = n.getImpl.extractTypeImpl()
  1311. of nnkObjectTy, nnkRefTy, nnkPtrTy: result = n
  1312. of nnkBracketExpr:
  1313. if n.typeKind == ntyTypeDesc:
  1314. result = n[1].extractTypeImpl()
  1315. else:
  1316. doAssert n.typeKind == ntyGenericInst
  1317. result = n[0].getImpl()
  1318. of nnkTypeDef:
  1319. result = n[2]
  1320. else: error("Invalid node to retrieve type implementation of: " & $n.kind)
  1321. proc customPragmaNode(n: NimNode): NimNode =
  1322. expectKind(n, {nnkSym, nnkDotExpr, nnkBracketExpr, nnkTypeOfExpr, nnkType, nnkCheckedFieldExpr})
  1323. let
  1324. typ = n.getTypeInst()
  1325. if typ.kind == nnkBracketExpr and typ.len > 1 and typ[1].kind == nnkProcTy:
  1326. return typ[1][1]
  1327. elif typ.typeKind == ntyTypeDesc:
  1328. let impl = getImpl(
  1329. if kind(typ[1]) == nnkBracketExpr: typ[1][0]
  1330. else: typ[1]
  1331. )
  1332. if impl.kind == nnkNilLit:
  1333. return impl
  1334. elif impl[0].kind == nnkPragmaExpr:
  1335. return impl[0][1]
  1336. else:
  1337. return impl[0] # handle types which don't have macro at all
  1338. if n.kind == nnkSym: # either an variable or a proc
  1339. let impl = n.getImpl()
  1340. if impl.kind in RoutineNodes:
  1341. return impl.pragma
  1342. elif impl.kind in {nnkIdentDefs, nnkConstDef} and impl[0].kind == nnkPragmaExpr:
  1343. return impl[0][1]
  1344. else:
  1345. let timpl = typ.getImpl()
  1346. if timpl.len>0 and timpl[0].len>1:
  1347. return timpl[0][1]
  1348. else:
  1349. return timpl
  1350. if n.kind in {nnkDotExpr, nnkCheckedFieldExpr}:
  1351. let name = $(if n.kind == nnkCheckedFieldExpr: n[0][1] else: n[1])
  1352. let typInst = getTypeInst(if n.kind == nnkCheckedFieldExpr or n[0].kind == nnkHiddenDeref: n[0][0] else: n[0])
  1353. var typDef = getImpl(
  1354. if typInst.kind in {nnkVarTy, nnkBracketExpr}: typInst[0]
  1355. else: typInst
  1356. )
  1357. while typDef != nil:
  1358. typDef.expectKind(nnkTypeDef)
  1359. let typ = typDef[2].extractTypeImpl()
  1360. if typ.kind notin {nnkRefTy, nnkPtrTy, nnkObjectTy}: break
  1361. let isRef = typ.kind in {nnkRefTy, nnkPtrTy}
  1362. if isRef and typ[0].kind in {nnkSym, nnkBracketExpr}: # defines ref type for another object(e.g. X = ref X)
  1363. typDef = getImpl(typ[0])
  1364. else: # object definition, maybe an object directly defined as a ref type
  1365. let
  1366. obj = (if isRef: typ[0] else: typ)
  1367. var identDefsStack = newSeq[NimNode](obj[2].len)
  1368. for i in 0..<identDefsStack.len: identDefsStack[i] = obj[2][i]
  1369. while identDefsStack.len > 0:
  1370. var identDefs = identDefsStack.pop()
  1371. case identDefs.kind
  1372. of nnkRecList:
  1373. for child in identDefs.children:
  1374. identDefsStack.add(child)
  1375. of nnkRecCase:
  1376. # Add condition definition
  1377. identDefsStack.add(identDefs[0])
  1378. # Add branches
  1379. for i in 1 ..< identDefs.len:
  1380. identDefsStack.add(identDefs[i].last)
  1381. else:
  1382. for i in 0 .. identDefs.len - 3:
  1383. let varNode = identDefs[i]
  1384. if varNode.kind == nnkPragmaExpr:
  1385. var varName = varNode[0]
  1386. if varName.kind == nnkPostfix:
  1387. # This is a public field. We are skipping the postfix *
  1388. varName = varName[1]
  1389. if eqIdent($varName, name):
  1390. return varNode[1]
  1391. if obj[1].kind == nnkOfInherit: # explore the parent object
  1392. typDef = getImpl(obj[1][0])
  1393. else:
  1394. typDef = nil
  1395. macro hasCustomPragma*(n: typed, cp: typed{nkSym}): untyped =
  1396. ## Expands to `true` if expression `n` which is expected to be `nnkDotExpr`
  1397. ## (if checking a field), a proc or a type has custom pragma `cp`.
  1398. ##
  1399. ## See also `getCustomPragmaVal`_.
  1400. ##
  1401. ## ```
  1402. ## template myAttr() {.pragma.}
  1403. ## type
  1404. ## MyObj = object
  1405. ## myField {.myAttr.}: int
  1406. ##
  1407. ## proc myProc() {.myAttr.} = discard
  1408. ##
  1409. ## var o: MyObj
  1410. ## assert(o.myField.hasCustomPragma(myAttr))
  1411. ## assert(myProc.hasCustomPragma(myAttr))
  1412. ## ```
  1413. let pragmaNode = customPragmaNode(n)
  1414. for p in pragmaNode:
  1415. if (p.kind == nnkSym and p == cp) or
  1416. (p.kind in nnkPragmaCallKinds and p.len > 0 and p[0].kind == nnkSym and p[0] == cp):
  1417. return newLit(true)
  1418. return newLit(false)
  1419. macro getCustomPragmaVal*(n: typed, cp: typed{nkSym}): untyped =
  1420. ## Expands to value of custom pragma `cp` of expression `n` which is expected
  1421. ## to be `nnkDotExpr`, a proc or a type.
  1422. ##
  1423. ## See also `hasCustomPragma`_.
  1424. ##
  1425. ## ```
  1426. ## template serializationKey(key: string) {.pragma.}
  1427. ## type
  1428. ## MyObj {.serializationKey: "mo".} = object
  1429. ## myField {.serializationKey: "mf".}: int
  1430. ## var o: MyObj
  1431. ## assert(o.myField.getCustomPragmaVal(serializationKey) == "mf")
  1432. ## assert(o.getCustomPragmaVal(serializationKey) == "mo")
  1433. ## assert(MyObj.getCustomPragmaVal(serializationKey) == "mo")
  1434. ## ```
  1435. result = nil
  1436. let pragmaNode = customPragmaNode(n)
  1437. for p in pragmaNode:
  1438. if p.kind in nnkPragmaCallKinds and p.len > 0 and p[0].kind == nnkSym and p[0] == cp:
  1439. if p.len == 2 or (p.len == 3 and p[1].kind == nnkSym and p[1].symKind == nskType):
  1440. result = p[1]
  1441. else:
  1442. let def = p[0].getImpl[3]
  1443. result = newTree(nnkPar)
  1444. for i in 1 ..< def.len:
  1445. let key = def[i][0]
  1446. let val = p[i]
  1447. result.add newTree(nnkExprColonExpr, key, val)
  1448. break
  1449. if result.kind == nnkEmpty:
  1450. error(n.repr & " doesn't have a pragma named " & cp.repr()) # returning an empty node results in most cases in a cryptic error,
  1451. macro unpackVarargs*(callee: untyped; args: varargs[untyped]): untyped =
  1452. ## Calls `callee` with `args` unpacked as individual arguments.
  1453. ## This is useful in 2 cases:
  1454. ## * when forwarding `varargs[T]` for some typed `T`
  1455. ## * when forwarding `varargs[untyped]` when `args` can potentially be empty,
  1456. ## due to a compiler limitation
  1457. runnableExamples:
  1458. template call1(fun: typed; args: varargs[untyped]): untyped =
  1459. unpackVarargs(fun, args)
  1460. # when varargsLen(args) > 0: fun(args) else: fun() # this would also work
  1461. template call2(fun: typed; args: varargs[typed]): untyped =
  1462. unpackVarargs(fun, args)
  1463. proc fn1(a = 0, b = 1) = discard (a, b)
  1464. call1(fn1, 10, 11)
  1465. call1(fn1) # `args` is empty in this case
  1466. if false: call2(echo, 10, 11) # would print 1011
  1467. result = newCall(callee)
  1468. for i in 0 ..< args.len:
  1469. result.add args[i]
  1470. proc getProjectPath*(): string = discard
  1471. ## Returns the path to the currently compiling project.
  1472. ##
  1473. ## This is not to be confused with `system.currentSourcePath <system.html#currentSourcePath.t>`_
  1474. ## which returns the path of the source file containing that template
  1475. ## call.
  1476. ##
  1477. ## For example, assume a `dir1/foo.nim` that imports a `dir2/bar.nim`,
  1478. ## have the `bar.nim` print out both `getProjectPath` and
  1479. ## `currentSourcePath` outputs.
  1480. ##
  1481. ## Now when `foo.nim` is compiled, the `getProjectPath` from
  1482. ## `bar.nim` will return the `dir1/` path, while the `currentSourcePath`
  1483. ## will return the path to the `bar.nim` source file.
  1484. ##
  1485. ## Now when `bar.nim` is compiled directly, the `getProjectPath`
  1486. ## will now return the `dir2/` path, and the `currentSourcePath`
  1487. ## will still return the same path, the path to the `bar.nim` source
  1488. ## file.
  1489. ##
  1490. ## The path returned by this proc is set at compile time.
  1491. ##
  1492. ## See also:
  1493. ## * `getCurrentDir proc <os.html#getCurrentDir>`_
  1494. proc getSize*(arg: NimNode): int {.magic: "NSizeOf", noSideEffect.} =
  1495. ## Returns the same result as `system.sizeof` if the size is
  1496. ## known by the Nim compiler. Returns a negative value if the Nim
  1497. ## compiler does not know the size.
  1498. proc getAlign*(arg: NimNode): int {.magic: "NSizeOf", noSideEffect.} =
  1499. ## Returns the same result as `system.alignof` if the alignment
  1500. ## is known by the Nim compiler. It works on `NimNode` for use
  1501. ## in macro context. Returns a negative value if the Nim compiler
  1502. ## does not know the alignment.
  1503. proc getOffset*(arg: NimNode): int {.magic: "NSizeOf", noSideEffect.} =
  1504. ## Returns the same result as `system.offsetof` if the offset is
  1505. ## known by the Nim compiler. It expects a resolved symbol node
  1506. ## from a field of a type. Therefore it only requires one argument
  1507. ## instead of two. Returns a negative value if the Nim compiler
  1508. ## does not know the offset.
  1509. proc isExported*(n: NimNode): bool {.noSideEffect.} =
  1510. ## Returns whether the symbol is exported or not.
  1511. proc extractDocCommentsAndRunnables*(n: NimNode): NimNode =
  1512. ## returns a `nnkStmtList` containing the top-level doc comments and
  1513. ## runnableExamples in `a`, stopping at the first child that is neither.
  1514. ## Example:
  1515. ##
  1516. ## ```
  1517. ## import std/macros
  1518. ## macro transf(a): untyped =
  1519. ## result = quote do:
  1520. ## proc fun2*() = discard
  1521. ## let header = extractDocCommentsAndRunnables(a.body)
  1522. ## # correct usage: rest is appended
  1523. ## result.body = header
  1524. ## result.body.add quote do: discard # just an example
  1525. ## # incorrect usage: nesting inside a nnkStmtList:
  1526. ## # result.body = quote do: (`header`; discard)
  1527. ##
  1528. ## proc fun*() {.transf.} =
  1529. ## ## first comment
  1530. ## runnableExamples: discard
  1531. ## runnableExamples: discard
  1532. ## ## last comment
  1533. ## discard # first statement after doc comments + runnableExamples
  1534. ## ## not docgen'd
  1535. ## ```
  1536. result = newStmtList()
  1537. for ni in n:
  1538. case ni.kind
  1539. of nnkCommentStmt:
  1540. result.add ni
  1541. of nnkCall, nnkCommand:
  1542. if ni[0].kind == nnkIdent and ni[0].eqIdent "runnableExamples":
  1543. result.add ni
  1544. else: break
  1545. else: break