macros.nim 53 KB

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