summaryrefslogtreecommitdiff
path: root/tests/typ/code/closure.typ
blob: 86a6f63284a01d75aec788337bca790113d54883 (plain) (blame)
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
// Test closures.
// Ref: false

---

// 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!")
}

// Don't leak environment.
{
    // Error: 18-19 unknown variable
    let func() = x
    let x = "hi"

    test(func(), error)
}

---
// Too few arguments.
{
    let types(x, y) = "[" + type(x) + ", " + type(y) + "]"
    test(types(14%, 12pt), "[relative, length]")

    // Error: 16-22 missing argument: y
    test(types("nope"), "[string, none]")
}

// Too many arguments.
{
    let f(x) = x + 1

    // Error: 2:10-2:15 unexpected argument
    // Error: 1:17-1:24 unexpected argument
    f(1, "two", () => x)
}