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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
|
// Test closures.
// Ref: false
---
// Don't parse closure directly in content.
// Ref: true
#let x = "x"
// Should output `x => y`.
#x => y
---
// Basic closure without captures.
{
let adder = (x, y) => x + y
test(adder(2, 3), 5)
}
---
// Pass closure as argument and return closure.
// Also uses shorthand syntax for a single argument.
{
let chain = (f, g) => (x) => f(g(x))
let f = x => x + 1
let g = x => 2 * x
let h = chain(f, g)
test(h(2), 5)
}
---
// Capture environment.
{
let mark = "?"
let greet = {
let hi = "Hi"
name => {
hi + ", " + name + mark
}
}
test(greet("Typst"), "Hi, Typst?")
mark = "!"
test(greet("Typst"), "Hi, Typst!")
}
---
// Redefined variable.
{
let x = 1
let f() = {
let x = x + 2
x
}
test(f(), 3)
}
---
// Import bindings.
{
let b = "target.typ"
let f() = {
import b from b
b
}
test(f(), 1)
}
---
// For loop bindings.
{
let v = (1, 2, 3)
let s = 0
let f() = {
for v in v { s += v }
}
f()
test(s, 6)
}
---
// Let + closure bindings.
{
let g = "hi"
let f() = {
let g() = "bye"
g()
}
test(f(), "bye")
}
---
// Parameter bindings.
{
let x = 5
let g() = {
let f(x, y: x) = x + y
f
}
test(g()(8), 13)
}
---
// Don't leak environment.
{
// Error: 16-17 unknown variable
let func() = x
let x = "hi"
func()
}
---
// Too few arguments.
{
let types(x, y) = "[" + type(x) + ", " + type(y) + "]"
test(types(14%, 12pt), "[ratio, length]")
// Error: 13-21 missing argument: y
test(types("nope"), "[string, none]")
}
---
// Too many arguments.
{
let f(x) = x + 1
// Error: 8-13 unexpected argument
f(1, "two", () => x)
}
---
// Named arguments.
{
let greet(name, birthday: false) = {
if birthday { "Happy Birthday, " } else { "Hey, " } + name + "!"
}
test(greet("Typst"), "Hey, Typst!")
test(greet("Typst", birthday: true), "Happy Birthday, Typst!")
// Error: 23-35 unexpected argument
test(greet("Typst", whatever: 10))
}
|