macros.nim 63 KB

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