macros.nim 57 KB

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