03 Editor integration

The lsp plugin serves the Language Server Protocol to editors and agents while a database is open. Editor integration lists its settings. Start a server that keeps the database open, and connect the editor to the port:

stardust nrepl --config arrakis.dust
{plugins {<stdlib io> database {path "arrakis.db"} lsp true}}

Without port, the plugin listens on port 1980. If a different process uses 1980, the plugin tries 1981, 1982 and so on up to 65535, and uses the first port that is free. A port setting selects one port: if that port is in use, the database does not open. The startup warning on standard error gives the port, for example stardust: warning: plugin lsp listens on 127.0.0.1:1981 .... The stardust/status request also reports it. To give the port to an editor script, set port-file: the plugin writes the port to that file, as the nREPL server writes .nrepl-port. An editor connects to 1980 by default. Set the port of the editor when the warning gives a different port.

The socket has no authentication. A peer that connects can evaluate code and write the database. Keep the default loopback address if the network is not trusted.

3.1. Buffers and namespaces

A buffer holds a namespace when its URI names one:

  • file:///<root>/<path>.dust is the namespace <path>, for a file below the definitions root. The root is the workspace folder. The definitionsRoot initialization option can name a different folder, relative to the workspace folder. dune/houses.dust is the namespace dune/houses.
  • stardust://namespaces/<path> is the saved namespace <path>. The editor reads its text with workspace/textDocumentContent. Add ?asOf=T for the revision at transaction T. When you save such a buffer, the server publishes the namespace. When you rename it, the server moves the namespace. A filesystem provider sends stardust/renameNamespace with oldUri and newUri and waits for its response before it reports success. Set initializationOptions.namespaceFileOperations to true when the provider sends this request. The server then ignores workspace/didRenameFiles from that client to prevent a second move. Other clients can use workspace/didRenameFiles to move a namespace.
  • stardust://entities/<id> shows the fields of entity <id> as DUST. The server reads them with entities/read. Add ?asOf=T for the entity at transaction T. You cannot change this document.

The server decodes each .dust buffer at each change. A syntax error is a diagnostic immediately. Then namespaces/check examines a namespace buffer against the other saved namespaces of the database. The editor shows each form that does not compile and each unavailable name. This includes a removed export that a saved namespace still imports. The server publishes such an error in the namespace that imports the changed one: in its open buffer, or else in its stardust://namespaces/<path> document. The error is at the form that uses the changed name, and its relatedInformation points at the change. After each namespace save, from this editor or from a different client, the server examines each open namespace buffer again and sends its new diagnostics. Each diagnostic has the error code in code, and the namespace, form and cell in data. While a buffer has a syntax error, features that need a parse use the last text that decoded. Positions count UTF-8 bytes when the client gives utf-8 in positionEncodings. Otherwise, they count UTF-16 code units.

3.2. Saving and conflicts

The stardust.namespaces.save command, with {uri}, publishes the buffer with namespaces/save. It sends the base revision of the buffer as expected-revision. This is the revision when the buffer opened, or the revision of its last save. With paths, a list of URIs, the command publishes many buffers in one atomic save. If a different client saved the namespace first, the command returns {error category "conflict" path expected actual} and publishes nothing. stardust.namespaces.overwrite saves without the revision check. The command registry marks it as a command that the user must confirm. With saveOnDidSave true in the initialization options, a save in the editor also publishes the file. Sessions use a saved namespace at their next evaluation. Named subscriptions use it at their next event.

3.3. Live interaction

Each connection has a database session. The session opens at the first session command and closes with the connection. A session argument names a different session. The commands take their input as the first argument object of workspace/executeCommand:

Command Input Requests Result
stardust.forms.evaluate uri and range, position (the top-level form) or neither (the whole buffer) namespaces/load of the buffer, then one eval per form with namespace {values [{text error range}]}
stardust.namespaces.load uri, optional alias namespaces/load with forms {path alias exports}
stardust.sessions.reset optional session sessions/reset {}
stardust.queries.subscribe uri and position of a defquery or query map, or namespace, name and args queries/subscribe {subscription}
stardust.queries.unsubscribe subscription cancel {}
stardust.expressions.evaluate programText, optional bindings eval without a session {values [{text error}]}
stardust.queries.run queryText, a query map, optional bindings query {rows pages}, after a stardust/queryPage notification for each page
stardust.transactions.apply mutationText, optional bindings and dryRun transact {tx result}; with dryRun true, {tx null dryRun true result}
stardust.schemas.validate valueText and schemaText or name schemas/valid? {valid diagnostics}
stardust.namespaces.save, stardust.namespaces.overwrite uri or paths namespaces/save {tx namespaces}
stardust.namespaces.reload uri namespaces/read Replaces the buffer with the saved source

stardust.forms.evaluate loads a namespace buffer into the session without the selected forms. Then it evaluates each selected form in the scope of the namespace, where private definitions are visible. Each result is an inlay hint at the end of its form and a stardust/evaluationResult notification. The hint stays until the text of the form changes or the session resets. A failure or a returned #err value is a diagnostic with the source stardust eval. A subscription sends stardust/queryEvent {subscription uri event tx rows result} for each event. At its end, it sends {subscription done error}. Its form shows live · N rows · tx T. The subscription ends with stardust.queries.unsubscribe, when its buffer closes, or with the connection. Results are DUST text.

textDocument/codeLens puts Evaluate above each top-level definition and Subscribe above each defquery. When the database reports reactors (reactors/status), a defreactor form also shows its runs, changes and failures. textDocument/codeAction gives the commands as source actions. It renames an unavailable imported name to the nearest export of its namespace. After a save conflict, it gives Reload from database and Save anyway.

With dryRun true, stardust.transactions.apply sends transact with dry-run true. The dry run writes nothing, and result shows the changes that the transaction would make (Database requests). The VS Code extension shows this preview first, and applies the transaction only after the user confirms it.

$/cancelRequest cancels the database requests of a command. A command that committed still returns its result. When every database request slot is busy, a command waits for a free slot instead of failing. Waiting commands send each ready database operation to the end of the queue. Those operations start in the order that they were queued. A command can wait for as long as every slot stays busy, for example while live queries hold all the slots. $/cancelRequest removes a waiting command, and the reply says that the request was cancelled. When the connection closes, its waiting commands are removed and do not run. stardust/capabilities returns the command registry. For each command, the registry gives its request, whether the command has a preview (stardust.transactions.apply with dryRun), and whether the client must ask the user first, as for stardust.transactions.apply and stardust.namespaces.overwrite. Session commands and saves use worker zero. A long evaluation delays them. The commands without a session run on any worker.

3.4. Editor features

The server also replies to these requests. It uses the last text of the buffer that decoded:

  • textDocument/semanticTokens/full and range color each DUST value, comment and builtin call. There is no other highlighting.
  • textDocument/formatting and rangeFormatting return one edit to the stardust fmt form (Formatting). A range formats the top-level forms that it touches. A CRLF buffer stays CRLF.
  • textDocument/documentSymbol, foldingRange and selectionRange show the top-level definitions, the containers over several lines and comment runs, and the values that hold a position.
  • textDocument/hover, signatureHelp, completion and completionItem/resolve use the function documentation of DUST in the binary, the definitions of the buffer and programs/names.
  • textDocument/definition, references and documentHighlight find a top-level name of the buffer. For alias/name, they find the declaration of the export in an open buffer of the namespace or in stardust://namespaces/<path>. The references of an export include the open buffers that import it.
  • A local name goes to its nearest binding. A let, for or loop binding vector, or a fn, defn or defmacro parameter vector, binds a local name. Completion gives the local names around the position, the innermost first.
  • The definition of a #link value is its stardust://entities/<id> document.
  • textDocument/prepareCallHierarchy, callHierarchy/incomingCalls and outgoingCalls show the calls between the defn forms of the open buffers. An incoming call from a different namespace calls alias/name.
  • stardust/entityBacklinks {entity asOf} and stardust/entityHistory {entity field limit asOf} return the results of entities/backlinks and entities/history. entity is an entity ID or a stardust://entities/ URI. Each value and link is DUST text. Each entity has its uri.
  • workspace/symbol lists the saved namespaces and their exports.

3.5. Editors

  • VS Code: task vscode:install builds and installs the stardust extension (tools/vscode/stardust). The extension registers dust and ron. It connects to stardust.host and stardust.port (default 1980). stardust.saveOnDidSave and stardust.definitionsRoot become initialization options. Ctrl+Enter evaluates the form or the selection. Ctrl+Alt+S saves the namespace. You can open, save and rename stardust://namespaces/<path> documents as files. Results show after their forms. Query events show in the Stardust output channel.
  • Neovim: add tools/neovim to runtimepath and call require('stardust').setup({ port = 1980 }). It connects with vim.lsp.rpc.connect and turns on inlay hints and code lenses. It adds these commands: :StardustEval, :StardustLoad, :StardustSave[!], :StardustSubscribe, :StardustUnsubscribe and :StardustReset.
  • Emacs: load tools/emacs/stardust.el after dust-mode. It adds an Eglot contact for dust-mode and commands under C-c C-d.
  • Helix and other clients that start a server process connect through a byte bridge:
[[language]]
name = "dust"
scope = "source.dust"
file-types = ["dust"]
comment-token = ";"
language-servers = ["stardust"]

[language-server.stardust]
command = "nc"
args = ["127.0.0.1", "1980"]

Clients without an extension can evaluate, save and subscribe, because each feature uses standard requests, code actions and inlay hints.