knotflow Lessons PDF ↓ Deutsch Handbook Modeller ↗ Source

Lesson 2.1 · II The language

Building a language

What it's about: How text becomes a model: the lexer, parser and evaluator of a language of its own. The twisted vase from Lesson 1.3 is a text file:

param twist = 90 in 0..360 "Twist at the top [°]"

fn section(t) = polygon(6, 40 + 15 * sin(t * 180))
  |> rotate(t * twist)
  |> move(z: t * 200)

export loft([section(t) | t <- linspace(0, 1, 9)], degree: 3)

kf render examples/vase.kf -D twist=180 -o vase.stl turns it into an STL. This lesson shows what happens between the text and the triangles, and why the language is functional. There are three stages, each smaller than you might expect:

Text ──Lexer──► Tokens ──Parser──► Syntax tree ──Evaluation──► Values (numbers, curves, surfaces)

The code lives in crates/lang/src/: lexer, parser, evaluator and the built-in functions (one file per group).

1. A few decisions first

The whole language on one page is at the start of Lesson 2.2; kf help shows every built-in function with its parameters. For this lesson, a few decisions that run through everything are enough:

2. Stage 1: The lexer splits the text into tokens

A token is the smallest piece that carries meaning: a number, a name, an operator. Spaces and comments disappear at this stage.

let r = h / 2   // half the diameter

becomes

[let] [Name r] [=] [Name h] [/] [Number 2]

This is plain legwork, one character after another. The only tricky part is characters with several meanings: 1.5 is a number, but 1..5 is three tokens (1, .., 5), and ... is something else again. <- is a token of its own – which is why "x less than minus 1" has to be written with a space: x < -1. (Haskell has the same quirk.) Each token also remembers which character it starts and ends at – the error messages need that.

3. Stage 2: The parser builds a tree

The parser recognises the structure. 40 + bulge * sin(t * 180) becomes a syntax tree:

        +
       / \
     40   *
         / \
    bulge   sin( )
              |
              *
             / \
            t   180

Whatever is computed first sits lower in the tree. The only question is: how does the parser know that * comes before +?

Binding power (Pratt parsing)

Each operator gets a number, its binding power:

Operator Power
or 2
and 3
not 4
== < >= … 5
|> 6
>> (Lesson 2.2) 7
+ - ++ 8
* / % 9
-x (sign) 10
^ 11

|> binds more tightly than comparisons and logic, as in Elixir: xs |> len == 3 means (xs |> len) == 3. If it bound the weakest, it would mean xs |> (len == 3) – hardly ever intended (Lesson 2.3).

The method behind it (after Vaughan Pratt) is short: read a value. Look at the next operator. If it is stronger than the one you are currently working on, the next value belongs to it – so read the right-hand part recursively first. Otherwise your subexpression is finished. Take 1 + 2 * 3: after 1 + comes 2, then * – stronger than +, so the 2 belongs to the *. Result: 1 + (2 * 3).

Small subtleties that come out right on their own:

Syntactic sugar

Some things never appear in the tree. The parser rewrites sections |> rotate(30) directly to rotate(sections, 30), zs.map(f) to map(zs, f), and Haskell's sections to lambdas: (* 2) becomes x => x * 2, (2 ^) becomes x => 2 ^ x, (+) becomes (a, b) => a + b. This is called syntactic sugar: nicer to write, but nothing new for the evaluation. One exception, as in Haskell: (- 1) is the number −1, not a section. And a section has exactly one operand: (* 2 + 1) is an error, because a reader can't tell whether x * 2 + 1 or x * (2 + 1) is meant. You write (* (2 + 1)).

4. Stage 3: Evaluation

Evaluation walks the tree from the bottom up and computes a value for each node. There are these kinds of values:

Kind Example made by
number 1.5 numbers, arithmetic
truth value true comparisons, and, or, not
text "height" texts, text, read
point (1, 2), (1, 2, 3) tuples of numbers; calculates like a vector
tuple (1, "a") tuples that are not all numbers, such as those from zip
list [1, 2, 3] lists, comprehensions, range; a list of shapes is a group
record {w: 3, h: 8} named fields (Lesson 2.2)
function x => x * 2 fn, lambdas, sections
curve circle(10) curves, outlines, lettering (Lesson 1.2)
surface revolve(…) revolve, extrude, loft, sweep (Lesson 1.3)
perforated solid perforate(…) a solid with holes (Lesson 3.5)
solid union(a, b) Booleans, shell, solid (Lesson 3.4)
mesh relief(…) triangles directly, from relief, plate or isosurface (Lesson 1.3)
implicit shape blend(…) rods and balls that melt together (Lesson 3.14)
instances instance(…) many copies of one shape, tessellated once (Lesson 3.1)
field grid(…) a number per cell of a grid: height, distance, density; from grid, image, sdf (Lessons 2.5, 3.13)
table table(…) values at every combination of named axes (Lesson 2.5)
bytes read_bytes(…) a file as it is: a font, a picture (Lesson 2.5)

Where do the names live? In an environment (also called a scope): a table from name to value. The outermost one holds the built-in functions and pi. Every param and let adds a name to it. When you call a function, it gets its own small environment for its parameters, which passes lookups on to the outer one. where also opens a small environment:

fn ring(r, thick) = revolve(tube)
  where tube = circle(thick / 2) |> move(x: r)

Lambdas remember where they were made

let k = 3
let times_k = x => x * k
let a = times_k(2)          // 6

times_k needs k, but k is not a parameter. So the lambda remembers the environment it was written in. A function with its environment packed in like this is called a closure. Since values never change, nothing can go wrong here.

5. Lists: explicit rather than automatic

Node editors do it like this: when a function receives a list where it expects a single value, it automatically works through the list element by element (broadcasting). [1, 2, 3] * 2 would be [2, 4, 6], and the vase would need no loop:

let sections = polygon(6, 40 + 15 * sin(t * 180)) |> rotate(t * twist) |> move(z: zs)

That is short and elegant – and it has three traps:

  1. Your own functions are second-class citizens. fn absolute(x) = if x < 0 then -x else x works with -3, but not with [-3, 4]: if can't test a list of truth values. Built-in functions "understand" lists, your own don't.
  2. Meanings flip. [1, 2] == [1, 2] would give [true, true] instead of true.
  3. "One or many?" is ambiguous. circle([10, 20]) |> move(z: [0, 5, 10]) – in pairs (doesn't fit) or every radius at every height? In a case like this, node editors silently repeat the last element, and for nested lists they later need special "data trees" with commands of their own to reshape them.

So the rule in knotflow is: lists are never processed automatically. * and + only work with numbers and points. What should happen to each element, you write down – and functional programming has the tools for that:

Tool Example Result
map [1, 2, 3].map((* 10)) [10, 20, 30]
filter [1, 5, 2].filter((> 1)) [5, 2]
fold fold([1, 2, 3], 0, (+)) 6
zip zip([1, 2], [5, 6]) [(1, 5), (2, 6)]
product product([1, 2], [5, 6]) [(1, 5), (1, 6), (2, 5), (2, 6)]
enumerate enumerate([7, 8]) [(0, 7), (1, 8)]
++ [1, 2] ++ [3] [1, 2, 3]

As a side effect, the vase becomes easier to read: how a cross-section is made is in one place (fn section(t)), instead of being spread over three pipe stages with three parallel lists.

6. Comprehensions: set notation

From mathematics you know {2x | x ∈ M, x > 0}. Haskell turned this into the list comprehension, and knotflow adopts it:

[2 * x | x <- xs, x > 0]

Left of the | is what comes out. On the right are generators (x <- xs: "for each x in xs") and filters (conditions). Several generators nest inside each other, like nested loops:

[(x, y) | x <- [1, 2], y <- [5, 6]]            // all combinations
[polygon(6, r) |> move(z: z) | (r, z) <- zip(radii, heights)]   // in pairs

This answers the question "in pairs or every one with every other?" before it comes up: you can see it. A single notation covers map, filter and the cross product.

7. Patterns and equations (pattern matching)

A pattern takes a value apart and gives names to the pieces:

let (x, y) = (3, 4)                       // x = 3, y = 4
[r + z | (r, z) <- zip(radii, heights)]   // unpack each pair

Patterns can also check: 0 only matches the number 0, [] only the empty list, [x, ...rest] any list with at least one element (x is the first, rest is the rest), and _ matches anything without giving it a name.

This leads to one of the nicest ideas from Haskell: a function in several equations. The equations are tried from top to bottom; the first one whose patterns match wins:

fn fact(0) = 1
fn fact(n) = n * fact(n - 1)

fn total([])           = 0
fn total([x, ...rest]) = x + total(rest)

A condition after | (a guard) narrows an equation down further:

fn radius(k) | k % 2 == 0 = outer         // even corners of the star: outside
fn radius(_)              = inner         // all others: inside

This is made for "0 = auto" from Lesson 1.1 – the special case becomes an equation of its own:

fn rib_count(0, rt) = max(6, 3 * round(2 * pi * rt / 75 / 3))   // 0 means: automatic
fn rib_count(n, _)  = n

If no equation matches, you get a clear message instead of a wrong result (section 9).

That this works without static type checking is no accident: Erlang and Elixir – also dynamically typed – work exactly like this. What knotflow deliberately does not take from Haskell is currying (rotate 30 shape without parentheses): it doesn't get along with named and optional arguments such as polygon(6, r: 40), and without a type checker that checks everything before running, a forgotten argument would silently create half a function whose error only shows up much later.

How deep may recursion go?

Each nested call needs room on the stack, the memory in which the program remembers where to return to after a call. So the language allows 1000 nested calls, 250 in the browser, and then reports "endless recursion?". The limit does not apply to tail calls: if the recursive call is the last thing a function does (fn count(n, acc) = count(n - 1, acc + 1)), the evaluation jumps straight into the next call, up to 5 million times in a row. Lesson 4.1 explains how that is built and why the browser is tighter. For long lists you would use fold or a comprehension anyway.

8. One table for everything

Every built-in function appears exactly once in a table: its name, its group, its parameters with type and default, one sentence of description and the code that runs it. For rotate these are three parameters: geometry (a shape), angle (a number) and axis (a vector, the upright axis if not given). A flag also says whether the result is worth remembering (Lesson 4.2): for expensive functions such as isosurface, whose computation takes much longer than checking their arguments.

Everything else follows from this automatically: how arguments are matched up (in order or by name), which types are allowed, the error messages, kf help, the help and autocompletion in the browser editor and in the language server (Lesson 4.4) and the language reference for AI assistants (docs/llms.txt, Lesson 4.5). A new function is a new table entry.

9. Error messages

Every token knows its position, and so does every tree node. So every message can show exactly where things go wrong – and, where possible, how to get it right:

error: circle: r must be a number, got a list (for every element of a list: map or [… | x <- list])
 --> rings.kf:2:20
  |
2 | let rings = circle(radii)
  |                    ^^^^^
error: ribs: no equation fits (-2, 75)
 --> ribs.kf:3:9
  |
3 | let a = ribs(-2, 75)
  |         ^^^^^^^^^^^^

If a parameter is outside its range, you get a warning, and the nearest allowed value is used:

warning: height = 600 is outside 40..500, using 500

10. The node graph is already in there

Lesson 1.1 said: every let is a node, every name a wire. kf graph makes that visible:

$ kf graph examples/star.kf
param points
param outer
param inner
param height
   fn radius   ◄─ outer, inner
   fn corner   ◄─ points, radius
  let outline  ◄─ points, corner
      export   ◄─ outline, height

This is the star's node graph, just as text. Because a name never gets a second value, this graph is always correct. The cache uses this (Lesson 4.2): if only height changes in the browser, only the result needs to be recomputed, not the outline.

11. How it is checked

A model that reaches the same result by two routes must give the same thing, bit for bit. The closed sweep rebuilt with the means of the language (examples/sweep_in_language.kf: frames along the curve, a loft over them) gives the same STL file as the built-in function tube; browser and command line write byte-identical files for all examples (Lesson 4.1), and every example is a closed solid. Where two routes do drift apart in the last bits, the numerics of Lesson 1.4 are almost always behind it: in the language cos(90) is exactly 0, a turn by 90° in radians would leave 6·10⁻¹⁷.

Try it yourself

cargo run --release -p kf -- help
cargo run --release -p kf -- graph examples/star.kf
cargo run --release -p kf -- render examples/vase.kf -D twist=180 -D sides=4 -o out/vase.stl
cargo run --release -p kf -- render examples/vase.kf --tol 0.5 -o out/vase.svg

Exercises:

  1. In examples/rings.kf, turn the three rings into ten: radii and heights with range, paired with zip. And then: what do you get with product instead of zip?
  2. Write fn total from section 7 with fold instead of recursion.
  3. Give the star three alternating radii (outer, middle, inner): one more equation for radius with a guard on k % 3.
  4. Write a model of your own, say a bowl: a quarter-circle profile (arc(r, 270, 90)), moved up, turned with revolve. What happens if the profile doesn't touch the axis?