macros.nim 63 KB

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