macros.nim 64 KB

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