macros.nim 61 KB

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