macros.nim 64 KB

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