macros.nim 64 KB

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