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:
- Silently a different meaning. That is the real bug.
- An error without a hint. That is annoying, but harmless.
- 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:
range(0, 5). In Python, Rust and JavaScript a range stops before the end, and the namerangeraises exactly that expectation. Sorangebehaves as in Python:range(5)is[0, 1, 2, 3, 4],range(2, 5)is[2, 3, 4]. If you want the end included, you write[2 .. 5]. Rust solves the same problem with two notations,a..bwithout anda..=bwith the end. In knotflow,..always includes the end, the way you read it in mathematics and the way a sliderparam x = 5 in 0..10needs it. So if you write[0 ..= 5]out of Rust habit, you get the hint that..already includes the end.10 // 3. In Python,//is integer division; in knotflow it is a comment, as in OpenSCAD, C and JavaScript. Changing the comment would surprise everyone else. So10//3without spaces is an error with a hint to usefloor(a / b). With spaces it stays a comment, becausex = 5 // radiusis far more common. That remnant of the trap stays.
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:
- No broadcasting.
[1, 2, 3] * 2is an error. For people coming from node editors or NumPy this is the biggest adjustment, but the message points straight tomapand comprehensions. 0 < x < 10is an error, where Python computes it correctly and C silently produces nonsense.- Angles in degrees, as in OpenSCAD and every CAD program.
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:
- Right angles. A rotation by 90° via π/2 gives
6·10⁻¹⁷ instead of 0, because π/2 cannot even be written down exactly as
a floating-point number. So in knotflow sine and cosine compute
in degrees and are exact at all multiples of 30° and
45°: sin(180°) = 0, cos(60°) = 0.5, tan(45°) = 1. Rotations and arcs
land exactly on the axes. Likewise
asin,acos,atanandatan2are exact at multiples of 15°:asin(0.5)is 30, not 30.000000000000004. normalize((3, 4))would give 0.6000000000000001 if you multiplied by 1/5 instead of dividing by 5: two roundings instead of one. knotflow divides.[0 .. 2.999999999999]must not end with 3. So the tolerance for rounding errors at the end of a range is only a few machine epsilons, not 10⁻⁹.[0, 0.1 .. 0.3]ends exactly on 0.3.length((3e200, 4e200))must not overflow, although the squares of the numbers would.- Messages put negative numbers in parentheses: "(-8) ^ 0.333… is not a finite number".
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.
fn f(a, a),(x, x) => …,where y = 1, y = 2,{a: 1, a: 2}andf(b: 1, b: 2)are errors.- A default value may only use the parameters to its left;
fn f(a = b, b = 1)does not fetch abfrom outside the function. This is checked on the syntax tree, with the same function that also builds the dependency graph. A check on the tokens would take every wordbin the default value for the parameterb, even inb => b,{b: 1}org(b: 1). As a general rule: a rule about meaning belongs on the tree, not on the text.
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:
x<-1is the generator arrow, notx < -1. In[x | x <- xs, x<-[7, 8]], an intended filter would silently become a second generator. Haskell has exactly the same trap. knotflow gives a hint wherever<-turns up unexpectedly, a number after the arrow is an error right away, and a second generator may not rebind a name of an earlier one.7//2would be 7: the rest of the line is a comment. For people coming from Python that is a trap; section 1 shows how knotflow defuses it.3.abs()must not read3.as a number. So a dot only belongs to the number if a digit follows.
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:
- Comprehensions don't skip anything silently. In
Haskell,
[x | (x, y) <- points]leaves out elements that don't match the pattern. In knotflow that would mean all 3D points vanish without a sound. So a literal in the pattern filters ([x | (x, 0) <- ps]– it says so explicitly), and a wrong shape is an error. That is a deliberate departure from Haskell, following guideline 3 ("explicit rather than magic"). - Guards see the
whereof their equation, as in Haskell. Because knotflow evaluates strictly and not lazily, only what the guard needs is computed before the guard. Withfn f(x) | y > 0 = y where y = x - 1, z = 1 / x,zis never computed forf(0). But what the guard needs is computed completely before it runs: infn f(x) | x != 0 and y > 0 = … where y = 1 / x, thex != 0does not protect against the division, becauseyis already fixed beforehand. Then the condition belongs in an equation of its own before it:fn f(0) = …. - Local functions in
wheremay call themselves and each other. Lambdas come first, because they compute nothing until they are called. - This stays as it is:
- Line breaks are whitespace. Because every statement starts with a keyword, a line break can never silently split a statement in two.
if … elseand lambdas extend as far to the right as possible, as in Haskell.(1,)is simply 1; there are no one-element tuples.- Comments can be nested:
/* … /* … */ … */.
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:
- "missing ',' between the bindings of 'where'"
- "is an operator or a ',' missing before it?"
- "a point is not a function (a ',' missing before the '('?)"
- Invisible characters show up as U+00A0, umlauts in names are explained explicitly.
- Internal names such as
#p1never appear.
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:
==remembers pairs it has already found equal.- For a part it has already seen, the fingerprint writes "part no. k again". That way, equal content with equal sharing gets the same fingerprint.
- The output has a budget of 2000 values.
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:
- Check before computing, not afterwards: estimate the number of blocks of an isosurface before allocating them.
- Name the limits (section 10).
- Compute without recursion where the input can be arbitrarily deep. The depth of an expression is measured with a loop, so that even the measuring cannot overflow. And a scope hands its contents to a list when it is freed, instead of freeing closure after closure in a nested way.
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
- Write
let a = [1, 2, 3] |> len == 3andlet 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? - What does
(1, 2) == (1, 2, 0)give, and what doeslet (x, y) = (1, 2, 5)do? Why do both belong to the same rule? - Try
let a = 0.1 + 0.2andlet b = sin(30). Why is one inexact and the other not? - Use
foldto build a list that contains itself twice, 100 levels deep. How many numbers are in it, how many lists really exist – and why isa == astill done instantly? - 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?
- 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?