std/macros

Search:
Source   Edit  

This module contains the interface to the compiler's abstract syntax tree (AST). Macros operate on this tree.

See also:

The AST in Nim

This section describes how the AST is modelled with Nim's type system. The AST consists of nodes (NimNode) with a variable number of children. Each node has a field named kind which describes what the node contains:

typeNimNodeKind=enum## kind of a node; only explanatorynnkNone,## invalid node kindnnkEmpty,## empty nodennkIdent,## node contains an identifiernnkIntLit,## node contains an int literal (example: 10)nnkStrLit,## node contains a string literal (example: "abc")nnkNilLit,## node contains a nil literal (example: nil)nnkCaseStmt,## node represents a case statement...## many moreNimNode=refNimNodeObjNimNodeObj=objectcasekind:NimNodeKind## the node's kindofnnkNone,nnkEmpty,nnkNilLit:discard## node contains no additional fieldsofnnkCharLit..nnkUInt64Lit:intVal:BiggestInt## the int literalofnnkFloatLit..nnkFloat64Lit:floatVal:BiggestFloat## the float literalofnnkStrLit..nnkTripleStrLit,nnkCommentStmt,nnkIdent,nnkSym:strVal:string## the string literalelse:sons:seq[NimNode]## the node's sons (or children)

For the NimNode type, the [] operator has been overloaded: n[i] is n's i-th child.

To specify the AST for the different Nim constructs, the notation nodekind(son1, son2, ...) or nodekind(value) or nodekind(field=value) is used.

Some child may be missing. A missing child is a node of kind nnkEmpty; a child can never be nil.

Leaf nodes/Atoms

A leaf of the AST often corresponds to a terminal symbol in the concrete syntax. Note that the default float in Nim maps to float64 such that the default AST for a float is nnkFloat64Lit as below.

Nim expressionCorresponding AST
42nnkIntLit(intVal = 42)
42'i8nnkInt8Lit(intVal = 42)
42'i16nnkInt16Lit(intVal = 42)
42'i32nnkInt32Lit(intVal = 42)
42'i64nnkInt64Lit(intVal = 42)
42'u8nnkUInt8Lit(intVal = 42)
42'u16nnkUInt16Lit(intVal = 42)
42'u32nnkUInt32Lit(intVal = 42)
42'u64nnkUInt64Lit(intVal = 42)
42.0nnkFloat64Lit(floatVal = 42.0)
42.0'f32nnkFloat32Lit(floatVal = 42.0)
42.0'f64nnkFloat64Lit(floatVal = 42.0)
"abc"nnkStrLit(strVal = "abc")
r"abc"nnkRStrLit(strVal = "abc")
"""abc"""nnkTripleStrLit(strVal = "abc")
' 'nnkCharLit(intVal = 32)
nilnnkNilLit()
myIdentifiernnkIdent(strVal = "myIdentifier")
myIdentifierafter lookup pass: nnkSym(strVal = "myIdentifier", ...)

Identifiers are nnkIdent nodes. After the name lookup pass these nodes get transferred into nnkSym nodes.

Calls/expressions

Command call

Concrete syntax:

echo"abc","xyz"

AST:

nnkCommand(nnkIdent("echo"),nnkStrLit("abc"),nnkStrLit("xyz"))

Call with ()

Concrete syntax:

echo("abc","xyz")

AST:

nnkCall(nnkIdent("echo"),nnkStrLit("abc"),nnkStrLit("xyz"))

Infix operator call

Concrete syntax:

"abc"&"xyz"

AST:

nnkInfix(nnkIdent("&"),nnkStrLit("abc"),nnkStrLit("xyz"))

Note that with multiple infix operators, the command is parsed by operator precedence.

Concrete syntax:

5+3*4

AST:

nnkInfix(nnkIdent("+"),nnkIntLit(5),nnkInfix(nnkIdent("*"),nnkIntLit(3),nnkIntLit(4)))

As a side note, if you choose to use infix operators in a prefix form, the AST behaves as a parenthetical function call with nnkAccQuoted, as follows:

Concrete syntax:

`+`(3,4)

AST:

nnkCall(nnkAccQuoted(nnkIdent("+")),nnkIntLit(3),nnkIntLit(4))

Prefix operator call

Concrete syntax:

?"xyz"

AST:

nnkPrefix(nnkIdent("?"),nnkStrLit("abc"))

Postfix operator call

Note: There are no postfix operators in Nim. However, the nnkPostfix node is used for the asterisk export marker*:

Concrete syntax:

identifier*

AST:

nnkPostfix(nnkIdent("*"),nnkIdent("identifier"))

Call with named arguments

Concrete syntax:

writeLine(file=stdout,"hallo")

AST:

nnkCall(nnkIdent("writeLine"),nnkExprEqExpr(nnkIdent("file"),nnkIdent("stdout")),nnkStrLit("hallo"))

Call with raw string literal

This is used, for example, in the bindSym examples here and with re"some regexp" in the regular expression module.

Concrete syntax:

echo"abc"

AST:

nnkCallStrLit(nnkIdent("echo"),nnkRStrLit("hello"))

Dereference operator []

Concrete syntax:

x[]

AST:

nnkDerefExpr(nnkIdent("x"))

Addr operator

Concrete syntax:

addr(x)

AST:

nnkAddr(nnkIdent("x"))

Cast operator

Concrete syntax:

cast[T](x)

AST:

nnkCast(nnkIdent("T"),nnkIdent("x"))

Object access operator .

Concrete syntax:

x.y

AST:

nnkDotExpr(nnkIdent("x"),nnkIdent("y"))

If you use Nim's flexible calling syntax (as in x.len()), the result is the same as above but wrapped in an nnkCall.

Array access operator []

Concrete syntax:

x[y]

AST:

nnkBracketExpr(nnkIdent("x"),nnkIdent("y"))

Parentheses

Parentheses for affecting operator precedence use the nnkPar node.

Concrete syntax:

(a+b)*c

AST:

nnkInfix(nnkIdent("*"),nnkPar(nnkInfix(nnkIdent("+"),nnkIdent("a"),nnkIdent("b"))),nnkIdent("c"))

Tuple Constructors

Nodes for tuple construction are built with the nnkTupleConstr node.

Concrete syntax:

(1,2,3)(a:1,b:2,c:3)()

AST:

nnkTupleConstr(nnkIntLit(1),nnkIntLit(2),nnkIntLit(3))nnkTupleConstr(nnkExprColonExpr(nnkIdent("a"),nnkIntLit(1)),nnkExprColonExpr(nnkIdent("b"),nnkIntLit(2)),nnkExprColonExpr(nnkIdent("c"),nnkIntLit(3)))nnkTupleConstr()

Since the one tuple would be syntactically identical to parentheses with an expression in them, the parser expects a trailing comma for them. For tuple constructors with field names, this is not necessary.

(1,)(a:1)

AST:

nnkTupleConstr(nnkIntLit(1))nnkTupleConstr(nnkExprColonExpr(nnkIdent("a"),nnkIntLit(1)))

Curly braces

Curly braces are used as the set constructor.

Concrete syntax:

{1,2,3}

AST:

nnkCurly(nnkIntLit(1),nnkIntLit(2),nnkIntLit(3))

When used as a table constructor, the syntax is different.

Concrete syntax:

{a:3,b:5}

AST:

nnkTableConstr(nnkExprColonExpr(nnkIdent("a"),nnkIntLit(3)),nnkExprColonExpr(nnkIdent("b"),nnkIntLit(5)))

Brackets

Brackets are used as the array constructor.

Concrete syntax:

[1,2,3]

AST:

nnkBracket(nnkIntLit(1),nnkIntLit(2),nnkIntLit(3))

Ranges

Ranges occur in set constructors, case statement branches, or array slices. Internally, the node kind nnkRange is used, but when constructing the AST, construction with .. as an infix operator should be used instead.

Concrete syntax:

1..3

AST:

nnkInfix(nnkIdent(".."),nnkIntLit(1),nnkIntLit(3))

Example code:

macrogenRepeatEcho()=result=newNimNode(nnkStmtList)varforStmt=newNimNode(nnkForStmt)# generate a for statementforStmt.add(ident("i"))# use the variable `i` for iterationvarrangeDef=newNimNode(nnkInfix).add(ident("..")).add(newIntLitNode(3),newIntLitNode(5))# iterate over the range 3..5forStmt.add(rangeDef)forStmt.add(newCall(ident("echo"),newIntLitNode(3)))# meat of the loopresult.add(forStmt)genRepeatEcho()# gives:# 3# 3# 3

If expression

The representation of the if expression is subtle, but easy to traverse.

Concrete syntax:

ifcond1:expr1elifcond2:expr2else:expr3

AST:

nnkIfExpr(nnkElifExpr(cond1,expr1),nnkElifExpr(cond2,expr2),nnkElseExpr(expr3))

Documentation Comments

Double-hash (##) comments in the code actually have their own format, using strVal to get and set the comment text. Single-hash (#) comments are ignored.

Concrete syntax:

## This is a comment## This is part of the first commentstmt1## Yet another

AST:

nnkCommentStmt()# only appears once for the first two lines!stmt1nnkCommentStmt()# another nnkCommentStmt because there is another comment# (separate from the first)

Pragmas

One of Nim's cool features is pragmas, which allow fine-tuning of various aspects of the language. They come in all types, such as adorning procs and objects, but the standalone emit pragma shows the basics with the AST.

Concrete syntax:

{.emit:"#include <stdio.h>".}

AST:

nnkPragma(nnkExprColonExpr(nnkIdent("emit"),nnkStrLit("#include <stdio.h>")# the "argument"))

As many nnkIdent appear as there are pragmas between {..}. Note that the declaration of new pragmas is essentially the same:

Concrete syntax:

{.pragma:cdeclRename,cdecl.}

AST:

nnkPragma(nnkExprColonExpr(nnkIdent("pragma"),# this is always first when declaring a new pragmannkIdent("cdeclRename")# the name of the pragma),nnkIdent("cdecl"))

Statements

If statement

The representation of the if statement is subtle, but easy to traverse. If there is no else branch, no nnkElse child exists.

Concrete syntax:

ifcond1:stmt1elifcond2:stmt2elifcond3:stmt3else:stmt4

AST:

nnkIfStmt(nnkElifBranch(cond1,stmt1),nnkElifBranch(cond2,stmt2),nnkElifBranch(cond3,stmt3),nnkElse(stmt4))

When statement

Like the if statement, but the root has the kind nnkWhenStmt.

Assignment

Concrete syntax:

x=42

AST:

nnkAsgn(nnkIdent("x"),nnkIntLit(42))

This is not the syntax for assignment when combined with var, let, or const.

Statement list

Concrete syntax:

stmt1stmt2stmt3

AST:

nnkStmtList(stmt1,stmt2,stmt3)

Case statement

Concrete syntax:

caseexpr1ofexpr2,expr3..expr4:stmt1ofexpr5:stmt2elifcond1:stmt3else:stmt4

AST:

nnkCaseStmt(expr1,nnkOfBranch(expr2,nnkRange(expr3,expr4),stmt1),nnkOfBranch(expr5,stmt2),nnkElifBranch(cond1,stmt3),nnkElse(stmt4))

The nnkElifBranch and nnkElse parts may be missing.

While statement

Concrete syntax:

whileexpr1:stmt1

AST:

nnkWhileStmt(expr1,stmt1)

For statement

Concrete syntax:

forident1,ident2inexpr1:stmt1

AST:

nnkForStmt(ident1,ident2,expr1,stmt1)

Try statement

Concrete syntax:

try:stmt1excepte1,e2:stmt2excepte3:stmt3except:stmt4finally:stmt5

AST:

nnkTryStmt(stmt1,nnkExceptBranch(e1,e2,stmt2),nnkExceptBranch(e3,stmt3),nnkExceptBranch(stmt4),nnkFinally(stmt5))

Return statement

Concrete syntax:

returnexpr1

AST:

nnkReturnStmt(expr1)

Yield statement

Like return, but with nnkYieldStmt kind.

nnkYieldStmt(expr1)

Discard statement

Like return, but with nnkDiscardStmt kind.

nnkDiscardStmt(expr1)

Continue statement

Concrete syntax:

continue

AST:

nnkContinueStmt()

Break statement

Concrete syntax:

breakotherLocation

AST:

nnkBreakStmt(nnkIdent("otherLocation"))

If break is used without a jump-to location, nnkEmpty replaces nnkIdent.

Block statement

Concrete syntax:

blockname:

AST:

nnkBlockStmt(nnkIdent("name"),nnkStmtList(...))

A block doesn't need an name, in which case nnkEmpty is used.

Asm statement

Concrete syntax:

asm""" some asm """

AST:

nnkAsmStmt(nnkEmpty(),# for pragmasnnkTripleStrLit("some asm"),)

Import section

Nim's import statement actually takes different variations depending on what keywords are present. Let's start with the simplest form.

Concrete syntax:

importstd/math

AST:

nnkImportStmt(nnkIdent("math"))

With except, we get nnkImportExceptStmt.

Concrete syntax:

importstd/mathexceptpow

AST:

nnkImportExceptStmt(nnkIdent("math"),nnkIdent("pow"))

Note that import std/math as m does not use a different node; rather, we use nnkImportStmt with as as an infix operator.

Concrete syntax:

importstd/strutilsassu

AST:

nnkImportStmt(nnkInfix(nnkIdent("as"),nnkIdent("strutils"),nnkIdent("su")))

From statement

If we use from ... import, the result is different, too.

Concrete syntax:

fromstd/mathimportpow

AST:

nnkFromStmt(nnkIdent("math"),nnkIdent("pow"))

Using from std/math as m import pow works identically to the as modifier with the import statement, but wrapped in nnkFromStmt.

Export statement

When you are making an imported module accessible by modules that import yours, the export syntax is pretty straightforward.

Concrete syntax:

exportunsigned

AST:

nnkExportStmt(nnkIdent("unsigned"))

Similar to the import statement, the AST is different for export ... except.

Concrete syntax:

exportmathexceptpow# we're going to implement our own exponentiation

AST:

nnkExportExceptStmt(nnkIdent("math"),nnkIdent("pow"))

Include statement

Like a plain import statement but with nnkIncludeStmt.

Concrete syntax:

includeblocks

AST:

nnkIncludeStmt(nnkIdent("blocks"))

Var section

Concrete syntax:

vara=3

AST:

nnkVarSection(nnkIdentDefs(nnkIdent("a"),nnkEmpty(),# or nnkIdent(...) if the variable declares the typennkIntLit(3),))

Note that either the second or third (or both) parameters above must exist, as the compiler needs to know the type somehow (which it can infer from the given assignment).

This is not the same AST for all uses of var. See Procedure declaration for details.

Let section

This is equivalent to var, but with nnkLetSection rather than nnkVarSection.

Concrete syntax:

leta=3

AST:

nnkLetSection(nnkIdentDefs(nnkIdent("a"),nnkEmpty(),# or nnkIdent(...) for the typennkIntLit(3),))

Const section

Concrete syntax:

consta=3

AST:

nnkConstSection(nnkConstDef(# not nnkConstDefs!nnkIdent("a"),nnkEmpty(),# or nnkIdent(...) if the variable declares the typennkIntLit(3),# required in a const declaration!))

Type section

Starting with the simplest case, a type section appears much like var and const.

Concrete syntax:

typeA=int

AST:

nnkTypeSection(nnkTypeDef(nnkIdent("A"),nnkEmpty(),nnkIdent("int")))

Declaring distinct types is similar, with the last nnkIdent wrapped in nnkDistinctTy.

Concrete syntax:

typeMyInt=distinctint

AST:

# ...nnkTypeDef(nnkIdent("MyInt"),nnkEmpty(),nnkDistinctTy(nnkIdent("int")))

If a type section uses generic parameters, they are treated here:

Concrete syntax:

typeA[T]=expr1

AST:

nnkTypeSection(nnkTypeDef(nnkIdent("A"),nnkGenericParams(nnkIdentDefs(nnkIdent("T"),nnkEmpty(),# if the type is declared with options, like# ``[T: SomeInteger]``, they are given herennkEmpty(),))expr1,))

Note that not all nnkTypeDef utilize nnkIdent as their parameter. One of the most common uses of type declarations is to work with objects.

Concrete syntax:

typeIO=objectofRootObj

AST:

# ...nnkTypeDef(nnkIdent("IO"),nnkEmpty(),nnkObjectTy(nnkEmpty(),# no pragmas herennkOfInherit(nnkIdent("RootObj")# inherits from RootObj),nnkEmpty()))

Nim's object syntax is rich. Let's take a look at an involved example in its entirety to see some of the complexities.

Concrete syntax:

typeObj[T]{.inheritable.}=objectname:stringcaseisFat:booloftrue:m:array[100_000,T]offalse:m:array[10,T]

AST:

# ...nnkPragmaExpr(nnkIdent("Obj"),nnkPragma(nnkIdent("inheritable"))),nnkGenericParams(nnkIdentDefs(nnkIdent("T"),nnkEmpty(),nnkEmpty())),nnkObjectTy(nnkEmpty(),nnkEmpty(),nnkRecList(# list of object parametersnnkIdentDefs(nnkIdent("name"),nnkIdent("string"),nnkEmpty()),nnkRecCase(# case statement within object (not nnkCaseStmt)nnkIdentDefs(nnkIdent("isFat"),nnkIdent("bool"),nnkEmpty()),nnkOfBranch(nnkIdent("true"),nnkRecList(# again, a list of object parametersnnkIdentDefs(nnkIdent("m"),nnkBracketExpr(nnkIdent("array"),nnkIntLit(100000),nnkIdent("T")),nnkEmpty())),nnkOfBranch(nnkIdent("false"),nnkRecList(nnkIdentDefs(nnkIdent("m"),nnkBracketExpr(nnkIdent("array"),nnkIntLit(10),nnkIdent("T")),nnkEmpty()))))))

Using an enum is similar to using an object.

Concrete syntax:

typeX=enumFirst

AST:

# ...nnkEnumTy(nnkEmpty(),nnkIdent("First")# you need at least one nnkIdent or the compiler complains)

The usage of concept (experimental) is similar to objects.

Concrete syntax:

typeCon=conceptx,y,z(x&y&z)isstring

AST:

# ...nnkTypeClassTy(# note this isn't nnkConceptTy!nnkArgList(# ... idents for x, y, z)# ...)

Static types, like static[int], use nnkIdent wrapped in nnkStaticTy.

Concrete syntax:

typeA[T:static[int]]=object

AST:

# ... within nnkGenericParamsnnkIdentDefs(nnkIdent("T"),nnkStaticTy(nnkIdent("int")),nnkEmpty())# ...

In general, declaring types mirrors this syntax (i.e., nnkStaticTy for static, etc.). Examples follow (exceptions marked by *):

Nim typeCorresponding AST
staticnnkStaticTy
tuplennkTupleTy
varnnkVarTy
ptrnnkPtrTy
refnnkRefTy
distinctnnkDistinctTy
enumnnkEnumTy
conceptnnkTypeClassTy*
arraynnkBracketExpr(nnkIdent("array"),...*
procnnkProcTy
iteratornnkIteratorTy
objectnnkObjectTy

Take special care when declaring types as proc. The behavior is similar to Procedure declaration, below, but does not treat nnkGenericParams. Generic parameters are treated in the type, not the proc itself.

Concrete syntax:

typeMyProc[T]=proc(x:T){.nimcall.}

AST:

# ...nnkTypeDef(nnkIdent("MyProc"),nnkGenericParams(# here, not with the proc# ...)nnkProcTy(# behaves like a procedure declaration from here onnnkFormalParams(# ...),nnkPragma(nnkIdent("nimcall"))))

The same syntax applies to iterator (with nnkIteratorTy), but does not apply to converter or template.

Type class versions of these nodes generally share the same node kind but without any child nodes. The tuple type class is represented by nnkTupleClassTy, while a proc or iterator type class with pragmas has an nnkEmpty node in place of the nnkFormalParams node of a concrete proc or iterator type node.

typeTypeClass=proc{.nimcall.}|ref|tuple

AST:

nnkTypeDef(nnkIdent("TypeClass"),nnkEmpty(),nnkInfix(nnkIdent("|"),nnkProcTy(nnkEmpty(),nnkPragma(nnkIdent("nimcall"))),nnkInfix(nnkIdent("|"),nnkRefTy(),nnkTupleClassTy())))

Mixin statement

Concrete syntax:

mixinx

AST:

nnkMixinStmt(nnkIdent("x"))

Bind statement

Concrete syntax:

bindx

AST:

nnkBindStmt(nnkIdent("x"))

Procedure declaration

Let's take a look at a procedure with a lot of interesting aspects to get a feel for how procedure calls are broken down.

Concrete syntax:

prochello*[T:SomeInteger](x:int=3,y:float32):int{.inline.}=discard

AST:

nnkProcDef(nnkPostfix(nnkIdent("*"),nnkIdent("hello")),# the exported proc namennkEmpty(),# patterns for term rewriting in templates and macros (not procs)nnkGenericParams(# generic type parameters, like with type declarationnnkIdentDefs(nnkIdent("T"),nnkIdent("SomeInteger"),nnkEmpty())),nnkFormalParams(nnkIdent("int"),# the first FormalParam is the return type. nnkEmpty() if there is nonennkIdentDefs(nnkIdent("x"),nnkIdent("int"),# type type (required for procs, not for templates)nnkIntLit(3)# a default value),nnkIdentDefs(nnkIdent("y"),nnkIdent("float32"),nnkEmpty())),nnkPragma(nnkIdent("inline")),nnkEmpty(),# reserved slot for future usennkStmtList(nnkDiscardStmt(nnkEmpty()))# the meat of the proc)

There is another consideration. Nim has flexible type identification for its procs. Even though proc(a: int, b: int) and proc(a, b: int) are equivalent in the code, the AST is a little different for the latter.

Concrete syntax:

proc(a,b:int)

AST:

# ...AST as above...nnkFormalParams(nnkEmpty(),# no return herennkIdentDefs(nnkIdent("a"),# the first parameternnkIdent("b"),# directly to the second parameternnkIdent("int"),# their shared type identifiernnkEmpty(),# default value would go here)),# ...

When a procedure uses the special var type return variable, the result is different from that of a var section.

Concrete syntax:

prochello():varint

AST:

# ...nnkFormalParams(nnkVarTy(nnkIdent("int")))

Iterator declaration

The syntax for iterators is similar to procs, but with nnkIteratorDef replacing nnkProcDef.

Concrete syntax:

iteratornonsense[T](x:seq[T]):float{.closure.}=...

AST:

nnkIteratorDef(nnkIdent("nonsense"),nnkEmpty(),...)

Converter declaration

A converter is similar to a proc.

Concrete syntax:

convertertoBool(x:float):bool

AST:

nnkConverterDef(nnkIdent("toBool"),# ...)

Template declaration

Templates (as well as macros, as we'll see) have a slightly expanded AST when compared to procs and iterators. The reason for this is term-rewriting macros. Notice the nnkEmpty() as the second argument to nnkProcDef and nnkIteratorDef above? That's where the term-rewriting macros go.

Concrete syntax:

templateoptOpt{expr1}(a:int):int

AST:

nnkTemplateDef(nnkIdent("optOpt"),nnkStmtList(# instead of nnkEmpty()expr1),# follows like a proc or iterator)

If the template does not have types for its parameters, the type identifiers inside nnkFormalParams just becomes nnkEmpty.

Macro declaration

Macros behave like templates, but nnkTemplateDef is replaced with nnkMacroDef.

Hidden Standard Conversion

varf:float=1

The type of "f" is float but the type of "1" is actually int. Inserting int into a float is a type error. Nim inserts the nnkHiddenStdConv node around the nnkIntLit node so that the new node has the correct type of float. This works for any auto converted nodes and makes the conversion explicit.

Special node kinds

There are several node kinds that are used for semantic checking or code generation. These are accessible from this module, but should not be used. Other node kinds are especially designed to make AST manipulations easier. These are explained here.

To be written.

Types

BindSymRule=enumbrClosed,## only the symbols in current scope are boundbrOpen,## open for overloaded symbols, but may be a single## symbol if not ambiguous (the rules match that of## binding in generics)brForceOpen## same as brOpen, but it will always be open even## if not ambiguous (this cannot be achieved with## any other means in the language currently)
Specifies how bindSym behaves. The difference between open and closed symbols can be found in manual.html#symbol-lookup-in-generics-open-and-closed-symbolsSource   Edit  
LineInfo=objectfilename*:stringline*,column*:int
Source   Edit  
NimIdent {....deprecated.} =objectofRootObj
Deprecated
Represents a Nim identifier in the AST. Note: This is only rarely useful, for identifier construction from a string use ident"abc". Source   Edit  
NimNodeKind=enumnnkNone,nnkEmpty,nnkIdent,nnkSym,nnkType,nnkCharLit,nnkIntLit,nnkInt8Lit,nnkInt16Lit,nnkInt32Lit,nnkInt64Lit,nnkUIntLit,nnkUInt8Lit,nnkUInt16Lit,nnkUInt32Lit,nnkUInt64Lit,nnkFloatLit,nnkFloat32Lit,nnkFloat64Lit,nnkFloat128Lit,nnkStrLit,nnkRStrLit,nnkTripleStrLit,nnkNilLit,nnkComesFrom,nnkDotCall,nnkCommand,nnkCall,nnkCallStrLit,nnkInfix,nnkPrefix,nnkPostfix,nnkHiddenCallConv,nnkExprEqExpr,nnkExprColonExpr,nnkIdentDefs,nnkVarTuple,nnkPar,nnkObjConstr,nnkCurly,nnkCurlyExpr,nnkBracket,nnkBracketExpr,nnkPragmaExpr,nnkRange,nnkDotExpr,nnkCheckedFieldExpr,nnkDerefExpr,nnkIfExpr,nnkElifExpr,nnkElseExpr,nnkLambda,nnkDo,nnkAccQuoted,nnkTableConstr,nnkBind,nnkClosedSymChoice,nnkOpenSymChoice,nnkHiddenStdConv,nnkHiddenSubConv,nnkConv,nnkCast,nnkStaticExpr,nnkAddr,nnkHiddenAddr,nnkHiddenDeref,nnkObjDownConv,nnkObjUpConv,nnkChckRangeF,nnkChckRange64,nnkChckRange,nnkStringToCString,nnkCStringToString,nnkAsgn,nnkFastAsgn,nnkGenericParams,nnkFormalParams,nnkOfInherit,nnkImportAs,nnkProcDef,nnkMethodDef,nnkConverterDef,nnkMacroDef,nnkTemplateDef,nnkIteratorDef,nnkOfBranch,nnkElifBranch,nnkExceptBranch,nnkElse,nnkAsmStmt,nnkPragma,nnkPragmaBlock,nnkIfStmt,nnkWhenStmt,nnkForStmt,nnkParForStmt,nnkWhileStmt,nnkCaseStmt,nnkTypeSection,nnkVarSection,nnkLetSection,nnkConstSection,nnkConstDef,nnkTypeDef,nnkYieldStmt,nnkDefer,nnkTryStmt,nnkFinally,nnkRaiseStmt,nnkReturnStmt,nnkBreakStmt,nnkContinueStmt,nnkBlockStmt,nnkStaticStmt,nnkDiscardStmt,nnkStmtList,nnkImportStmt,nnkImportExceptStmt,nnkExportStmt,nnkExportExceptStmt,nnkFromStmt,nnkIncludeStmt,nnkBindStmt,nnkMixinStmt,nnkUsingStmt,nnkCommentStmt,nnkStmtListExpr,nnkBlockExpr,nnkStmtListType,nnkBlockType,nnkWith,nnkWithout,nnkTypeOfExpr,nnkObjectTy,nnkTupleTy,nnkTupleClassTy,nnkTypeClassTy,nnkStaticTy,nnkRecList,nnkRecCase,nnkRecWhen,nnkRefTy,nnkPtrTy,nnkVarTy,nnkConstTy,nnkOutTy,nnkDistinctTy,nnkProcTy,nnkIteratorTy,nnkSinkAsgn,nnkEnumTy,nnkEnumFieldDef,nnkArgList,nnkPattern,nnkHiddenTryStmt,nnkClosure,nnkGotoState,nnkState,nnkBreakState,nnkFuncDef,nnkTupleConstr,nnkError,## erroneous AST nodennkModuleRef,nnkReplayAction,nnkNilRodNode,## internal IC nodesnnkOpenSym
Source   Edit  
NimSym {....deprecated.} =refNimSymObj
Deprecated
Represents a Nim symbol in the compiler; a symbol is a looked-up ident. Source   Edit  
NimSymKind=enumnskUnknown,nskConditional,nskDynLib,nskParam,nskGenericParam,nskTemp,nskModule,nskType,nskVar,nskLet,nskConst,nskResult,nskProc,nskFunc,nskMethod,nskIterator,nskConverter,nskMacro,nskTemplate,nskField,nskEnumField,nskForVar,nskLabel,nskStub
Source   Edit  
NimTypeKind=enumntyNone,ntyBool,ntyChar,ntyEmpty,ntyAlias,ntyNil,ntyExpr,ntyStmt,ntyTypeDesc,ntyGenericInvocation,ntyGenericBody,ntyGenericInst,ntyGenericParam,ntyDistinct,ntyEnum,ntyOrdinal,ntyArray,ntyObject,ntyTuple,ntySet,ntyRange,ntyPtr,ntyRef,ntyVar,ntySequence,ntyProc,ntyPointer,ntyOpenArray,ntyString,ntyCString,ntyForward,ntyInt,ntyInt8,ntyInt16,ntyInt32,ntyInt64,ntyFloat,ntyFloat32,ntyFloat64,ntyFloat128,ntyUInt,ntyUInt8,ntyUInt16,ntyUInt32,ntyUInt64,ntyUnused0,ntyUnused1,ntyUnused2,ntyVarargs,ntyUncheckedArray,ntyError,ntyBuiltinTypeClass,ntyUserTypeClass,ntyUserTypeClassInst,ntyCompositeTypeClass,ntyInferred,ntyAnd,ntyOr,ntyNot,ntyAnything,ntyStatic,ntyFromExpr,ntyOptDeprecated,ntyVoid
Source   Edit  
TNimSymKinds {....deprecated.} =set[NimSymKind]
Deprecated
Source   Edit  
TNimTypeKinds {....deprecated.} =set[NimTypeKind]
Deprecated
Source   Edit  

Consts

AtomicNodes={nnkNone..nnkNilLit}
Source   Edit  
CallNodes={nnkCall,nnkInfix,nnkPrefix,nnkPostfix,nnkCommand,nnkCallStrLit,nnkHiddenCallConv}
Source   Edit  
nnkCallKinds={nnkCall,nnkInfix,nnkPrefix,nnkPostfix,nnkCommand,nnkCallStrLit,nnkHiddenCallConv}
Source   Edit  
nnkLiterals={nnkCharLit..nnkNilLit}
Source   Edit  
nnkMutableTy {....deprecated.} =nnkOutTy
Source   Edit  
nnkSharedTy {....deprecated.} =nnkSinkAsgn
Source   Edit  
RoutineNodes={nnkProcDef,nnkFuncDef,nnkMethodDef,nnkDo,nnkLambda,nnkIteratorDef,nnkTemplateDef,nnkConverterDef,nnkMacroDef}
Source   Edit  

Procs

proc`$`(arg:LineInfo):string {....raises:[],tags:[],forbids:[].}
Return a string representation in the form filepath(line,column). Source   Edit  
proc`$`(i:NimIdent):string {.magic:"NStrVal",noSideEffect,...deprecated:"Deprecated since version 0.18.1; Use \'strVal\' instead.",raises:[],tags:[],forbids:[].}
Deprecated: Deprecated since version 0.18.1; Use 'strVal' instead.
Converts a Nim identifier to a string. Source   Edit  
proc`$`(node:NimNode):string {....raises:[],tags:[],forbids:[].}
Get the string of an identifier node. Source   Edit  
proc`$`(s:NimSym):string {.magic:"NStrVal",noSideEffect,...deprecated:"Deprecated since version 0.18.1; Use \'strVal\' instead.",raises:[],tags:[],forbids:[].}
Deprecated: Deprecated since version 0.18.1; Use 'strVal' instead.
Converts a Nim symbol to a string. Source   Edit  
proc`==`(a,b:NimIdent):bool {.magic:"EqIdent",noSideEffect,...deprecated:"Deprecated since version 0.18.1; Use \'==\' on \'NimNode\' instead.",raises:[],tags:[],forbids:[].}
Deprecated: Deprecated since version 0.18.1; Use '==' on 'NimNode' instead.
Compares two Nim identifiers. Source   Edit  
proc`==`(a,b:NimNode):bool {.magic:"EqNimrodNode",noSideEffect,...raises:[],tags:[],forbids:[].}
Compare two Nim nodes. Return true if nodes are structurally equivalent. This means two independently created nodes can be equal. Source   Edit  
proc`==`(a,b:NimSym):bool {.magic:"EqNimrodNode",noSideEffect,...deprecated:"Deprecated since version 0.18.1; Use \'==(NimNode, NimNode)\' instead.",raises:[],tags:[],forbids:[].}
Deprecated: Deprecated since version 0.18.1; Use '==(NimNode, NimNode)' instead.
Compares two Nim symbols. Source   Edit  
proc`[]`(n:NimNode;i:BackwardsIndex):NimNode {....raises:[],tags:[],forbids:[].}
Get n's i'th child. Source   Edit  
proc`[]`(n:NimNode;i:int):NimNode {.magic:"NChild",noSideEffect,...raises:[],tags:[],forbids:[].}
Get n's i'th child. Source   Edit  
proc`[]`[T,U:Ordinal](n:NimNode;x:HSlice[T,U]):seq[NimNode]
Slice operation for NimNode. Returns a seq of child of n who inclusive range [n[x.a],n[x.b]]. Source   Edit  
proc`[]=`(n:NimNode;i:BackwardsIndex;child:NimNode) {....raises:[],tags:[],forbids:[].}
Set n's i'th child to child. Source   Edit  
proc`[]=`(n:NimNode;i:int;child:NimNode) {.magic:"NSetChild",noSideEffect,...raises:[],tags:[],forbids:[].}
Set n's i'th child to child. Source   Edit  
procadd(father,child:NimNode):NimNode {.magic:"NAdd",discardable,noSideEffect,...raises:[],tags:[],forbids:[].}
Adds the child to the father node. Returns the father node so that calls can be nested. Source   Edit  
procadd(father:NimNode;children:varargs[NimNode]):NimNode {. magic:"NAddMultiple",discardable,noSideEffect,...raises:[],tags:[],forbids:[].}
Adds each child of children to the father node. Returns the father node so that calls can be nested. Source   Edit  
procaddIdentIfAbsent(dest:NimNode;ident:string) {....raises:[],tags:[],forbids:[].}
Add ident to dest if it is not present. This is intended for use with pragmas. Source   Edit  
procaddPragma(someProc,pragma:NimNode) {....raises:[],tags:[],forbids:[].}
Adds pragma to routine definition. Source   Edit  
procastGenRepr(n:NimNode):string {....gcsafe,raises:[],tags:[],forbids:[].}

Convert the AST n to the code required to generate that AST.

See also system: repr, treeRepr, and lispRepr.

Source   Edit  
procbasename(a:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
Pull an identifier from prefix/postfix expressions. Source   Edit  
procbasename=(a:NimNode;val:string) {....raises:[],tags:[],forbids:[].}
Source   Edit  
procbindSym(ident:string|NimNode;rule:BindSymRule=brClosed):NimNode {. magic:"NBindSym",noSideEffect,...raises:[],tags:[],forbids:[].}

Creates a node that binds ident to a symbol node. The bound symbol may be an overloaded symbol. if ident is a NimNode, it must have nnkIdent kind. If rule==brClosed either an nnkClosedSymChoice tree is returned or nnkSym if the symbol is not ambiguous. If rule==brOpen either an nnkOpenSymChoice tree is returned or nnkSym if the symbol is not ambiguous. If rule==brForceOpen always an nnkOpenSymChoice tree is returned even if the symbol is not ambiguous.

See the manual for more details.

Source   Edit  
procbody(someProc:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
Source   Edit  
procbody=(someProc:NimNode;val:NimNode) {....raises:[],tags:[],forbids:[].}
Source   Edit  
procboolVal(n:NimNode):bool {.noSideEffect,...raises:[],tags:[],forbids:[].}
Source   Edit  
proccallsite():NimNode {.magic:"NCallSite",...gcsafe,deprecated:"Deprecated since v0.18.1; use `varargs[untyped]` in the macro prototype instead",raises:[],tags:[],forbids:[].}
Deprecated: Deprecated since v0.18.1; use `varargs[untyped]` in the macro prototype instead
Returns the AST of the invocation expression that invoked this macro. Source   Edit  
proccopy(node:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
An alias for copyNimTree. Source   Edit  
proccopyChildrenTo(src,dest:NimNode) {....raises:[],tags:[],forbids:[].}
Copy all children from src to dest. Source   Edit  
proccopyLineInfo(arg:NimNode;info:NimNode) {.magic:"NLineInfo",noSideEffect,...raises:[],tags:[],forbids:[].}
Copy lineinfo from info. Source   Edit  
proccopyNimNode(n:NimNode):NimNode {.magic:"NCopyNimNode",noSideEffect,...raises:[],tags:[],forbids:[].}
Creates a new AST node by copying the node n. Note that unlike copyNimTree, child nodes of n are not copied.

Example:

macrofoo(x:typed)=vars=copyNimNode(x)doAsserts.len==0doAsserts.kind==nnkStmtListfoo:letx=12echox
Source   Edit  
proccopyNimTree(n:NimNode):NimNode {.magic:"NCopyNimTree",noSideEffect,...raises:[],tags:[],forbids:[].}
Creates a new AST node by recursively copying the node n. Note that unlike copyNimNode, this copies n, the children of n, etc.

Example:

macrofoo(x:typed)=vars=copyNimTree(x)doAsserts.len==2doAsserts.kind==nnkStmtListfoo:letx=12echox
Source   Edit  
procdel(father:NimNode;idx=0;n=1) {.magic:"NDel",noSideEffect,...raises:[],tags:[],forbids:[].}
Deletes n children of father starting at index idx. Source   Edit  
proceqIdent(a:NimNode;b:NimNode):bool {.magic:"EqIdent",noSideEffect,...raises:[],tags:[],forbids:[].}
Style insensitive comparison. a and b can be an identifier or a symbol. Both may be wrapped in an export marker (nnkPostfix) or quoted with backticks (nnkAccQuoted), these nodes will be unwrapped. Source   Edit  
proceqIdent(a:NimNode;b:string):bool {.magic:"EqIdent",noSideEffect,...raises:[],tags:[],forbids:[].}
Style insensitive comparison. a can be an identifier or a symbol. a may be wrapped in an export marker (nnkPostfix) or quoted with backticks (nnkAccQuoted), these nodes will be unwrapped. Source   Edit  
proceqIdent(a:string;b:NimNode):bool {.magic:"EqIdent",noSideEffect,...raises:[],tags:[],forbids:[].}
Style insensitive comparison. b can be an identifier or a symbol. b may be wrapped in an export marker (nnkPostfix) or quoted with backticks (nnkAccQuoted), these nodes will be unwrapped. Source   Edit  
proceqIdent(a:string;b:string):bool {.magic:"EqIdent",noSideEffect,...raises:[],tags:[],forbids:[].}
Style insensitive comparison. Source   Edit  
procerror(msg:string;n:NimNode=nil) {.magic:"NError",...gcsafe,noreturn,...raises:[],tags:[],forbids:[].}
Writes an error message at compile time. The optional n:NimNode parameter is used as the source for file and line number information in the compilation error message. Source   Edit  
procexpectIdent(n:NimNode;name:string) {....raises:[],tags:[],forbids:[].}
Check that eqIdent(n,name) holds true. If this is not the case, compilation aborts with an error message. This is useful for writing macros that check the AST that is passed to them. Source   Edit  
procexpectKind(n:NimNode;k:NimNodeKind) {....raises:[],tags:[],forbids:[].}
Checks that n is of kind k. If this is not the case, compilation aborts with an error message. This is useful for writing macros that check the AST that is passed to them. Source   Edit  
procexpectKind(n:NimNode;k:set[NimNodeKind]) {....raises:[],tags:[],forbids:[].}
Checks that n is of kind k. If this is not the case, compilation aborts with an error message. This is useful for writing macros that check the AST that is passed to them. Source   Edit  
procexpectLen(n:NimNode;len:int) {....raises:[],tags:[],forbids:[].}
Checks that n has exactly len children. If this is not the case, compilation aborts with an error message. This is useful for writing macros that check its number of arguments. Source   Edit  
procexpectLen(n:NimNode;min,max:int) {....raises:[],tags:[],forbids:[].}
Checks that n has a number of children in the range min..max. If this is not the case, compilation aborts with an error message. This is useful for writing macros that check its number of arguments. Source   Edit  
procexpectMinLen(n:NimNode;min:int) {....raises:[],tags:[],forbids:[].}
Checks that n has at least min children. If this is not the case, compilation aborts with an error message. This is useful for writing macros that check its number of arguments. Source   Edit  
procextractDocCommentsAndRunnables(n:NimNode):NimNode {....raises:[],tags:[],forbids:[].}

returns a nnkStmtList containing the top-level doc comments and runnableExamples in a, stopping at the first child that is neither. Example:

importstd/macrosmacrotransf(a):untyped=result=quotedo:procfun2*()=discardletheader=extractDocCommentsAndRunnables(a.body)# correct usage: rest is appendedresult.body=headerresult.body.addquotedo:discard# just an example# incorrect usage: nesting inside a nnkStmtList:# result.body = quote do: (`header`; discard)procfun*(){.transf.}=## first commentrunnableExamples:discardrunnableExamples:discard## last commentdiscard# first statement after doc comments + runnableExamples## not docgen'd

Source   Edit  
procfloatVal(n:NimNode):BiggestFloat {.magic:"NFloatVal",noSideEffect,...raises:[],tags:[],forbids:[].}
Returns a float from any floating point literal. Source   Edit  
procfloatVal=(n:NimNode;val:BiggestFloat) {.magic:"NSetFloatVal",noSideEffect,...raises:[],tags:[],forbids:[].}
Source   Edit  
procgenSym(kind:NimSymKind=nskLet;ident=""):NimNode {.magic:"NGenSym",noSideEffect,...raises:[],tags:[],forbids:[].}
Generates a fresh symbol that is guaranteed to be unique. The symbol needs to occur in a declaration context. Source   Edit  
procgetAlign(arg:NimNode):int {.magic:"NSizeOf",noSideEffect,...raises:[],tags:[],forbids:[].}
Returns the same result as system.alignof if the alignment is known by the Nim compiler. It works on NimNode for use in macro context. Returns a negative value if the Nim compiler does not know the alignment. Source   Edit  
procgetAst(macroOrTemplate:untyped):NimNode {.magic:"ExpandToAst",noSideEffect,...raises:[],tags:[],forbids:[].}

Obtains the AST nodes returned from a macro or template invocation. See also genasts.genAst. Example:

macroFooMacro()=varast=getAst(BarTemplate())

Source   Edit  
procgetImpl(s:NimSym):NimNode {.magic:"GetImpl",noSideEffect,...deprecated:"use `getImpl: NimNode -> NimNode` instead",raises:[],tags:[],forbids:[].}
Deprecated: use `getImpl: NimNode -> NimNode` instead
Source   Edit  
procgetImpl(symbol:NimNode):NimNode {.magic:"GetImpl",noSideEffect,...raises:[],tags:[],forbids:[].}
Returns a copy of the declaration of a symbol or nil. Source   Edit  
procgetImplTransformed(symbol:NimNode):NimNode {.magic:"GetImplTransf",noSideEffect,...raises:[],tags:[],forbids:[].}
For a typed proc returns the AST after transformation pass; this is useful for debugging how the compiler transforms code (e.g.: defer, for) but note that code transformations are implementation dependent and subject to change. See an example in tests/macros/tmacros_various.nim. Source   Edit  
procgetOffset(arg:NimNode):int {.magic:"NSizeOf",noSideEffect,...raises:[],tags:[],forbids:[].}
Returns the same result as system.offsetof if the offset is known by the Nim compiler. It expects a resolved symbol node from a field of a type. Therefore it only requires one argument instead of two. Returns a negative value if the Nim compiler does not know the offset. Source   Edit  
procgetProjectPath():string {....raises:[],tags:[],forbids:[].}

Returns the path to the currently compiling project.

This is not to be confused with system.currentSourcePath which returns the path of the source file containing that template call.

For example, assume a dir1/foo.nim that imports a dir2/bar.nim, have the bar.nim print out both getProjectPath and currentSourcePath outputs.

Now when foo.nim is compiled, the getProjectPath from bar.nim will return the dir1/ path, while the currentSourcePath will return the path to the bar.nim source file.

Now when bar.nim is compiled directly, the getProjectPath will now return the dir2/ path, and the currentSourcePath will still return the same path, the path to the bar.nim source file.

The path returned by this proc is set at compile time.

See also:

Source   Edit  
procgetSize(arg:NimNode):int {.magic:"NSizeOf",noSideEffect,...raises:[],tags:[],forbids:[].}
Returns the same result as system.sizeof if the size is known by the Nim compiler. Returns a negative value if the Nim compiler does not know the size. Source   Edit  
procgetType(n:NimNode):NimNode {.magic:"NGetType",noSideEffect,...raises:[],tags:[],forbids:[].}
With 'getType' you can access the node's type. A Nim type is mapped to a Nim AST too, so it's slightly confusing but it means the same API can be used to traverse types. Recursive types are flattened for you so there is no danger of infinite recursions during traversal. To resolve recursive types, you have to call 'getType' again. To see what kind of type it is, call typeKind on getType's result. Source   Edit  
procgetType(n:typedesc):NimNode {.magic:"NGetType",noSideEffect,...raises:[],tags:[],forbids:[].}
Version of getType which takes a typedesc. Source   Edit  
procgetTypeImpl(n:NimNode):NimNode {.magic:"NGetType",noSideEffect,...raises:[],tags:[],forbids:[].}
Returns the type of a node in a form matching the implementation of the type. Any intermediate aliases are expanded to arrive at the final type implementation. You can instead use getImpl on a symbol if you want to find the intermediate aliases.

Example:

typeVec[N:static[int],T]=objectarr:array[N,T]Vec4[T]=Vec[4,T]Vec4f=Vec4[float32]vara:Vec4fvarb:Vec4[float32]varc:Vec[4,float32]macrodumpTypeImpl(x:typed):untyped=newLit(x.getTypeImpl.repr)lett=""" object arr: array[0 .. 3, float32]"""doAssert(dumpTypeImpl(a)==t)doAssert(dumpTypeImpl(b)==t)doAssert(dumpTypeImpl(c)==t)
Source   Edit  
procgetTypeImpl(n:typedesc):NimNode {.magic:"NGetType",noSideEffect,...raises:[],tags:[],forbids:[].}
Version of getTypeImpl which takes a typedesc. Source   Edit  
procgetTypeInst(n:NimNode):NimNode {.magic:"NGetType",noSideEffect,...raises:[],tags:[],forbids:[].}
Returns the type of a node in a form matching the way the type instance was declared in the code.

Example:

typeVec[N:static[int],T]=objectarr:array[N,T]Vec4[T]=Vec[4,T]Vec4f=Vec4[float32]vara:Vec4fvarb:Vec4[float32]varc:Vec[4,float32]macrodumpTypeInst(x:typed):untyped=newLit(x.getTypeInst.repr)doAssert(dumpTypeInst(a)=="Vec4f")doAssert(dumpTypeInst(b)=="Vec4[float32]")doAssert(dumpTypeInst(c)=="Vec[4, float32]")
Source   Edit  
procgetTypeInst(n:typedesc):NimNode {.magic:"NGetType",noSideEffect,...raises:[],tags:[],forbids:[].}
Version of getTypeInst which takes a typedesc. Source   Edit  
prochasArgOfName(params:NimNode;name:string):bool {....raises:[],tags:[],forbids:[].}
Search nnkFormalParams for an argument. Source   Edit  
prochint(msg:string;n:NimNode=nil) {.magic:"NHint",...gcsafe,raises:[],tags:[],forbids:[].}
Writes a hint message at compile time. Source   Edit  
procident(n:NimNode):NimIdent {.magic:"NIdent",noSideEffect,...deprecated:"Deprecated since version 0.18.1; All functionality is defined on \'NimNode\'.",raises:[],tags:[],forbids:[].}
Deprecated: Deprecated since version 0.18.1; All functionality is defined on 'NimNode'.
Source   Edit  
procident(name:string):NimNode {.magic:"StrToIdent",noSideEffect,...raises:[],tags:[],forbids:[].}
Create a new ident node from a string. Source   Edit  
procident=(n:NimNode;val:NimIdent) {.magic:"NSetIdent",noSideEffect,...deprecated:"Deprecated since version 0.18.1; Generate a new \'NimNode\' with \'ident(string)\' instead.",raises:[],tags:[],forbids:[].}
Deprecated: Deprecated since version 0.18.1; Generate a new 'NimNode' with 'ident(string)' instead.
Source   Edit  
procinfix(a:NimNode;op:string;b:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
Source   Edit  
procinsert(a:NimNode;pos:int;b:NimNode) {....raises:[],tags:[],forbids:[].}
Insert node b into node a at pos. Source   Edit  
procinternalErrorFlag():string {.magic:"NError",noSideEffect,...raises:[],tags:[],forbids:[].}
Some builtins set an error flag. This is then turned into a proper exception. Note: Ordinary application code should not call this. Source   Edit  
procintVal(n:NimNode):BiggestInt {.magic:"NIntVal",noSideEffect,...raises:[],tags:[],forbids:[].}
Returns an integer value from any integer literal or enum field symbol. Source   Edit  
procintVal=(n:NimNode;val:BiggestInt) {.magic:"NSetIntVal",noSideEffect,...raises:[],tags:[],forbids:[].}
Source   Edit  
procisExported(n:NimNode):bool {.noSideEffect,...raises:[],tags:[],forbids:[].}
Returns whether the symbol is exported or not. Source   Edit  
procisInstantiationOf(instanceProcSym,genProcSym:NimNode):bool {. magic:"SymIsInstantiationOf",noSideEffect,...raises:[],tags:[],forbids:[].}
Checks if a proc symbol is an instance of the generic proc symbol. Useful to check proc symbols against generic symbols returned by bindSym. Source   Edit  
prockind(n:NimNode):NimNodeKind {.magic:"NKind",noSideEffect,...raises:[],tags:[],forbids:[].}
Returns the kind of the node n. Source   Edit  
proclast(node:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
Return the last item in nodes children. Same as node[^1]. Source   Edit  
proclen(n:NimNode):int {.magic:"NLen",noSideEffect,...raises:[],tags:[],forbids:[].}
Returns the number of children of n. Source   Edit  
proclineInfo(arg:NimNode):string {....raises:[],tags:[],forbids:[].}
Return line info in the form filepath(line,column). Source   Edit  
proclineInfoObj(n:NimNode):LineInfo {....raises:[],tags:[],forbids:[].}
Returns LineInfo of n, using absolute path for filename. Source   Edit  
proclispRepr(n:NimNode;indented=false):string {....gcsafe,raises:[],tags:[],forbids:[].}

Convert the AST n to a human-readable lisp-like string.

See also repr, treeRepr, and astGenRepr.

Source   Edit  
procname(someProc:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
Source   Edit  
procname=(someProc:NimNode;val:NimNode) {....raises:[],tags:[],forbids:[].}
Source   Edit  
procnestList(op:NimNode;pack:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
Nests the list pack into a tree of call expressions: [a,b,c] is transformed into op(a,op(c,d)). This is also known as fold expression. Source   Edit  
procnestList(op:NimNode;pack:NimNode;init:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
Nests the list pack into a tree of call expressions: [a,b,c] is transformed into op(a,op(c,d)). This is also known as fold expression. Source   Edit  
procnewAssignment(lhs,rhs:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
Source   Edit  
procnewBlockStmt(body:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
Create a new block: stmt. Source   Edit  
procnewBlockStmt(label,body:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
Create a new block statement with label. Source   Edit  
procnewCall(theProc:NimIdent;args:varargs[NimNode]):NimNode {....deprecated:"Deprecated since v0.18.1; use \'newCall(string, ...)\' or \'newCall(NimNode, ...)\' instead",raises:[],tags:[],forbids:[].}
Deprecated: Deprecated since v0.18.1; use 'newCall(string, ...)' or 'newCall(NimNode, ...)' instead
Produces a new call node. theProc is the proc that is called with the arguments args[0..]. Source   Edit  
procnewCall(theProc:NimNode;args:varargs[NimNode]):NimNode {....raises:[],tags:[],forbids:[].}
Produces a new call node. theProc is the proc that is called with the arguments args[0..]. Source   Edit  
procnewCall(theProc:string;args:varargs[NimNode]):NimNode {....raises:[],tags:[],forbids:[].}
Produces a new call node. theProc is the proc that is called with the arguments args[0..]. Source   Edit  
procnewColonExpr(a,b:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
Create new colon expression. newColonExpr(a, b) -> a:bSource   Edit  
procnewCommentStmtNode(s:string):NimNode {.noSideEffect,...raises:[],tags:[],forbids:[].}
Creates a comment statement node. Source   Edit  
procnewConstStmt(name,value:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
Create a new const stmt. Source   Edit  
procnewDotExpr(a,b:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
Create new dot expression. a.dot(b) -> a.bSource   Edit  
procnewEmptyNode():NimNode {.noSideEffect,...raises:[],tags:[],forbids:[].}
Create a new empty node. Source   Edit  
procnewEnum(name:NimNode;fields:openArray[NimNode];public,pure:bool):NimNode {. ...raises:[],tags:[],forbids:[].}

Creates a new enum. name must be an ident. Fields are allowed to be either idents or EnumFieldDef:

newEnum(name=ident("Colors"),fields=[ident("Blue"),ident("Red")],public=true,pure=false)# type Colors* = Blue Red

Source   Edit  
procnewFloatLitNode(f:BiggestFloat):NimNode {....raises:[],tags:[],forbids:[].}
Creates a float literal node from f. Source   Edit  
procnewIdentDefs(name,kind:NimNode;default=newEmptyNode()):NimNode {. ...raises:[],tags:[],forbids:[].}

Creates a new nnkIdentDefs node of a specific kind and value.

nnkIdentDefs need to have at least three children, but they can have more: first comes a list of identifiers followed by a type and value nodes. This helper proc creates a three node subtree, the first subnode being a single identifier name. Both the kind node and default (value) nodes may be empty depending on where the nnkIdentDefs appears: tuple or object definitions will have an empty default node, let or var blocks may have an empty kind node if the identifier is being assigned a value. Example:

varvarSection=newNimNode(nnkVarSection).add(newIdentDefs(ident("a"),ident("string")),newIdentDefs(ident("b"),newEmptyNode(),newLit(3)))# --> var# a: string# b = 3

If you need to create multiple identifiers you need to use the lower level newNimNode:

result=newNimNode(nnkIdentDefs).add(ident("a"),ident("b"),ident("c"),ident("string"),newStrLitNode("Hello"))

Source   Edit  
procnewIdentNode(i:NimIdent):NimNode {....deprecated:"use ident(string)",raises:[],tags:[],forbids:[].}
Deprecated: use ident(string)
Creates an identifier node from i. Source   Edit  
procnewIdentNode(i:string):NimNode {.magic:"StrToIdent",noSideEffect,...raises:[],tags:[],forbids:[].}
Creates an identifier node from i. It is simply an alias for ident(string). Use that, it's shorter. Source   Edit  
procnewIfStmt(branches:varargs[tuple[cond,body:NimNode]]):NimNode {. ...raises:[],tags:[],forbids:[].}

Constructor for if statements.

newIfStmt((Ident,StmtList),...)

Source   Edit  
procnewIntLitNode(i:BiggestInt):NimNode {....raises:[],tags:[],forbids:[].}
Creates an int literal node from i. Source   Edit  
procnewLetStmt(name,value:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
Create a new let stmt. Source   Edit  
procnewLit(arg:enum):NimNode
Source   Edit  
procnewLit(arg:object):NimNode
Source   Edit  
procnewLit(arg:refobject):NimNode
produces a new ref type literal node. Source   Edit  
procnewLit(b:bool):NimNode {....raises:[],tags:[],forbids:[].}
Produces a new boolean literal node. Source   Edit  
procnewLit(c:char):NimNode {....raises:[],tags:[],forbids:[].}
Produces a new character literal node. Source   Edit  
procnewLit(f:float32):NimNode {....raises:[],tags:[],forbids:[].}
Produces a new float literal node. Source   Edit  
procnewLit(f:float64):NimNode {....raises:[],tags:[],forbids:[].}
Produces a new float literal node. Source   Edit  
procnewLit(i:int):NimNode {....raises:[],tags:[],forbids:[].}
Produces a new integer literal node. Source   Edit  
procnewLit(i:int8):NimNode {....raises:[],tags:[],forbids:[].}
Produces a new integer literal node. Source   Edit  
procnewLit(i:int16):NimNode {....raises:[],tags:[],forbids:[].}
Produces a new integer literal node. Source   Edit  
procnewLit(i:int32):NimNode {....raises:[],tags:[],forbids:[].}
Produces a new integer literal node. Source   Edit  
procnewLit(i:int64):NimNode {....raises:[],tags:[],forbids:[].}
Produces a new integer literal node. Source   Edit  
procnewLit(i:uint):NimNode {....raises:[],tags:[],forbids:[].}
Produces a new unsigned integer literal node. Source   Edit  
procnewLit(i:uint8):NimNode {....raises:[],tags:[],forbids:[].}
Produces a new unsigned integer literal node. Source   Edit  
procnewLit(i:uint16):NimNode {....raises:[],tags:[],forbids:[].}
Produces a new unsigned integer literal node. Source   Edit  
procnewLit(i:uint32):NimNode {....raises:[],tags:[],forbids:[].}
Produces a new unsigned integer literal node. Source   Edit  
procnewLit(i:uint64):NimNode {....raises:[],tags:[],forbids:[].}
Produces a new unsigned integer literal node. Source   Edit  
procnewLit(s:string):NimNode {....raises:[],tags:[],forbids:[].}
Produces a new string literal node. Source   Edit  
procnewLit[N,T](arg:array[N,T]):NimNode
Source   Edit  
procnewLit[T:tuple](arg:T):NimNode
Source   Edit  
procnewLit[T](arg:seq[T]):NimNode
Source   Edit  
procnewLit[T](s:set[T]):NimNode
Source   Edit  
procnewNilLit():NimNode {....raises:[],tags:[],forbids:[].}
New nil literal shortcut. Source   Edit  
procnewNimNode(kind:NimNodeKind;lineInfoFrom:NimNode=nil):NimNode {. magic:"NNewNimNode",noSideEffect,...raises:[],tags:[],forbids:[].}

Creates a new AST node of the specified kind.

The lineInfoFrom parameter is used for line information when the produced code crashes. You should ensure that it is set to a node that you are transforming.

Source   Edit  
procnewPar(exprs:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
Create a new parentheses-enclosed expression. Source   Edit  
procnewPar(exprs:varargs[NimNode]):NimNode {....deprecated:"don\'t use newPar/nnkPar to construct tuple expressions; use nnkTupleConstr instead",raises:[],tags:[],forbids:[].}
Deprecated: don't use newPar/nnkPar to construct tuple expressions; use nnkTupleConstr instead
Create a new parentheses-enclosed expression. Source   Edit  
procnewProc(name=newEmptyNode();params:openArray[NimNode]=[newEmptyNode()];body:NimNode=newStmtList();procType=nnkProcDef;pragmas:NimNode=newEmptyNode()):NimNode {....raises:[],tags:[],forbids:[].}

Shortcut for creating a new proc.

The params array must start with the return type of the proc, followed by a list of IdentDefs which specify the params.

Source   Edit  
procnewStmtList(stmts:varargs[NimNode]):NimNode {....raises:[],tags:[],forbids:[].}
Create a new statement list. Source   Edit  
procnewStrLitNode(s:string):NimNode {.noSideEffect,...raises:[],tags:[],forbids:[].}
Creates a string literal node from s. Source   Edit  
procnewTree(kind:NimNodeKind;children:varargs[NimNode]):NimNode {. ...raises:[],tags:[],forbids:[].}
Produces a new node with children. Source   Edit  
procnewVarStmt(name,value:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
Create a new var stmt. Source   Edit  
procnodeID(n:NimNode):int {.magic:"NodeId",...raises:[],tags:[],forbids:[].}
Returns the id of n, when the compiler has been compiled with the flag -d:useNodeids, otherwise returns -1. This proc is for the purpose to debug the compiler only. Source   Edit  
procowner(sym:NimNode):NimNode {.magic:"SymOwner",noSideEffect,...deprecated,raises:[],tags:[],forbids:[].}
Deprecated

Accepts a node of kind nnkSym and returns its owner's symbol. The meaning of 'owner' depends on sym's NimSymKind and declaration context. For top level declarations this is an nskModule symbol, for proc local variables an nskProc symbol, for enum/object fields an nskType symbol, etc. For symbols without an owner, nil is returned.

See also:

Source   Edit  
procparams(someProc:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
Source   Edit  
procparams=(someProc:NimNode;params:NimNode) {....raises:[],tags:[],forbids:[].}
Source   Edit  
procparseExpr(s:string;filename:string=""):NimNode {.noSideEffect,...raises:[ValueError],tags:[],forbids:[].}
Compiles the passed string to its AST representation. Expects a single expression. Raises ValueError for parsing errors. A filename can be given for more informative errors. Source   Edit  
procparseStmt(s:string;filename:string=""):NimNode {.noSideEffect,...raises:[ValueError],tags:[],forbids:[].}
Compiles the passed string to its AST representation. Expects one or more statements. Raises ValueError for parsing errors. A filename can be given for more informative errors. Source   Edit  
procpostfix(node:NimNode;op:string):NimNode {....raises:[],tags:[],forbids:[].}
Source   Edit  
procpragma(someProc:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
Get the pragma of a proc type. These will be expanded. Source   Edit  
procpragma=(someProc:NimNode;val:NimNode) {....raises:[],tags:[],forbids:[].}
Set the pragma of a proc type. Source   Edit  
procprefix(node:NimNode;op:string):NimNode {....raises:[],tags:[],forbids:[].}
Source   Edit  
procquote(bl:typed;op="``"):NimNode {.magic:"QuoteAst",noSideEffect,...raises:[],tags:[],forbids:[].}

Quasi-quoting operator. Accepts an expression or a block and returns the AST that represents it. Within the quoted AST, you are able to interpolate NimNode expressions from the surrounding scope. If no operator is given, quoting is done using backticks. Otherwise, the given operator must be used as a prefix operator for any interpolated expression. The original meaning of the interpolation operator may be obtained by escaping it (by prefixing it with itself) when used as a unary operator: e.g. @ is escaped as @@, &% is escaped as &%&% and so on; see examples.

A custom operator interpolation needs accent quoted (``) whenever it resolves to a symbol.

See also genasts which avoids some issues with quote.

Example:

macrocheck(ex:untyped)=# this is a simplified version of the check macro from the# unittest module.# If there is a failed check, we want to make it easy for# the user to jump to the faulty line in the code, so we# get the line info here:varinfo=ex.lineinfo# We will also display the code string of the failed check:varexpString=ex.toStrLit# Finally we compose the code to implement the check:result=quotedo:ifnot`ex`:echo`info`&": Check failed: "&`expString`check1+1==2

Example:

# example showing how to define a symbol that requires backtick without# quoting it.vardestroyCalled=falsemacrobar()=lets=newTree(nnkAccQuoted,ident"=destroy")# let s = ident"`=destroy`" # this would not workresult=quotedo:typeFoo=object# proc `=destroy`(a: var Foo) = destroyCalled = true # this would not workproc`s`(a:varFoo)=destroyCalled=trueblock:leta=Foo()bar()doAssertdestroyCalled

Example:

# custom `op`vardestroyCalled=falsemacrobar(ident)=varx=1.5result=quote("@")do:typeFoo=objectlet`@ident`=0# custom op interpolated symbols need quoted (``)proc`=destroy`(a:varFoo)=doAssert@x==1.5doAssertcompiles(@x==1.5)letb1=@[1,2]letb2=@@[1,2]doAssert$b1=="[1, 2]"doAssert$b2=="@[1, 2]"destroyCalled=trueblock:leta=Foo()bar(someident)doAssertdestroyCalledproc`&%`(x:int):int=1proc`&%`(x,y:int):int=2macrobar2()=varx=3result=quote("&%")do:vary=&%x# quoting operatordoAssert&%&%y==1# unary operator => need to escapedoAsserty&%y==2# binary operator => no need to escapedoAsserty==3bar2()
Source   Edit  
procsameType(a,b:NimNode):bool {.magic:"SameNodeType",noSideEffect,...raises:[],tags:[],forbids:[].}
Compares two Nim nodes' types. Return true if the types are the same, e.g. true when comparing alias with original type. Source   Edit  
procsetLineInfo(arg:NimNode;file:string;line:int;column:int) {. ...raises:[],tags:[],forbids:[].}
Sets the line info on the NimNode. The file needs to exists, but can be a relative path. If you want to attach line info to a block using quote you'll need to add the line information after the quote block. Source   Edit  
procsetLineInfo(arg:NimNode;lineInfo:LineInfo) {....raises:[],tags:[],forbids:[].}
See setLineInfo procSource   Edit  
procsignatureHash(n:NimNode):string {.magic:"NSigHash",noSideEffect,...raises:[],tags:[],forbids:[].}
Returns a stable identifier derived from the signature of a symbol. The signature combines many factors such as the type of the symbol, the owning module of the symbol and others. The same identifier is used in the back-end to produce the mangled symbol name. Source   Edit  
procstrVal(n:NimNode):string {.magic:"NStrVal",noSideEffect,...raises:[],tags:[],forbids:[].}

Returns the string value of an identifier, symbol, comment, or string literal.

See also:

Source   Edit  
procstrVal=(n:NimNode;val:string) {.magic:"NSetStrVal",noSideEffect,...raises:[],tags:[],forbids:[].}

Sets the string value of a string literal or comment. Setting strVal is disallowed for nnkIdent and nnkSym nodes; a new node must be created using ident or bindSym instead.

See also:

Source   Edit  
procsymBodyHash(s:NimNode):string {.noSideEffect,...raises:[],tags:[],forbids:[].}
Returns a stable digest for symbols derived not only from type signature and owning module, but also implementation body. All procs/variables used in the implementation of this symbol are hashed recursively as well, including magics from system module. Source   Edit  
procsymbol(n:NimNode):NimSym {.magic:"NSymbol",noSideEffect,...deprecated:"Deprecated since version 0.18.1; All functionality is defined on \'NimNode\'.",raises:[],tags:[],forbids:[].}
Deprecated: Deprecated since version 0.18.1; All functionality is defined on 'NimNode'.
Source   Edit  
procsymbol=(n:NimNode;val:NimSym) {.magic:"NSetSymbol",noSideEffect,...deprecated:"Deprecated since version 0.18.1; Generate a new \'NimNode\' with \'genSym\' instead.",raises:[],tags:[],forbids:[].}
Deprecated: Deprecated since version 0.18.1; Generate a new 'NimNode' with 'genSym' instead.
Source   Edit  
procsymKind(symbol:NimNode):NimSymKind {.magic:"NSymKind",noSideEffect,...raises:[],tags:[],forbids:[].}
Source   Edit  
proctoNimIdent(s:string):NimIdent {.magic:"StrToIdent",noSideEffect,...deprecated:"Deprecated since version 0.18.0: Use \'ident\' or \'newIdentNode\' instead.",raises:[],tags:[],forbids:[].}
Deprecated: Deprecated since version 0.18.0: Use 'ident' or 'newIdentNode' instead.
Constructs an identifier from the string s. Source   Edit  
proctoStrLit(n:NimNode):NimNode {....raises:[],tags:[],forbids:[].}
Converts the AST n to the concrete Nim code and wraps that in a string literal node. Source   Edit  
proctreeRepr(n:NimNode):string {....gcsafe,raises:[],tags:[],forbids:[].}

Convert the AST n to a human-readable tree-like string.

See also repr, lispRepr, and astGenRepr.

Source   Edit  
proctypeKind(n:NimNode):NimTypeKind {.magic:"NGetType",noSideEffect,...raises:[],tags:[],forbids:[].}
Returns the type kind of the node 'n' that should represent a type, that means the node should have been obtained via getType. Source   Edit  
procunpackInfix(node:NimNode):tuple[left:NimNode,op:string,right:NimNode] {. ...raises:[],tags:[],forbids:[].}
Source   Edit  
procunpackPostfix(node:NimNode):tuple[node:NimNode,op:string] {. ...raises:[],tags:[],forbids:[].}
Source   Edit  
procunpackPrefix(node:NimNode):tuple[node:NimNode,op:string] {....raises:[],tags:[],forbids:[].}
Source   Edit  
procwarning(msg:string;n:NimNode=nil) {.magic:"NWarning",...gcsafe,raises:[],tags:[],forbids:[].}
Writes a warning message at compile time. Source   Edit  

Iterators

iteratorchildren(n:NimNode):NimNode {.inline,...raises:[],tags:[],forbids:[].}
Iterates over the children of the NimNode n. Source   Edit  
iteratoritems(n:NimNode):NimNode {.inline,...raises:[],tags:[],forbids:[].}
Iterates over the children of the NimNode n. Source   Edit  
iteratorpairs(n:NimNode):(int,NimNode) {.inline,...raises:[],tags:[],forbids:[].}
Iterates over the children of the NimNode n and its indices. Source   Edit  

Macros

macrodumpAstGen(s:untyped):untyped

Accepts a block of nim code and prints the parsed abstract syntax tree using the astGenRepr proc. Printing is done at compile time.

You can use this as a tool to write macros quicker by writing example outputs and then copying the snippets into the macro for modification.

For example:

dumpAstGen:echo"Hello, World!"

Outputs:

nnkStmtList.newTree(nnkCommand.newTree(newIdentNode("echo"),newLit("Hello, World!")))

Also see dumpTree and dumpLisp.

Source   Edit  
macrodumpLisp(s:untyped):untyped

Accepts a block of nim code and prints the parsed abstract syntax tree using the lispRepr proc. Printing is done at compile time.

You can use this as a tool to explore the Nim's abstract syntax tree and to discover what kind of nodes must be created to represent a certain expression/statement.

For example:

dumpLisp:echo"Hello, World!"

Outputs:

(StmtList(Command(Ident"echo")(StrLit"Hello, World!")))

Also see dumpAstGen and dumpTree.

Source   Edit  
macrodumpTree(s:untyped):untyped

Accepts a block of nim code and prints the parsed abstract syntax tree using the treeRepr proc. Printing is done at compile time.

You can use this as a tool to explore the Nim's abstract syntax tree and to discover what kind of nodes must be created to represent a certain expression/statement.

For example:

dumpTree:echo"Hello, World!"

Outputs:

StmtListCommandIdent"echo"StrLit"Hello, World!"

Also see dumpAstGen and dumpLisp.

Source   Edit  
macroexpandMacros(body:typed):untyped

Expands one level of macro - useful for debugging. Can be used to inspect what happens when a macro call is expanded, without altering its result.

For instance,

importstd/[sugar,macros]letx=10y=20expandMacros:dump(x+y)

will actually dump x+y, but at the same time will print at compile time the expansion of the dump macro, which in this case is debugEcho["x + y"," = ",x+y].

Source   Edit  
macrogetCustomPragmaVal(n:typed;cp:typed{nkSym}):untyped

Expands to value of custom pragma cp of expression n which is expected to be nnkDotExpr, a proc or a type.

See also hasCustomPragma.

templateserializationKey(key:string){.pragma.}typeMyObj{.serializationKey:"mo".}=objectmyField{.serializationKey:"mf".}:intvaro:MyObjassert(o.myField.getCustomPragmaVal(serializationKey)=="mf")assert(o.getCustomPragmaVal(serializationKey)=="mo")assert(MyObj.getCustomPragmaVal(serializationKey)=="mo")

Source   Edit  
macrohasCustomPragma(n:typed;cp:typed{nkSym}):untyped

Expands to true if expression n which is expected to be nnkDotExpr (if checking a field), a proc or a type has custom pragma cp.

See also getCustomPragmaVal.

templatemyAttr(){.pragma.}typeMyObj=objectmyField{.myAttr.}:intprocmyProc(){.myAttr.}=discardvaro:MyObjassert(o.myField.hasCustomPragma(myAttr))assert(myProc.hasCustomPragma(myAttr))

Source   Edit  
macrounpackVarargs(callee:untyped;args:varargs[untyped]):untyped
Calls callee with args unpacked as individual arguments. This is useful in 2 cases:
  • when forwarding varargs[T] for some typed T
  • when forwarding varargs[untyped] when args can potentially be empty, due to a compiler limitation

Example:

templatecall1(fun:typed;args:varargs[untyped]):untyped=unpackVarargs(fun,args)# when varargsLen(args) > 0: fun(args) else: fun() # this would also worktemplatecall2(fun:typed;args:varargs[typed]):untyped=unpackVarargs(fun,args)procfn1(a=0,b=1)=discard(a,b)call1(fn1,10,11)call1(fn1)# `args` is empty in this caseiffalse:call2(echo,10,11)# would print 1011
Source   Edit  

Templates

templatefindChild(n:NimNode;cond:untyped):NimNode {.dirty.}

Find the first child node matching condition (or nil).

varres=findChild(n,it.kind==nnkPostfixandit.basename.ident==ident"foo")

Source   Edit  
template`or`(x,y:NimNode):NimNode

Evaluate x and when it is not an empty node, return it. Otherwise evaluate to y. Can be used to chain several expressions to get the first expression that is not empty.

letnode=mightBeEmpty()ormightAlsoBeEmpty()orfallbackNode

Source   Edit  
close