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:
parent
c5acafd5dd
commit
5e4ac7d9aa
6 changed files with 273 additions and 49 deletions
|
|
@ -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.
|
||||
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.
|
||||
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
|
||||
/// made in `path` as the file's.
|
||||
|
|
|
|||
2
Fixes.fs
2
Fixes.fs
|
|
@ -18,7 +18,7 @@ type Facts =
|
|||
|
||||
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
|
||||
/// keeps what is in `path` as the file's.
|
||||
|
|
|
|||
214
Program.fs
214
Program.fs
|
|
@ -52,12 +52,22 @@ let private texts = Collections.Generic.Dictionary<string, string>()
|
|||
/// starts.
|
||||
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 =
|
||||
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 =
|
||||
match Project.prepare (uriToPath uri) with
|
||||
| Some message ->
|
||||
|
|
@ -70,19 +80,24 @@ let private publish (uri: string) =
|
|||
Elsewhere = 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 =
|
||||
try
|
||||
Check.file buffers (uriToPath uri)
|
||||
Bjolang.Compilation.inNew (fun () -> Check.file job.Buffers (uriToPath job.Uri))
|
||||
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))
|
||||
|
||||
// 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
|
||||
Check.publishParams job.Uri (job.Note @ found)
|
||||
|
||||
/// 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.
|
||||
|
|
@ -630,6 +645,10 @@ let private capabilities () : JsonNode =
|
|||
|
||||
[<EntryPoint>]
|
||||
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 ()
|
||||
useInstalledCompiler ()
|
||||
let mutable shutdownAsked = false
|
||||
|
|
@ -660,6 +679,82 @@ let main _ =
|
|||
|
||||
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
|
||||
/// for it.
|
||||
let rec next () : JsonNode option =
|
||||
|
|
@ -679,7 +774,7 @@ let main _ =
|
|||
|
||||
for uri in due do
|
||||
dueChecks.Remove uri |> ignore
|
||||
publish uri
|
||||
startCheck uri
|
||||
|
||||
next ()
|
||||
|
||||
|
|
@ -712,7 +807,7 @@ let main _ =
|
|||
uri ()
|
||||
|> Option.iter (fun u ->
|
||||
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.
|
||||
| "textDocument/didChange" ->
|
||||
match uri (), message["params"]["contentChanges"] with
|
||||
|
|
@ -725,7 +820,7 @@ let main _ =
|
|||
uri ()
|
||||
|> Option.iter (fun u ->
|
||||
dueChecks.Remove u |> ignore
|
||||
publish u)
|
||||
startCheck u)
|
||||
// A closed file's diagnostics are the client's to forget,
|
||||
// and an empty list is how it is told to.
|
||||
| "textDocument/didClose" ->
|
||||
|
|
@ -733,24 +828,29 @@ let main _ =
|
|||
|> Option.iter (fun u ->
|
||||
texts.Remove u |> ignore
|
||||
dueChecks.Remove u |> ignore
|
||||
latest.TryRemove u |> ignore
|
||||
lastSymbols.Remove u |> ignore
|
||||
Rpc.notify "textDocument/publishDiagnostics" (Check.publishParams u []))
|
||||
| "textDocument/documentSymbol" ->
|
||||
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" ->
|
||||
let position = message["params"]["position"]
|
||||
let line = position["line"].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
|
||||
// to be of the text as it stands for them to be at
|
||||
// the right places.
|
||||
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)
|
||||
match uri () with
|
||||
| Some u -> whenChecked u (fun () -> Rpc.respond id (hoverAt u line character))
|
||||
| None -> Rpc.respond id null
|
||||
| "textDocument/completion" ->
|
||||
let position = message["params"]["position"]
|
||||
let line = position["line"].GetValue<int>()
|
||||
|
|
@ -803,14 +903,12 @@ let main _ =
|
|||
{ Line = n["line"].GetValue<int>() + 1
|
||||
Column = n["character"].GetValue<int>() }
|
||||
|
||||
let answer =
|
||||
uri ()
|
||||
|> Option.map (fun u ->
|
||||
if dueChecks.Remove u then publish u
|
||||
actionsAt u (position r["start"]) (position r["end"]))
|
||||
|> Option.defaultValue (JsonArray())
|
||||
let first = position r["start"]
|
||||
let last = position r["end"]
|
||||
|
||||
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
|
||||
// message, which says why.
|
||||
| "textDocument/prepareRename"
|
||||
|
|
@ -852,23 +950,57 @@ let main _ =
|
|||
| null -> otherwise
|
||||
| v -> v.GetValue<bool>()
|
||||
|
||||
let answer =
|
||||
uri ()
|
||||
|> Option.bind (fun u ->
|
||||
if dueChecks.Remove u then publish u
|
||||
let line = position["line"].GetValue<int>() + 1
|
||||
let character = position["character"].GetValue<int>()
|
||||
let full = flag "full" true
|
||||
let hygienic = flag "hygienic" false
|
||||
|
||||
Expansion.at
|
||||
(uriToPath u)
|
||||
(position["line"].GetValue<int>() + 1)
|
||||
(position["character"].GetValue<int>())
|
||||
(flag "full" true)
|
||||
(flag "hygienic" false))
|
||||
let answer (u: string) () =
|
||||
Expansion.at (uriToPath u) line character full hygienic
|
||||
|> Option.map (fun (macro, text) ->
|
||||
JsonObject(dict [ "macro", JsonValue.Create macro :> JsonNode; "text", JsonValue.Create text ])
|
||||
:> JsonNode)
|
||||
|> 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.
|
||||
| "" -> ()
|
||||
| _ when not (isNull id) -> Rpc.respondError id -32601 $"%s{methodName} is not supported"
|
||||
|
|
|
|||
33
README.md
33
README.md
|
|
@ -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
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
- 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:
|
||||
everything that touches the compiler runs on one thread, because the
|
||||
compiler's state is global.
|
||||
- One check at a time. Checks run on a thread of their own (see "Checks in
|
||||
the background"), one after another. A check that has started runs to its
|
||||
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
|
||||
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
|
||||
|
|
|
|||
4
Types.fs
4
Types.fs
|
|
@ -176,10 +176,10 @@ let private read (env: Env) (file: string) (decls: TDecl list) : Index =
|
|||
Fields = List.ofSeq fields }
|
||||
|
||||
/// 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.
|
||||
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.
|
||||
let checkedText (path: string) : string option =
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
||||
|
||||
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):
|
||||
path = os.path.join(tmp, "fields.bjo")
|
||||
uri = "file://" + path
|
||||
|
|
@ -1764,6 +1828,7 @@ with tempfile.TemporaryDirectory() as tmp:
|
|||
ranges(server, tmp)
|
||||
helping(server, tmp)
|
||||
formatting(server, tmp)
|
||||
responding(server, tmp)
|
||||
renaming(server, tmp)
|
||||
referencing(server, tmp)
|
||||
acting(server, tmp)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue