summaryrefslogtreecommitdiff
path: root/tests/typ/expr
diff options
context:
space:
mode:
authorLaurenz <laurmaedje@gmail.com>2021-03-03 17:53:40 +0100
committerLaurenz <laurmaedje@gmail.com>2021-03-03 17:53:40 +0100
commitc94a18833f23d2b57de1b87971458fd54b56d088 (patch)
tree9e1ed55cfca15aef6d39ced50a3a5b14d2800aae /tests/typ/expr
parent4d90a066f197264341eff6bf67e8c06cae434eb4 (diff)
Closures and function definitions 🚀
Supports: - Closure syntax: `(x, y) => z` - Shorthand for a single argument: `x => y` - Function syntax: `let f(x) = y` - Capturing of variables from the environment - Error messages for too few / many passed arguments Does not support: - Named arguments - Variadic arguments with `..`
Diffstat (limited to 'tests/typ/expr')
-rw-r--r--tests/typ/expr/closure.typ66
1 files changed, 66 insertions, 0 deletions
diff --git a/tests/typ/expr/closure.typ b/tests/typ/expr/closure.typ
new file mode 100644
index 00000000..d05acaa4
--- /dev/null
+++ b/tests/typ/expr/closure.typ
@@ -0,0 +1,66 @@
+// 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)
+}
+
+---
+// Ref: false
+
+// 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)
+}