作者: | Andreas Rumpf |
---|---|
版本: | |nimversion| |
介绍
"Repetition renders the ridiculous reasonable." -- Norman Wildberger
这篇文档是 Nim 编程语言高级部分的教程。**注意这篇文档可能已经过时** manual 中包含有更多关于语言高级特性的示例。
编译注记
编译注记是 Nim 用于告知编译器附加信息/命令的方法,以免定义一堆新关键字。 编译注记包含于特殊的 {. 和 .} 花括号点对之中。本教程没有介绍编译 注记的具体内容,了解可用的编译注记可从 manual 或 user guide 中获取。
面向对象编程
Nim 的面向对象(OOP)支持简约而优雅,你可以自由地使用强大的 OOP 技术。显然 OOP 是 一种 程序设计的方式,但这方式并不 唯一 。通常,使用过程式的编程方式编写的 代码更加有效。特别地,组合通常比继承更佳。
Objects
和 tuples 一样,objects 是一种把不同的值用结构的方式打包在一起的方法。但 objects 提供了很多 tuples 没有的特性,如:继承与信息隐藏。因为 objects 包装了数据,对象 构造器 T() 只能在内部使用,程序员应该提供一个初始化对象的 proc (称做 构造器 )。
可以在运行时访问 Objects 的类型。``of`` 运算符能用于检查 object 的类型:
type Person = object of RootObj name*: string # * 表示 `name` 可以从其他模块访问 age: int # 没有 * 意味着这个字段对其他模块而言是不可见的 Student = object of Person # Student 继承自 Person id: int # 另有一个 id 字段 var student: Student person: Person assert(student of Student) # is true # 对象构造: student = Student(name: "Anton", age: 5, id: 2)
Object 中的字段若希望在本模块之外的地方使用,则必须用 * 标记。不同于 tuples, 不同的 object 绝不 相等 。新的 object 类型只能在 type 块内定义。
继承用 object of 的语法实现,多重继承尚未支持。如果类型没有合适的基类(ancestor), 可以使用 RootObj 作为其基类,但这只是一个惯例。没有指定基类的 Objects 会被隐式 指定为 final 的,你可以用 inheritable 编译注记来指定一个新的对象基类(roots), 而不是 system.RootObj 。(如GTK的包装器)。
注意: 对于代码重用,组合 (has-a 关系) 通常比继承 (is-a 关系) 更好,Nim 中的 objects 是值类型,因而组合与继承的效率相当。
互递归类型
Objects, tuples 及引用(references)可以塑造出相互依赖的相当复杂的数据结构。称作 互递归 。 在 Nim 中,这些类型只能在单个 type 块中声明。(不在此 type 块中的其它任何的符号,需要回溯 搜索会导致降低编译速度。)
例:
type Node = ref NodeObj # 建立了一个对 NodeObj 的跟踪引用 NodeObj = object le, ri: Node # 左右子树 sym: ref Sym # 叶子包含了对 Sym 的引用 Sym = object # 符号 name: string # 符号的名字 line: int # 符号声明所在的行 code: PNode # 符号的抽象语法树
类型转换
Nim 区分了 类型强转(cast) 与 类型转换 。强转使用 cast 运算符 强制编译器按位的方式将原始类型转为新的类型。
类型转换将一个类型转为另一个类型的方式更加文雅:它维持了抽象的 值 ,而不必用 位模式 。如果不能进行转换,编译器就会发挠骚或者引发一个异常。
类型转换的语法为 目标类型(要转换的表达式) (就像普通调用一样):
proc getID(x: Person): int = Student(x).id
如果 x 不是 Student ,将会引发 InvalidObjectConversionError 异常。
对象可变量
在实际场景中,如果只是需要一个简单的可变类型,用对象继承通常就有点大材小用了。
例:
# 这是一个关于怎么在 Nim 中模拟抽象语法树的例子 type NodeKind = enum # 不用的节点类型 nkInt, # 整数叶子 nkFloat, # 浮点叶子 nkString, # 字符串叶子 nkAdd, # 加法 nkSub, # 减法 nkIf # if语句 Node = ref NodeObj NodeObj = object case kind: NodeKind # ``kind`` 字段是一个识别器 of nkInt: intVal: int of nkFloat: floatVal: float of nkString: strVal: string of nkAdd, nkSub: leftOp, rightOp: PNode of nkIf: condition, thenPart, elsePart: PNode var n = PNode(kind: nkFloat, floatVal: 1.0) # 下面的语句引发一个 `FieldError` 异常,因为 n.kind 的值不匹配 n.strVal = ""
从例子中可以看到,对象可变量较对象继承还有一个优点,不需要对不同的类型作类型 转换。当然,访问无效的对象字段会引发异常。
方法
在传统的面向对象语言中,过程(也叫作 方法 )与类绑定在一起。这样有一些缺点:
- 无法向类中添加方法,或者必须使用丑陋的变通手段。
- 方法究竟属于谁通常很纠结: join 是 string 的方法呢还是 array的方法呢?
Nim 并不将方法指定给类,因此回避了这些问题。所有的方法在 Nim 中都是复方法( multi-methods)。随后我们会看到,复方法不同于 proc ,它只用于动态绑定。
方法调用的语法
对于日常的调用有一个语法糖: 可以用 对象.方法(参数) 的语法代替 方法(对象,参数) 的形式。如果没有 剩余参数,小括号可以省去: 对象.len (本来是 len(对象) )。
这种调用的语法不局限于对象,可用于任何类型:
echo("abc".len) # 与 echo(len("abc")) 同 echo("abc".toUpper()) echo({'a', 'b', 'c'}.card) stdout.writeln("Hallo") # 与 writeln(stdout, "Hallo") 同
(另一个方法调用语法要注意的点是,它提供了原本没有的后缀记法)
所以"纯面向对象"的代码写起来很容易:
import strutils stdout.writeln("Give a list of numbers (separated by spaces): ") stdout.write(stdin.readLine.split.map(parseInt).max.`$`) stdout.writeln(" is the maximum!")
Properties
As the above example shows, Nim has no need for get-properties: Ordinary get-procedures that are called with the method call syntax achieve the same. But setting a value is different; for this a special setter syntax is needed:
type Socket* = object of RootObj FHost: int # cannot be accessed from the outside of the module # the `F` prefix is a convention to avoid clashes since # the accessors are named `host` proc `host=`*(s: var Socket, value: int) {.inline.} = ## setter of hostAddr s.FHost = value proc host*(s: Socket): int {.inline.} = ## getter of hostAddr s.FHost var s: Socket s.host = 34 # same as `host=`(s, 34)
(The example also shows inline procedures.)
The [] array access operator can be overloaded to provide array properties:
type Vector* = object x, y, z: float proc `[]=`* (v: var Vector, i: int, value: float) = # setter case i of 0: v.x = value of 1: v.y = value of 2: v.z = value else: assert(false) proc `[]`* (v: Vector, i: int): float = # getter case i of 0: result = v.x of 1: result = v.y of 2: result = v.z else: assert(false)
The example is silly, since a vector is better modelled by a tuple which already provides v[] access.
Dynamic dispatch
Procedures always use static dispatch. For dynamic dispatch replace the proc keyword by method:
type PExpr = ref object of RootObj ## abstract base class for an expression PLiteral = ref object of PExpr x: int PPlusExpr = ref object of PExpr a, b: PExpr # watch out: 'eval' relies on dynamic binding method eval(e: PExpr): int = # override this base method quit "to override!" method eval(e: PLiteral): int = e.x method eval(e: PPlusExpr): int = eval(e.a) + eval(e.b) proc newLit(x: int): PLiteral = PLiteral(x: x) proc newPlus(a, b: PExpr): PPlusExpr = PPlusExpr(a: a, b: b) echo eval(newPlus(newPlus(newLit(1), newLit(2)), newLit(4)))
Note that in the example the constructors newLit and newPlus are procs because it makes more sense for them to use static binding, but eval is a method because it requires dynamic binding.
In a multi-method all parameters that have an object type are used for the dispatching:
type Thing = object of RootObj Unit = object of Thing x: int method collide(a, b: Thing) {.inline.} = quit "to override!" method collide(a: Thing, b: Unit) {.inline.} = echo "1" method collide(a: Unit, b: Thing) {.inline.} = echo "2" var a, b: Unit collide(a, b) # output: 2
As the example demonstrates, invocation of a multi-method cannot be ambiguous: Collide 2 is preferred over collide 1 because the resolution works from left to right. Thus Unit, Thing is preferred over Thing, Unit.
Performance note: Nim does not produce a virtual method table, but generates dispatch trees. This avoids the expensive indirect branch for method calls and enables inlining. However, other optimizations like compile time evaluation or dead code elimination do not work with methods.
Exceptions
In Nim exceptions are objects. By convention, exception types are suffixed with 'Error'. The system module defines an exception hierarchy that you might want to stick to. Exceptions derive from system.Exception, which provides the common interface.
Exceptions have to be allocated on the heap because their lifetime is unknown. The compiler will prevent you from raising an exception created on the stack. All raised exceptions should at least specify the reason for being raised in the msg field.
A convention is that exceptions should be raised in exceptional cases: For example, if a file cannot be opened, this should not raise an exception since this is quite common (the file may not exist).
Raise statement
Raising an exception is done with the raise statement:
var e: ref OSError new(e) e.msg = "the request to the OS failed" raise e
If the raise keyword is not followed by an expression, the last exception is re-raised. For the purpose of avoiding repeating this common code pattern, the template newException in the system module can be used:
raise newException(OSError, "the request to the OS failed")
Try statement
The try statement handles exceptions:
# read the first two lines of a text file that should contain numbers # and tries to add them var f: File if open(f, "numbers.txt"): try: let a = readLine(f) let b = readLine(f) echo "sum: ", parseInt(a) + parseInt(b) except OverflowError: echo "overflow!" except ValueError: echo "could not convert string to integer" except IOError: echo "IO error!" except: echo "Unknown exception!" # reraise the unknown exception: raise finally: close(f)
The statements after the try are executed unless an exception is raised. Then the appropriate except part is executed.
The empty except part is executed if there is an exception that is not explicitly listed. It is similar to an else part in if statements.
If there is a finally part, it is always executed after the exception handlers.
The exception is consumed in an except part. If an exception is not handled, it is propagated through the call stack. This means that often the rest of the procedure - that is not within a finally clause - is not executed (if an exception occurs).
If you need to access the actual exception object or message inside an except branch you can use the getCurrentException() and getCurrentExceptionMsg() procs from the system module. Example:
try: doSomethingHere() except: let e = getCurrentException() msg = getCurrentExceptionMsg() echo "Got exception ", repr(e), " with message ", msg
Annotating procs with raised exceptions
Through the use of the optional {.raises.} pragma you can specify that a proc is meant to raise a specific set of exceptions, or none at all. If the {.raises.} pragma is used, the compiler will verify that this is true. For instance, if you specify that a proc raises IOError, and at some point it (or one of the procs it calls) starts raising a new exception the compiler will prevent that proc from compiling. Usage example:
proc complexProc() {.raises: [IOError, ArithmeticError].} = ... proc simpleProc() {.raises: [].} = ...
Once you have code like this in place, if the list of raised exception changes the compiler will stop with an error specifying the line of the proc which stopped validating the pragma and the raised exception not being caught, along with the file and line where the uncaught exception is being raised, which may help you locate the offending code which has changed.
If you want to add the {.raises.} pragma to existing code, the compiler can also help you. You can add the {.effects.} pragma statement to your proc and the compiler will output all inferred effects up to that point (exception tracking is part of Nim's effect system). Another more roundabout way to find out the list of exceptions raised by a proc is to use the Nim doc2 command which generates documentation for a whole module and decorates all procs with the list of raised exceptions. You can read more about Nim's effect system and related pragmas in the manual.
Generics
Generics are Nim's means to parametrize procs, iterators or types with type parameters. They are most useful for efficient type safe containers:
type BinaryTreeObj[T] = object # BinaryTree is a generic type with # with generic param ``T`` le, ri: BinaryTree[T] # left and right subtrees; may be nil data: T # the data stored in a node BinaryTree*[T] = ref BinaryTreeObj[T] # type that is exported proc newNode*[T](data: T): BinaryTree[T] = # constructor for a node new(result) result.data = data proc add*[T](root: var BinaryTree[T], n: BinaryTree[T]) = # insert a node into the tree if root == nil: root = n else: var it = root while it != nil: # compare the data items; uses the generic ``cmp`` proc # that works for any type that has a ``==`` and ``<`` operator var c = cmp(it.data, n.data) if c < 0: if it.le == nil: it.le = n return it = it.le else: if it.ri == nil: it.ri = n return it = it.ri proc add*[T](root: var BinaryTree[T], data: T) = # convenience proc: add(root, newNode(data)) iterator preorder*[T](root: BinaryTree[T]): T = # Preorder traversal of a binary tree. # Since recursive iterators are not yet implemented, # this uses an explicit stack (which is more efficient anyway): var stack: seq[BinaryTree[T]] = @[root] while stack.len > 0: var n = stack.pop() while n != nil: yield n.data add(stack, n.ri) # push right subtree onto the stack n = n.le # and follow the left pointer var root: BinaryTree[string] # instantiate a BinaryTree with ``string`` add(root, newNode("hello")) # instantiates ``newNode`` and ``add`` add(root, "world") # instantiates the second ``add`` proc for str in preorder(root): stdout.writeln(str)
The example shows a generic binary tree. Depending on context, the brackets are used either to introduce type parameters or to instantiate a generic proc, iterator or type. As the example shows, generics work with overloading: the best match of add is used. The built-in add procedure for sequences is not hidden and is used in the preorder iterator.
Templates
Templates are a simple substitution mechanism that operates on Nim's abstract syntax trees. Templates are processed in the semantic pass of the compiler. They integrate well with the rest of the language and share none of C's preprocessor macros flaws.
To invoke a template, call it like a procedure.
Example:
template `!=` (a, b: expr): expr = # this definition exists in the System module not (a == b) assert(5 != 6) # the compiler rewrites that to: assert(not (5 == 6))
The !=, >, >=, in, notin, isnot operators are in fact templates: this has the benefit that if you overload the == operator, the != operator is available automatically and does the right thing. (Except for IEEE floating point numbers - NaN breaks basic boolean logic.)
a > b is transformed into b < a. a in b is transformed into contains(b, a). notin and isnot have the obvious meanings.
Templates are especially useful for lazy evaluation purposes. Consider a simple proc for logging:
const debug = true proc log(msg: string) {.inline.} = if debug: stdout.writeln(msg) var x = 4 log("x has the value: " & $x)
This code has a shortcoming: if debug is set to false someday, the quite expensive $ and & operations are still performed! (The argument evaluation for procedures is eager).
Turning the log proc into a template solves this problem:
const debug = true template log(msg: string) = if debug: stdout.writeln(msg) var x = 4 log("x has the value: " & $x)
The parameters' types can be ordinary types or the meta types expr (stands for expression), stmt (stands for statement) or typedesc (stands for type description). If the template has no explicit return type, stmt is used for consistency with procs and methods.
If there is a stmt parameter it should be the last in the template declaration. The reason is that statements can be passed to a template via a special : syntax:
template withFile(f: expr, filename: string, mode: FileMode, body: stmt): stmt {.immediate.} = let fn = filename var f: File if open(f, fn, mode): try: body finally: close(f) else: quit("cannot open: " & fn) withFile(txt, "ttempl3.txt", fmWrite): txt.writeln("line 1") txt.writeln("line 2")
In the example the two writeln statements are bound to the body parameter. The withFile template contains boilerplate code and helps to avoid a common bug: to forget to close the file. Note how the let fn = filename statement ensures that filename is evaluated only once.
Macros
Macros enable advanced compile-time code transformations, but they cannot change Nim's syntax. However, this is no real restriction because Nim's syntax is flexible enough anyway. Macros have to be implemented in pure Nim code if the foreign function interface (FFI) is not enabled in the compiler, but other than that restriction (which at some point in the future will go away) you can write any kind of Nim code and the compiler will run it at compile time.
There are two ways to write a macro, either generating Nim source code and letting the compiler parse it, or creating manually an abstract syntax tree (AST) which you feed to the compiler. In order to build the AST one needs to know how the Nim concrete syntax is converted to an abstract syntax tree (AST). The AST is documented in the macros module.
Once your macro is finished, there are two ways to invoke it:
- invoking a macro like a procedure call (expression macros)
- invoking a macro with the special macrostmt syntax (statement macros)
Expression Macros
The following example implements a powerful debug command that accepts a variable number of arguments:
# to work with Nim syntax trees, we need an API that is defined in the # ``macros`` module: import macros macro debug(n: varargs[expr]): stmt = # `n` is a Nim AST that contains a list of expressions; # this macro returns a list of statements: result = newNimNode(nnkStmtList, n) # iterate over any argument that is passed to this macro: for i in 0..n.len-1: # add a call to the statement list that writes the expression; # `toStrLit` converts an AST to its string representation: result.add(newCall("write", newIdentNode("stdout"), toStrLit(n[i]))) # add a call to the statement list that writes ": " result.add(newCall("write", newIdentNode("stdout"), newStrLitNode(": "))) # add a call to the statement list that writes the expressions value: result.add(newCall("writeln", newIdentNode("stdout"), n[i])) var a: array[0..10, int] x = "some string" a[0] = 42 a[1] = 45 debug(a[0], a[1], x)
The macro call expands to:
write(stdout, "a[0]") write(stdout, ": ") writeln(stdout, a[0]) write(stdout, "a[1]") write(stdout, ": ") writeln(stdout, a[1]) write(stdout, "x") write(stdout, ": ") writeln(stdout, x)
Statement Macros
Statement macros are defined just as expression macros. However, they are invoked by an expression following a colon.
The following example outlines a macro that generates a lexical analyzer from regular expressions:
macro case_token(n: stmt): stmt = # creates a lexical analyzer from regular expressions # ... (implementation is an exercise for the reader :-) discard case_token: # this colon tells the parser it is a macro statement of r"[A-Za-z_]+[A-Za-z_0-9]*": return tkIdentifier of r"0-9+": return tkInteger of r"[\+\-\*\?]+": return tkOperator else: return tkUnknown
Building your first macro
To give a footstart to writing macros we will show now how to turn your typical dynamic code into something that compiles statically. For the exercise we will use the following snippet of code as the starting point:
import strutils, tables proc readCfgAtRuntime(cfgFilename: string): Table[string, string] = let inputString = readFile(cfgFilename) var source = "" result = initTable[string, string]() for line in inputString.splitLines: # Ignore empty lines if line.len < 1: continue var chunks = split(line, ',') if chunks.len != 2: quit("Input needs comma split values, got: " & line) result[chunks[0]] = chunks[1] if result.len < 1: quit("Input file empty!") let info = readCfgAtRuntime("data.cfg") when isMainModule: echo info["licenseOwner"] echo info["licenseKey"] echo info["version"]
Presumably this snippet of code could be used in a commercial software, reading a configuration file to display information about the person who bought the software. This external file would be generated by an online web shopping cart to be included along the program containing the license information:
version,1.1 licenseOwner,Hyori Lee licenseKey,M1Tl3PjBWO2CC48m
The readCfgAtRuntime proc will open the given filename and return a Table from the tables module. The parsing of the file is done (without much care for handling invalid data or corner cases) using the splitLines proc from the strutils module. There are many things which can fail; mind the purpose is explaining how to make this run at compile time, not how to properly implement a DRM scheme.
The reimplementation of this code as a compile time proc will allow us to get rid of the data.cfg file we would need to distribute along the binary, plus if the information is really constant, it doesn't make from a logical point of view to have it mutable in a global variable, it would be better if it was a constant. Finally, and likely the most valuable feature, we can implement some verification at compile time. You could think of this as a better unit testing, since it is impossible to obtain a binary unless everything is correct, preventing you to ship to users a broken program which won't start because a small critical file is missing or its contents changed by mistake to something invalid.
Generating source code
Our first attempt will start by modifying the program to generate a compile time string with the generated source code, which we then pass to the parseStmt proc from the macros module. Here is the modified source code implementing the macro:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import macros, strutils macro readCfgAndBuildSource(cfgFilename: string): stmt = let inputString = slurp(cfgFilename.strVal) var source = "" for line in inputString.splitLines: # Ignore empty lines if line.len < 1: continue var chunks = split(line, ',') if chunks.len != 2: error("Input needs comma split values, got: " & line) source &= "const cfg" & chunks[0] & "= \"" & chunks[1] & "\"\n" if source.len < 1: error("Input file empty!") result = parseStmt(source) readCfgAndBuildSource("data.cfg") when isMainModule: echo cfglicenseOwner echo cfglicenseKey echo cfgversion |
The good news is not much has changed! First, we need to change the handling of the input parameter (line 3). In the dynamic version the readCfgAtRuntime proc receives a string parameter. However, in the macro version it is also declared as string, but this is the outside interface of the macro. When the macro is run, it actually gets a PNimNode object instead of a string, and we have to call the strVal proc (line 5) from the macros module to obtain the string being passed in to the macro.
Second, we cannot use the readFile proc from the system module due to FFI restriction at compile time. If we try to use this proc, or any other which depends on FFI, the compiler will error with the message cannot evaluate and a dump of the macro's source code, along with a stack trace where the compiler reached before bailing out. We can get around this limitation by using the slurp proc from the system module, which was precisely made for compilation time (just like gorge which executes an external program and captures its output).
The interesting thing is that our macro does not return a runtime Table object. Instead, it builds up Nim source code into the source variable. For each line of the configuration file a const variable will be generated (line 15). To avoid conflicts we prefix these variables with cfg. In essence, what the compiler is doing is replacing the line calling the macro with the following snippet of code:
const cfgversion= "1.1" const cfglicenseOwner= "Hyori Lee" const cfglicenseKey= "M1Tl3PjBWO2CC48m"
You can verify this yourself adding the line echo source somewhere at the end of the macro and compiling the program. Another difference is that instead of calling the usual quit proc to abort (which we could still call) this version calls the error proc (line 14). The error proc has the same behavior as quit but will dump also the source and file line information where the error happened, making it easier for the programmer to find where compilation failed. In this situation it would point to the line invoking the macro, but not the line of data.cfg we are processing, that's something the macro itself would need to control.
Generating AST by hand
To generate an AST we would need to intimately know the structures used by the Nim compiler exposed in the macros module, which at first look seems a daunting task. But we can use as helper shortcut the dumpTree macro, which is used as a statement macro instead of an expression macro. Since we know that we want to generate a bunch of const symbols we can create the following source file and compile it to see what the compiler expects from us:
import macros dumpTree: const cfgversion: string = "1.1" const cfglicenseOwner= "Hyori Lee" const cfglicenseKey= "M1Tl3PjBWO2CC48m"
During compilation of the source code we should see the following lines in the output (again, since this is a macro, compilation is enough, you don't have to run any binary):
StmtList ConstSection ConstDef Ident !"cfgversion" Ident !"string" StrLit 1.1 ConstSection ConstDef Ident !"cfglicenseOwner" Empty StrLit Hyori Lee ConstSection ConstDef Ident !"cfglicenseKey" Empty StrLit M1Tl3PjBWO2CC48m
With this output we have a better idea of what kind of input the compiler expects. We need to generate a list of statements. For each constant the source code generates a ConstSection and a ConstDef. If we were to move all the constants to a single const block we would see only a single ConstSection with three children.
Maybe you didn't notice, but in the dumpTree example the first constant explicitly specifies the type of the constant. That's why in the tree output the two last constants have their second child Empty but the first has a string identifier. So basically a const definition is made up from an identifier, optionally a type (can be an empty node) and the value. Armed with this knowledge, let's look at the finished version of the AST building macro:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import macros, strutils macro readCfgAndBuildAST(cfgFilename: string): stmt = let inputString = slurp(cfgFilename.strVal) result = newNimNode(nnkStmtList) for line in inputString.splitLines: # Ignore empty lines if line.len < 1: continue var chunks = split(line, ',') if chunks.len != 2: error("Input needs comma split values, got: " & line) var section = newNimNode(nnkConstSection) constDef = newNimNode(nnkConstDef) constDef.add(newIdentNode("cfg" & chunks[0])) constDef.add(newEmptyNode()) constDef.add(newStrLitNode(chunks[1])) section.add(constDef) result.add(section) if result.len < 1: error("Input file empty!") readCfgAndBuildAST("data.cfg") when isMainModule: echo cfglicenseOwner echo cfglicenseKey echo cfgversion |
Since we are building on the previous example generating source code, we will only mention the differences to it. Instead of creating a temporary string variable and writing into it source code as if it were written by hand, we use the result variable directly and create a statement list node (nnkStmtList) which will hold our children (line 7).
For each input line we have to create a constant definition (nnkConstDef) and wrap it inside a constant section (nnkConstSection). Once these variables are created, we fill them hierarchichally (line 17) like the previous AST dump tree showed: the constant definition is a child of the section definition, and the constant definition has an identifier node, an empty node (we let the compiler figure out the type), and a string literal with the value.
A last tip when writing a macro: if you are not sure the AST you are building looks ok, you may be tempted to use the dumpTree macro. But you can't use it inside the macro you are writting/debugging. Instead echo the string generated by treeRepr. If at the end of the this example you add echo treeRepr(result) you should get the same output as using the dumpTree macro, but of course you can call that at any point of the macro where you might be having troubles.