macros.nim 63 KB

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