macros.nim 61 KB

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