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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
discard """
action: compile
"""
template withOpenFile(f: untyped, filename: string, mode: FileMode,
actions: untyped): untyped =
block:
# test that 'f' is implicitly 'injecting':
var f: File
if open(f, filename, mode):
try:
actions
finally:
close(f)
else:
quit("cannot open for writing: " & filename)
withOpenFile(txt, "ttempl3.txt", fmWrite):
writeLine(txt, "line 1")
txt.writeLine("line 2")
var
myVar: array[0..1, int]
# Test zero argument template:
template ha: untyped = myVar[0]
ha = 1
echo(ha)
# Test identifier generation:
template prefix(name): untyped = `"hu" name`
var `hu "XYZ"` = "yay"
echo prefix(XYZ)
template typedef(name: untyped, typ: typeDesc) {.dirty.} =
type
`T name`* = typ
`P name`* = ref `T name`
typedef(myint, int)
var x: PMyInt
# Test UFCS
type
Foo = object
arg: int
proc initFoo(arg: int): Foo =
result.arg = arg
template create(typ: typeDesc, arg: untyped): untyped = `init typ`(arg)
var ff = Foo.create(12)
echo ff.arg
import macros
# bug #11494
macro staticForEach(arr: untyped, body: untyped): untyped =
result = newNimNode(nnkStmtList)
arr.expectKind(nnkBracket)
for n in arr:
let b = copyNimTree(body)
result.add quote do:
block:
type it {.inject.} = `n`
`b`
template forEveryMatchingEntity*() =
staticForEach([int, string, float]):
var a {.inject.}: it
echo a
forEveryMatchingEntity()
|