Lesson 4.4 · IV Tools
A language server
What it's about: In the browser, the modeller marks
errors and helps you write (Lesson 4.1). Every editor gets the same help
through kf lsp, a language server. The Language
Server Protocol (LSP) separates the editor from the language: the editor
sends texts and questions, the server answers with errors, help and
suggestions. One server thus serves all editors. The colours come
separately, from a Tree-sitter grammar. Because the language is
pure, the server can do more than usual: it evaluates the model and,
when you hover over a name, shows its value.
What you should know first: To set it up, only the
instructions in editors/README.md. For the rest: what an
interpreter does (Lesson 2.1), libraries (Lesson 2.4) and the cache
(Lesson 4.2). You should be able to read JSON.
1. What it can do and how to set it up
kf lsp can:
- report errors and warnings,
- help when hovering with the mouse (hover),
- completion (also after
knots.andimport), - go to definition,
- signature help in calls,
- an outline of the file.
A Zed extension is a small Rust program compiled to WebAssembly. The
one for knotflow looks for kf in the PATH and
starts kf lsp; on top of that come the language description
and the queries. Zed fetches the grammar via Git from this repository,
at a specific commit. The setup is described in
editors/README.md, together with Neovim and Helix.
Together with projects in the browser (Lesson 4.1) this makes a complete workspace: write in the editor, with errors, help and jumps into the libraries, and have the same folder open in the browser. The browser picks up every saved change within a second and shows the model.
2. Errors: really evaluating
Most language servers only check: syntax, types, names.
kf lsp evaluates, like kf render,
just without triangles. That way it also finds errors like a division by
zero in a library, or the assert from Tour 4. So that
typing never waits, a separate thread does the computing:
- with 64 MB of stack, because of the deep recursion (Lesson 2.1),
- with a cache per file (Lesson 4.2): after a small change, only what depends on it is recomputed,
- and each file only once per round, no matter how often it was changed while the thread was computing.
It computes when the text in the editor changes, and also when
something the model reads changes on disk: the server asks the editor to
report changes to .kf files and to data files (JSON, CSV,
SVG, PNG, fonts …). If another program saves a library or a table anew,
the errors in the model are right again straight away.
An error in a library appears in the model at the call that led there. The place in the library is attached as related information; a click opens it. The server also checks an open library on its own, as if it were imported.
3. While you type, the text is broken
The moment you need help is the moment the text is not right:
let a = knots. is not a valid program. A parser that gives
up then is of no use to the editor. So:
- Imports (
let knots = import knots) are read by the server from the tokens, not from the syntax tree. There are tokens even for half-written lines. - Your own definitions: If the text does not parse, the server tries again without the line the cursor is on. That line is replaced by spaces so that all positions stay right. Usually it is exactly that line that is half-written.
- Values come from the last evaluation that worked.
Without this second attempt, after shapes. the general
list would appear instead of ring: the half-written line
would spoil the whole text.
4. Hover with values
Because the server evaluates, it knows the values. Hover over
twice in let twice = size * 2 and it shows the
line, the comment above it and Value: 80.
For a param it shows the value and the slider range. This
only exists in this form because the language is pure: a value depends
only on the text, not on when or how often you compute.
The comments above a definition are read by lang::docs.
The same function supplies kf help, the browser and the
server. So there is one source for all three.
5. Colours: a grammar of its own
In Zed, Neovim and Helix, colours do not come from the language server but from Tree-sitter: a parser the editor runs itself, immediately and on every keystroke only for the piece that has changed (incremental). It tolerates broken spots and parses the rest anyway.
The grammar in editors/tree-sitter-knotflow/grammar.js
follows docs/grammar.md, with the same binding strengths.
Like the parser of the language, it reads patterns as expressions:
(a, b) => … is first a tuple, then parameters. That
avoids almost all ambiguities. In fact, it needs not a single declared
conflict (conflicts). It parses all .kf files
of the project without errors, and spot checks show the right grouping:
-2 ^ 2 is -(2 ^ 2), not a and b
is (not a) and b.
queries/highlights.scm says which node gets which
colour: parameters like constants, function names at definition and
call, field names like properties, library names after
import like types.
6. Positions are counted differently
Our language works with byte positions in the text,
the protocol with line and column in UTF-16 units, the
way JavaScript counts. ä is two bytes but one unit; an
emoji is four bytes and two units. Mix them up and errors in lines with
such characters are marked a few characters off.
crates/lsp/src/text.rs converts back and forth, with a test
for exactly these characters.
7. The protocol
Editor and server speak JSON over standard input and output. Every message starts with its length:
Content-Length: 117
{"jsonrpc":"2.0","id":7,"method":"textDocument/hover",
"params":{"textDocument":{"uri":"file:///…/vase.kf"},"position":{"line":3,"character":5}}}
There are three kinds of messages:
- Requests with an
idwant an answer (hover, completion, definition). - Responses carry the same
id. - Notifications without an
idwant no answer: "file opened", "text changed", and back from the server "here are the errors in this file".
The Rust libraries lsp-server and lsp-types
(from rust-analyzer) take care of reading, writing and the types of the
messages.
At startup the server says what it can do (capabilities): the list from section 1.
8. Stopping cleanly, and servers that are out of date
After exit the server has to end, or the editor waits.
That is harder than it sounds: lsp-server writes messages
in a thread of its own, and that thread only ends when
all senders of its channel are gone. The analysis
thread has one, and so does the main program, through its connection. If
the main program does not let go of its connection before waiting for
the threads, it waits for ever. The rule holds for every channel between
threads: whoever waits for a receiver to end must first let go of every
sender, including their own.
The other way round, a server often runs longer than you think. When
a new kf is installed after a change to the language, a
server the editor started earlier keeps computing with the old one. So
kf lsp notes the time stamp of its program file when it
starts, and shows a warning once as soon as a newer kf lies
there (lsp::fresh; kf mcp from Lesson 4.5 does
the same).
Try it yourself
cargo install --path crates/cli # kf into ~/.cargo/bin
- Set up Zed (
editors/README.md) and openexamples/knots.kf. Hover oversize, overknots.ropeand over aletname of your own. What does the hover show in each case? - In
lib/knots.kf(a copy in your own folder), put an error into a function the model uses. Where does it appear in the model, where in the library? - Open the same folder in the browser ("Project → Open folder …") and change a parameter in the editor. How quickly does the picture follow?
- Something to think about: what other help could a server give that knows values? (Hint: inlay hints show values right in the text; a slider in the editor would be a code action.)