knotflow Lessons PDF ↓ Deutsch Handbook Modeller ↗ Source

Lesson 2.3 · II The language

Rules you can rely on

What it's about: A language for models must above all do one thing: do what is written, or say why not. This lesson collects the rules knotflow keeps for that, and for each one explains which trap it prevents. The traps are general; most languages have stepped into some of them at some point. First come the rules you notice while writing: habits from other languages, numbers, names. Then the finer points of the grammar, the limits and how all of it is checked. At the end there are two deeper looks for anyone building a language of their own.

1. Habits from other languages

The first question for a DSL is: what happens when someone with experience in Python, JavaScript or OpenSCAD just starts typing? The principle of least surprise does not demand that everything looks the way it does elsewhere. It demands that anything unfamiliar stands out and does not silently mean something else. That gives three levels, from bad to harmless:

  1. Silently a different meaning. That is the real bug.
  2. An error without a hint. That is annoying, but harmless.
  3. An error that tells you how it is written here. That is good, and you learn something.

Two habits easily land on the first level:

These habits get a hint (the third level):

Habit Hint
a && b, a || b, !a and, or, not (for ! also: != for "not equal")
c ? a : b if c then a else b
2 ** 3 2 ^ 3
x -> x + 1 x => x + 1
x = 5, var x = 5, def f(x) let x = 5, fn f(x) = …
circle(r = 3) circle(r: 3)
[x * 2 for x in xs] [x * 2 | x <- xs]
; at the end of a line, # comment, 'text' nothing, //, "text"
True, null true; an empty value is []
"a" + "b", [1] + [2] a ++ b
max([1, 2]), xs.length() maximum(xs), len(xs)
xs[-1] xs[len(xs) - 1]

Deliberately different:

The functional core hardly gets in the way. let, fn f(x) = …, immutable values and comprehensions are familiar from OpenSCAD. =>, {r: 1}, ... and xs.map(f) are familiar from JavaScript, and/or/not from Python. What is unfamiliar is mainly where, equations with patterns and sections, and you can read those without knowing them. The stumbling blocks are almost only the places where your fingers type something else out of habit; those places come with hints.

Looking from the outside also reveals gaps: ... works in records ({...r}), in list patterns ([x, ...rest]) and therefore also in list expressions – if you can take [x, ...rest] apart, you also want to put it together that way. [a, ...xs, b] is shorthand for [a] ++ xs ++ [b]. For people with a JavaScript background there is a language tour of its own (docs/tour.md).

2. Numbers

NaN must not wander. 5 % 0, (-8) ^ (1/3) and asin(2) silently give NaN (not a number) in floating-point arithmetic. A NaN runs through move and revolve into the STL file, and at the end you would read "size NaN × 2 × 2, closed ✓". So in knotflow numbers are always finite: a computation that would give infinity or NaN is an error exactly where it arises. That is the same attitude as in Lesson 1.4: catch errors early instead of hunting symptoms later.

The output must not lie. With six decimal places, 0.1 + 0.2 shows 0.3, but 0.1 + 0.2 == 0.3 is false. And [1, 2, 3, 4, 5][0.3 / 0.1] would report "index 3 is outside 0..4", although the index is 2.9999999999999996. So knotflow shows the shortest number that reads back as exactly the same value, as Python and JavaScript do: 0.30000000000000004. That is honest, and no surprise to anyone with experience in numerics.

This honest output reveals further inaccuracies, and there is a remedy for each:

3. One name, one meaning

A model in which a name could have two meanings:

param r = 2
let area = pi * r * r      // pi: the number π?
param pi = 3               // or the parameter?
let report = area

If you evaluate line by line and enter names only when you reach them, pi is the built-in number in line 2 and a parameter from line 3 on, so the same name has two meanings in one model. That is confusing in itself. Together with the cache it becomes wrong: move the line param pi up, and report comes from the cache with the old value 12.57 instead of 12.

The cause is not the cache but the language: the rule from Lesson 2.2, "a name gets a value once", would only half hold. So in knotflow all names of a model are declared first. If you use a value that only comes further down, you get "pi is defined further down, in line 3", never the built-in number. All functions exist before the first line is computed. So their order never matters.

Related to this: duplicate names must not let the last definition win silently.

The call limit (section 10) belongs here too: a value from the cache costs no calls. A model that fails at the limit of ten million calls without the cache would go through the second time, and the browser would show something different from kf. So each cache entry remembers how many calls it cost, and they count again when it is reused. The principle from Lesson 4.2 holds for errors as well: with the cache, the result is the same as without it.

4. Greedy tokens

The lexer reads greedily (maximal munch): the longest matching token wins. That is right, but it has consequences:

In general: every character that occurs both on its own and as part of a longer token (< and <-, / and //, . and ..) is a potential stumbling block.

5. Precedence

The pipe. If |> binds the weakest, xs |> len == 3 means xs |> (len == 3) and reports "true/false is not a function". Worse: if comparing a function with == silently gives false, if xs |> len > 1 goes wrong without any error at all. The pipe is at the heart of the style, so this comes up all the time. So in knotflow |> binds more tightly than comparisons and logic, but more loosely than arithmetic, as in Elixir.

Sections that swallow operators. If (* 2 + 1) meant x => x * (2 + 1), everyone reading it would think of x * 2 + 1. And (2 ^ 1 ^) as (2 ^ 1) ^ x would contradict ^ grouping to the right. Haskell rejects both, and so does knotflow: a section is checked by the binding strength of its operand, not by its kind. (1 + 2 +) is unambiguous, (2 ^ 3 ^) is not (^ groups to the right), neither is (a < b ==) (comparisons do not chain), and (-2 ^) would be -(2 ^ x).

Chained comparisons. Grouping to the left, 1 < 2 < 3 would be (1 < 2) < 3, that is true < 3: a runtime error that explains nothing. And 1 == 1 == true would silently be true. In knotflow a chain of comparisons is an error with the hint a < b and b < c.

not between comparisons. not binds more loosely than comparisons (strength 4). In a == not b == c it would be unclear which comparison it takes. So this is an error; the remedy is a == (not b). After and and or, not is allowed.

Piping into a method. In x |> xs.take(1): does x go before or after xs? Instead of guessing, this is an error.

In general: precedence should follow reading, not the implementation. Where two readings are possible, an error is better than a silent choice.

6. Conveniences that must get along

Two rules can each be good on their own and still not get along.

Unpacking tuples. The justification goes: "A function with n parameters that receives an n-tuple unpacks it – unambiguous, because the call would otherwise always be an error." With default values the sentence no longer holds:

fn marker(p, r = 1) = …
marker((10, 20))           // p = 10, r = 20?

The call is perfectly fine without unpacking. So only the parameters without a default value count. The rule holds for built-in functions in the same way (zip(a, b).map(max)).

Method syntax. r.f(x) means f(r, x). But with records that look like objects, you read it as "call the field f of r". With r = {max: …}, r.max(3) would silently call the built-in max. So knotflow follows JavaScript's rule: if the record has a field f, r.f(x) calls the field; otherwise it is f(r, x). That is also how modules (records of functions, Lesson 2.4) call their function with knots.knot(…).

The guard flag. In a match guard, (x, y) => … must not be a lambda, so that the arrow ends the guard; in parentheses it may be (Lesson 2.2). The parser remembers that it is inside a guard, and has to save and restore that correctly across parentheses. If it forgot too early, parentheses of all things would break the guard.

In general: every convenience has a justification ("otherwise it would be an error"). When a new feature is added, you have to check every old justification again.

7. Equality

If geometry is compared by its address, that is, by whether it is the same object, isosurface(b) == isosurface(b) is true but circle(1) == circle(1) is false – depending on whether the second call came from the cache. The result of == would depend on an optimisation that is supposed to be invisible.

So in knotflow == compares geometry by its content. Functions cannot be compared at all: two functions are equal if they give the same result for every argument, and that cannot be checked. So sin == sin is an error, even hidden in lists or records: [sin] == [sin]. That way len == 3, too, reports right away what is wrong.

For points there is a single rule: points are three-dimensional, (x, y) is shorthand for (x, y, 0). ==, patterns, .z and [2] all follow it alike. Two rules – (1, 2) == (1, 2, 0) true, but the pattern (x, y) not matching (1, 2, 0) – would contradict each other.

8. Deliberate decisions

Some questions have no right answer. Here the language has chosen:

9. Error messages that help

A message that only says that something doesn't fit often leads astray. knotflow's messages say what was probably meant:

The grammar is written down completely in docs/grammar.md.

10. Limits

A language may refuse and report errors, but it must never crash, hang or fill the memory. So every quantity a model can make grow has a limit. Every limit ends with a message that names it:

What at most why
numbers finite NaN and ∞ would be errors far from their cause (section 2)
levels of brackets while reading 500 each level costs stack, and an overflow could not be reported
levels in the finished expression 1000 1 + 1 + … grows deeper than the parser descends
nested calls 1000, 250 in the browser stack (Lesson 4.1)
expressions evaluated inside each other 50,000, 1000 in the browser stack
tail calls in a row 5 million "endless loop?" instead of hanging
function calls per evaluation 10 million run time; the most expensive example needs 153,000
what a function makes at once (points, sides, lists) 1 million memory
elements of a list, characters of a text 10 million memory, above all in the browser
levels of nested values 500 printing, comparing and freeing walk down the levels
extent 10⁹ mm (1000 km) beyond that, floating point numbers are too coarse for a tolerance
degree of a curve or surface 15 higher degrees only wiggle more
cells of a field, pixels of a picture, blocks of an isosurface 4 million memory
parameter values per direction when cutting into triangles 1024 otherwise endless refinement far from the origin
unknowns and equations of solve 300 and 1000 the work grows with the cube
size of a file for read 64 MB memory

How the language makes sure of this is in section 13.

11. How it is checked

Four points of view complement each other: lexer and parser (ambiguities, precedence, line breaks), values (numbers, points, equality, built-in functions), functions and names (patterns, arguments, closures, where, cache) and robustness. There are three tools for this. Test programs each ask one question (What is -2 ^ 2? What is x<-1? What happens with {a: 1, a: 2}?) and compare with what a person would expect; every rule in this lesson is such a test. Fuzzing generates programs, at random from the grammar or by mangling real examples, and looks for anything that does not end with a message. Differential testing runs two routes against each other that must give the same result, such as evaluation with and without the cache. A test that checks a rule only finds the bugs someone thought of; a comparison finds the others too. And fixes are new code: they need the same checking as the old.

12. A deeper look: shared parts and memory

Values are immutable, so they may share parts: [a, a] does not contain two copies of a, but the same list twice. A fold that does this 40 times builds a value with 2⁴⁰ leaves out of just 40 lists, in milliseconds. But every check that walks a value element by element (nesting depth, finiteness, ==, the fingerprint for the cache, the output) would walk each shared part as often as it occurs. At depth 26 that takes 7 seconds; at depth 40 it would take hours. So each of these checks remembers which parts (recognised by their address) it has already seen:

This is a well-known pattern: a tree with shared parts is a directed acyclic graph (DAG), and walking it like a tree costs exponential time.

Memory that is never freed. Rust frees values as soon as nothing points to them any more (reference counting, Rc). With a cycle that does not work: a function remembers the scope it was defined in, and that scope contains the function. So every run would leave its scopes lying around. In the browser, where every move of a slider starts a run, memory would keep growing. So the evaluation remembers the scopes in which such a cycle can arise (model, prelude, where with functions, default values with functions) and empties them after the run. A test counts the live scopes before and after five runs: without emptying them, five would be left over per run; this way, none.

13. A deeper look: never crash

These inputs make an unprotected implementation crash or hang, or fill the memory; in knotflow each of them ends with a message:

Input What happens without protection
param a = 5 in 10..0 (while typing in 40..500 in the browser!) panic in clamp
revolve(profile, 0), circle(5 % 0) panic: assert! check in arc
mean(f, within: g) with g on a different grid index outside the field
100,000 parentheses, or 1 + 1 + … with 300,000 terms stack overflow, process killed
linspace(0, 1, 1e10), buckets(xs, 1e15, f) memory full
isosurface(ball(…), voxel: 1e-4) hangs
grid((0, 0), (1e300, 2), 1) numeric overflow while checking the size
bezier with 18 points panic: degree 17 too high
a list nested a million levels deep (built quickly with a tail-recursive loop) stack overflow when printing, comparing, even when freeing
a chain of a million closures (fold builds it) stack overflow when freeing
l ++ l forty times memory full
move(sphere(1), x: 1e300) the tessellation never ends

(A panic in Rust is the controlled abort of the program when an assumption is violated.) The remedies are always the same three:

Running time is part of correctness, too. A per-statement bookkeeping that grows quadratically needs 6.7 seconds instead of 0.5 for 10,000 lines that build on each other. And if xs[i] copies the whole list, a loop over the indices becomes quadratic: 29 seconds instead of 0.03.

Try it yourself

  1. Write let a = [1, 2, 3] |> len == 3 and let b = 1 < 2 < 3. What does the first give, what does the second report – and what would a language do in which |> binds the weakest and comparisons group to the left?
  2. What does (1, 2) == (1, 2, 0) give, and what does let (x, y) = (1, 2, 5) do? Why do both belong to the same rule?
  3. Try let a = 0.1 + 0.2 and let b = sin(30). Why is one inexact and the other not?
  4. Use fold to build a list that contains itself twice, 100 levels deep. How many numbers are in it, how many lists really exist – and why is a == a still done instantly?
  5. Type a few lines the way you would write them in your favourite language. Which message helps you along, which does not? Is a habit missing from the table in section 1?
  6. Something to think about: which other convenience of this language has a justification of the form "otherwise it would be an error"? (Hint: Lesson 2.2, sections and (-1).) Would it still hold if user-defined operators were added one day?