macros.nim 61 KB

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