Checks run on a thread of their own

A check held up every request, because the compiler could run one
compilation at a time. It can now run each in a context of its own.

- A check runs on a checking thread, in Compilation.inNew. The thread
  reports a check to the thread that serves requests, which writes to the
  client.
- The outline, definitions, references, completion, signature help and
  formatting are answered while a check runs.
- A hover, a code action and bjolang/expandMacro are answered when the
  check of their file ends, with the results of the text as it stands.
  Other requests are served meanwhile.
- A file that changes again before its check starts is checked once.
- The tables that a check writes are concurrent dictionaries.
- Standard output is the protocol's; the console's output goes to standard
  error.
- smoke: with a check of 1.6 s running, an outline is answered in 0.1 s.

Needs the compiler at its commit "Diagnostics.captured collects the output
of its own context".

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Linus Björnstam 2026-11-25 09:32:15 +01:00
parent c5acafd5dd
commit 5e4ac7d9aa
6 changed files with 273 additions and 49 deletions

View file

@ -133,10 +133,10 @@ let rec private pretty (name: string -> string) (indent: int) (atHead: bool) (s:
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
/// Each file's expansions, from its last check, in the order they were made. /// Each file's expansions, from its last check, in the order they were made.
let private byFile = Collections.Generic.Dictionary<string, Record list>() let private byFile = Collections.Concurrent.ConcurrentDictionary<string, Record list>()
/// Each name hygiene made, and the spelling the template wrote. /// Each name hygiene made, and the spelling the template wrote.
let private renamed = Collections.Generic.Dictionary<string, string>() let private renamed = Collections.Concurrent.ConcurrentDictionary<string, string>()
/// Runs `check` with the compiler reporting its expansions, and keeps those /// Runs `check` with the compiler reporting its expansions, and keeps those
/// made in `path` as the file's. /// made in `path` as the file's.

View file

@ -18,7 +18,7 @@ type Facts =
let private none = { Missing = []; Holes = []; Signatures = [] } let private none = { Missing = []; Holes = []; Signatures = [] }
let private byFile = System.Collections.Generic.Dictionary<string, Facts>() let private byFile = System.Collections.Concurrent.ConcurrentDictionary<string, Facts>()
/// Runs `check` of `path` with the compiler handing over what it refused, and /// Runs `check` of `path` with the compiler handing over what it refused, and
/// keeps what is in `path` as the file's. /// keeps what is in `path` as the file's.

View file

@ -52,12 +52,22 @@ let private texts = Collections.Generic.Dictionary<string, string>()
/// starts. /// starts.
let mutable private refreshesHints = false let mutable private refreshesHints = false
let private publish (uri: string) = /// A check to run: the file, the text of every open file when the check was
/// asked for, and what there is to say of the file's project.
type private Job =
{ Uri: string
Buffers: Map<string, string>
Note: Check.Found list }
/// The check of `uri` as its text stands now.
///
/// Made on the thread that serves requests, before the check: the first file
/// asked about decides which project's packages are installed, and they have
/// to be before anything resolves.
let private jobFor (uri: string) : Job =
let buffers = let buffers =
texts |> Seq.map (fun kv -> IO.Path.GetFullPath(uriToPath kv.Key), kv.Value) |> Map.ofSeq texts |> Seq.map (fun kv -> IO.Path.GetFullPath(uriToPath kv.Key), kv.Value) |> Map.ofSeq
// Before the check: the first file asked about decides which project's
// packages are installed, and they have to be before anything resolves.
let note: Check.Found list = let note: Check.Found list =
match Project.prepare (uriToPath uri) with match Project.prepare (uriToPath uri) with
| Some message -> | Some message ->
@ -70,19 +80,24 @@ let private publish (uri: string) =
Elsewhere = None } ] Elsewhere = None } ]
| None -> [] | None -> []
{ Uri = uri
Buffers = buffers
Note = note }
/// Runs a job, and gives the parameters of the `publishDiagnostics` that
/// tells the client what it found.
///
/// In a context of its own (`Compilation.inNew`), so that it shares no state
/// of a compilation with a request that reads a file at the same time.
let private run (job: Job) : JsonNode =
let found = let found =
try try
Check.file buffers (uriToPath uri) Bjolang.Compilation.inNew (fun () -> Check.file job.Buffers (uriToPath job.Uri))
with ex -> with ex ->
Rpc.log $"check of %s{uri} failed: %O{ex}" Rpc.log $"check of %s{job.Uri} failed: %O{ex}"
[] []
Rpc.notify "textDocument/publishDiagnostics" (Check.publishParams uri (note @ found)) Check.publishParams job.Uri (job.Note @ found)
// The hints are of this check's types. A client asks for them as the text
// changes, which is before the check, so it is told to ask again.
if refreshesHints then
Rpc.request "workspace/inlayHint/refresh" null
/// When each changed file is next to be checked. A check waits for typing to /// When each changed file is next to be checked. A check waits for typing to
/// pause, as one per keystroke would queue up behind each other. /// pause, as one per keystroke would queue up behind each other.
@ -630,6 +645,10 @@ let private capabilities () : JsonNode =
[<EntryPoint>] [<EntryPoint>]
let main _ = let main _ =
// Standard output is the protocol's, and `Rpc` writes it through the raw
// stream. All that anything else writes to the console goes to standard
// error, which is the log.
Console.SetOut Console.Error
setBjolangHome () setBjolangHome ()
useInstalledCompiler () useInstalledCompiler ()
let mutable shutdownAsked = false let mutable shutdownAsked = false
@ -660,6 +679,82 @@ let main _ =
reader.Start() reader.Start()
// Checks run on a thread of their own, one at a time, so that a request
// which does not need a check is answered while one runs. The thread
// tells this one when a check is done with a message of its own in the
// inbox, `bjolang/checked`, and this thread tells the client: all that
// is written to the client, and all of the server's tables but the
// results of a check, stay with this thread.
//
// - `latest` has the newest job of each file that is not started. A file
// that is asked for again before its check starts is checked once, as
// the newest text.
// - `inFlight` counts, for each file, the jobs given to the thread and
// not yet reported.
// - `waiting` has what to do when a file has no check due or in flight:
// the answers to the requests that need the results of its check.
let jobs = new Collections.Concurrent.BlockingCollection<string>()
let latest = Collections.Concurrent.ConcurrentDictionary<string, Job>()
let inFlight = Collections.Generic.Dictionary<string, int>()
let waiting = Collections.Generic.Dictionary<string, ResizeArray<unit -> unit>>()
let checker =
Threading.Thread(
(fun () ->
for uri in jobs.GetConsumingEnumerable() do
let published =
match latest.TryRemove uri with
| true, job -> run job
// A later request took this one's job.
| _ -> null
let done' =
JsonObject(
dict
[ "method", JsonValue.Create "bjolang/checked" :> JsonNode
"params",
JsonObject(
dict
[ "textDocument", JsonObject(dict [ "uri", JsonValue.Create uri :> JsonNode ]) :> JsonNode
"published", published ]
) ]
)
inbox.Add(Some(done' :> JsonNode))),
IsBackground = true
)
checker.Start()
/// Gives the check of `uri`, as its text stands, to the checking thread.
let startCheck (uri: string) =
latest[uri] <- jobFor uri
inFlight[uri] <-
match inFlight.TryGetValue uri with
| true, n -> n + 1
| _ -> 1
jobs.Add uri
/// Whether `uri` has a check that is due or not yet reported.
let busy (uri: string) =
dueChecks.ContainsKey uri || inFlight.ContainsKey uri
/// Runs `answer` when the results of `uri`'s check are of its text as it
/// stands: now, if no check is due or in flight; else when the last of
/// them is reported. A check that is due is started at once.
let whenChecked (uri: string) (answer: unit -> unit) =
if busy uri then
if dueChecks.Remove uri then
startCheck uri
match waiting.TryGetValue uri with
| true, answers -> answers.Add answer
| _ -> waiting[uri] <- ResizeArray [ answer ]
else
answer ()
/// The next message, running every check that falls due while waiting /// The next message, running every check that falls due while waiting
/// for it. /// for it.
let rec next () : JsonNode option = let rec next () : JsonNode option =
@ -679,7 +774,7 @@ let main _ =
for uri in due do for uri in due do
dueChecks.Remove uri |> ignore dueChecks.Remove uri |> ignore
publish uri startCheck uri
next () next ()
@ -712,7 +807,7 @@ let main _ =
uri () uri ()
|> Option.iter (fun u -> |> Option.iter (fun u ->
str message [ "params"; "textDocument"; "text" ] |> Option.iter (fun t -> texts[u] <- t) str message [ "params"; "textDocument"; "text" ] |> Option.iter (fun t -> texts[u] <- t)
publish u) startCheck u)
// Full sync: the one change is the whole text. // Full sync: the one change is the whole text.
| "textDocument/didChange" -> | "textDocument/didChange" ->
match uri (), message["params"]["contentChanges"] with match uri (), message["params"]["contentChanges"] with
@ -725,7 +820,7 @@ let main _ =
uri () uri ()
|> Option.iter (fun u -> |> Option.iter (fun u ->
dueChecks.Remove u |> ignore dueChecks.Remove u |> ignore
publish u) startCheck u)
// A closed file's diagnostics are the client's to forget, // A closed file's diagnostics are the client's to forget,
// and an empty list is how it is told to. // and an empty list is how it is told to.
| "textDocument/didClose" -> | "textDocument/didClose" ->
@ -733,24 +828,29 @@ let main _ =
|> Option.iter (fun u -> |> Option.iter (fun u ->
texts.Remove u |> ignore texts.Remove u |> ignore
dueChecks.Remove u |> ignore dueChecks.Remove u |> ignore
latest.TryRemove u |> ignore
lastSymbols.Remove u |> ignore lastSymbols.Remove u |> ignore
Rpc.notify "textDocument/publishDiagnostics" (Check.publishParams u [])) Rpc.notify "textDocument/publishDiagnostics" (Check.publishParams u []))
| "textDocument/documentSymbol" -> | "textDocument/documentSymbol" ->
Rpc.respond id (uri () |> Option.map symbolsOf |> Option.defaultValue (JsonArray())) Rpc.respond id (uri () |> Option.map symbolsOf |> Option.defaultValue (JsonArray()))
| "textDocument/definition" | "textDocument/definition" ->
let position = message["params"]["position"]
let line = position["line"].GetValue<int>()
let character = position["character"].GetValue<int>()
Rpc.respond id (uri () |> Option.map (fun u -> definitionAt u line character) |> Option.defaultValue null)
// A hover's types are from the last check, which has to
// be of the text as it stands for them to be at the right
// places. So the answer waits for a check that is due or
// in flight, and other requests are served meanwhile.
| "textDocument/hover" -> | "textDocument/hover" ->
let position = message["params"]["position"] let position = message["params"]["position"]
let line = position["line"].GetValue<int>() let line = position["line"].GetValue<int>()
let character = position["character"].GetValue<int>() let character = position["character"].GetValue<int>()
let answer = if methodName = "textDocument/hover" then hoverAt else definitionAt
// A hover's types are from the last check, which has match uri () with
// to be of the text as it stands for them to be at | Some u -> whenChecked u (fun () -> Rpc.respond id (hoverAt u line character))
// the right places. | None -> Rpc.respond id null
if methodName = "textDocument/hover" then
uri () |> Option.iter (fun u -> if dueChecks.Remove u then publish u)
Rpc.respond id (uri () |> Option.map (fun u -> answer u line character) |> Option.defaultValue null)
| "textDocument/completion" -> | "textDocument/completion" ->
let position = message["params"]["position"] let position = message["params"]["position"]
let line = position["line"].GetValue<int>() let line = position["line"].GetValue<int>()
@ -803,14 +903,12 @@ let main _ =
{ Line = n["line"].GetValue<int>() + 1 { Line = n["line"].GetValue<int>() + 1
Column = n["character"].GetValue<int>() } Column = n["character"].GetValue<int>() }
let answer = let first = position r["start"]
uri () let last = position r["end"]
|> Option.map (fun u ->
if dueChecks.Remove u then publish u
actionsAt u (position r["start"]) (position r["end"]))
|> Option.defaultValue (JsonArray())
Rpc.respond id answer match uri () with
| Some u -> whenChecked u (fun () -> Rpc.respond id (actionsAt u first last))
| None -> Rpc.respond id (JsonArray())
// A refusal is an error answer: the client shows its // A refusal is an error answer: the client shows its
// message, which says why. // message, which says why.
| "textDocument/prepareRename" | "textDocument/prepareRename"
@ -852,23 +950,57 @@ let main _ =
| null -> otherwise | null -> otherwise
| v -> v.GetValue<bool>() | v -> v.GetValue<bool>()
let answer = let line = position["line"].GetValue<int>() + 1
uri () let character = position["character"].GetValue<int>()
|> Option.bind (fun u -> let full = flag "full" true
if dueChecks.Remove u then publish u let hygienic = flag "hygienic" false
Expansion.at let answer (u: string) () =
(uriToPath u) Expansion.at (uriToPath u) line character full hygienic
(position["line"].GetValue<int>() + 1)
(position["character"].GetValue<int>())
(flag "full" true)
(flag "hygienic" false))
|> Option.map (fun (macro, text) -> |> Option.map (fun (macro, text) ->
JsonObject(dict [ "macro", JsonValue.Create macro :> JsonNode; "text", JsonValue.Create text ]) JsonObject(dict [ "macro", JsonValue.Create macro :> JsonNode; "text", JsonValue.Create text ])
:> JsonNode) :> JsonNode)
|> Option.defaultValue null |> Option.defaultValue null
|> Rpc.respond id
Rpc.respond id answer match uri () with
| Some u -> whenChecked u (answer u)
| None -> Rpc.respond id null
// The checking thread reports a check of a file, or
// that a later request took the check's job.
| "bjolang/checked" ->
uri ()
|> Option.iter (fun u ->
// A file that was closed meanwhile has no
// diagnostics to show.
match message["params"]["published"] with
| null -> ()
| published when texts.ContainsKey u ->
Rpc.notify "textDocument/publishDiagnostics" (published.DeepClone())
// The hints are of this check's types. A
// client asks for them as the text changes,
// which is before the check, so it is told to
// ask again.
if refreshesHints then
Rpc.request "workspace/inlayHint/refresh" null
| _ -> ()
match inFlight.TryGetValue u with
| true, n when n > 1 -> inFlight[u] <- n - 1
| _ -> inFlight.Remove u |> ignore
if not (busy u) then
match waiting.TryGetValue u with
| true, answers ->
waiting.Remove u |> ignore
for answer in answers do
try
answer ()
with ex ->
Rpc.log $"an answer that waited for the check of %s{u} failed: %O{ex}"
| _ -> ())
// The client's answer to a request of the server's. // The client's answer to a request of the server's.
| "" -> () | "" -> ()
| _ when not (isNull id) -> Rpc.respondError id -32601 $"%s{methodName} is not supported" | _ when not (isNull id) -> Rpc.respondError id -32601 $"%s{methodName} is not supported"

View file

@ -199,6 +199,33 @@ step: the clauses' bodies are holes, and each says what it has to be. The
actions are of the file's last check, which a check that is due replaces actions are of the file's last check, which a check that is due replaces
first, as for a hover, and only of text that is still what it checked. first, as for a hover, and only of text that is still what it checked.
## Checks in the background
A check runs on a thread of its own, in a context of the compiler's own
(`Compilation.inNew`), so that the thread which serves requests is free
while it runs:
- The outline, go to definition, references, completion, signature help and
formatting read only as far as the reader, and are answered at once, also
while a check runs. With a check of 1.6 s running, the smoke test gets an
outline in 0.1 s.
- A hover, a code action and `bjolang/expandMacro` need the results of the
file's check. Asked while a check of the file is due or running, each is
answered when the check ends, with the results of the text as it stands;
a check that waits for typing to pause starts at once. Other requests are
served meanwhile.
- Inlay hints are answered from the last check, as before, and the client
is asked to ask again when a check ends.
- A file that changes again before its check starts is checked once, as its
newest text.
- Rename checks the renamed text itself, on the thread that serves
requests, as before.
All that is written to the client is written by the thread that serves
requests: the checking thread reports a check to it. Standard output is the
protocol's; whatever else the process writes to the console goes to
standard error.
## Building ## Building
It expects the Bjolang checkout beside this one, at `../Bjolang`, and runs It expects the Bjolang checkout beside this one, at `../Bjolang`, and runs
@ -292,9 +319,9 @@ With eglot instead:
## What it does not do yet ## What it does not do yet
- A range over several lines is marked as far as its head only. - A range over several lines is marked as far as its head only.
- A check of a large file waits for the requests before it, and they for it: - One check at a time. Checks run on a thread of their own (see "Checks in
everything that touches the compiler runs on one thread, because the the background"), one after another. A check that has started runs to its
compiler's state is global. end, also when its text is no longer the newest.
- Names a macro binds, at top level or locally. A loop variable is taken to - Names a macro binds, at top level or locally. A loop variable is taken to
be in scope across its whole loop, which is wider than the loop allows. be in scope across its whole loop, which is wider than the loop allows.
- Which definition. A name defined in two imported modules goes to the - Which definition. A name defined in two imported modules goes to the

View file

@ -176,10 +176,10 @@ let private read (env: Env) (file: string) (decls: TDecl list) : Index =
Fields = List.ofSeq fields } Fields = List.ofSeq fields }
/// Each file's index, from its last check. /// Each file's index, from its last check.
let private byFile = Collections.Generic.Dictionary<string, Index>() let private byFile = Collections.Concurrent.ConcurrentDictionary<string, Index>()
/// Each file's text as its last check read it: where an index's ranges are. /// Each file's text as its last check read it: where an index's ranges are.
let private checkedTexts = Collections.Generic.Dictionary<string, string>() let private checkedTexts = Collections.Concurrent.ConcurrentDictionary<string, string>()
/// The text of `path` its last check read, if it was checked. /// The text of `path` its last check read, if it was checked.
let checkedText (path: string) : string option = let checkedText (path: string) : string option =

View file

@ -1091,6 +1091,70 @@ def formatting(server, tmp):
expect("formatting: a text that does not read is refused, with why", "never closed" in answer.get("error", {}).get("message", ""), answer) expect("formatting: a text that does not read is refused, with why", "never closed" in answer.get("error", {}).get("message", ""), answer)
def slow_text(probe):
"""A file whose check takes a second or more: many small functions. The
last one binds `probe` to a local, for a hover of its type."""
parts = ["(import (std prelude))\n"]
for i in range(2500):
parts.append(f"(: (-> int int))\n(defun (f{i} n) (if (> n {i}) (+ n {i}) (* n 2)))\n")
parts.append(f"(defun (main)\n (let ((probed {probe}))\n (ignore probed)\n 0))\n")
return "\n".join(parts)
def responding(server, tmp):
"""A check runs on a thread of its own: a request that does not need it
is answered while it runs, and one that does is answered when it ends."""
import time
path = os.path.join(tmp, "slow.bjo")
uri = "file://" + path
first = slow_text("1")
with open(path, "w") as f:
f.write(first)
started = time.time()
found = server.diagnostics_after("textDocument/didOpen", uri, first)
check_time = time.time() - started
errors = [d for d in found if d["severity"] == 1]
expect("responding: the slow file checks", errors == [], json.dumps(errors[:2], indent=1))
print(f" the check takes {check_time:.2f} s")
expect("responding: the file is slow enough for the test to mean something", check_time > 0.5, f"{check_time:.2f} s")
# A change, and the check of it starts after the pause. While it runs:
second = slow_text('"text"')
server.published(uri)
server.change(uri, second, 2)
time.sleep(0.55)
started = time.time()
symbols = server.send("textDocument/documentSymbol", {"textDocument": {"uri": uri}}, request=True)["result"]
symbol_time = time.time() - started
before_answer = server.published(uri)
expect("responding: the outline is answered while the check runs", len(symbols) > 2500 and before_answer == [],
f"{len(symbols)} symbols, {len(before_answer)} diagnostics before the answer")
expect("responding: and much sooner than a check takes", symbol_time < check_time / 2, f"{symbol_time:.2f} s against {check_time:.2f} s")
print(f" the outline takes {symbol_time:.2f} s")
started = time.time()
at = position_of(second, "(probed ", 0, 2)
items = server.send("textDocument/completion", {"textDocument": {"uri": uri}, "position": at}, request=True)["result"]
expect("responding: so is a completion", items is not None and server.published(uri) == [], "")
# A hover needs the check's types. It is asked while the check runs, and
# answered when the check ends, with the types of the new text.
at = position_of(second, "(ignore probed)", 0, 9)
h = server.send("textDocument/hover", {"textDocument": {"uri": uri}, "position": at}, request=True)["result"]
value = h["contents"]["value"] if h else ""
expect("responding: a hover waits for the check, and has the new text's type", "(: probed string)" in value, value[:300])
after = server.next_diagnostics(uri)
expect("responding: the check of the change is published", [d for d in after if d["severity"] == 1] == [], after[:2])
# A hover asked before the pause is over starts the check at once.
third = slow_text("2.5")
server.change(uri, third, 3)
h = server.send("textDocument/hover", {"textDocument": {"uri": uri}, "position": at}, request=True)["result"]
value = h["contents"]["value"] if h else ""
expect("responding: a hover of text not yet checked is of that text", "(: probed double)" in value, value[:300])
server.diagnostics_after("textDocument/didClose", uri)
def fields(server, tmp): def fields(server, tmp):
path = os.path.join(tmp, "fields.bjo") path = os.path.join(tmp, "fields.bjo")
uri = "file://" + path uri = "file://" + path
@ -1764,6 +1828,7 @@ with tempfile.TemporaryDirectory() as tmp:
ranges(server, tmp) ranges(server, tmp)
helping(server, tmp) helping(server, tmp)
formatting(server, tmp) formatting(server, tmp)
responding(server, tmp)
renaming(server, tmp) renaming(server, tmp)
referencing(server, tmp) referencing(server, tmp)
acting(server, tmp) acting(server, tmp)