lsp-bjolang/Program.fs
Linus Björnstam 5e4ac7d9aa 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>
2026-11-25 09:32:15 +01:00

1018 lines
45 KiB
FSharp

/// A language server for Bjolang. It answers diagnostics, from the compiler's
/// own frontend, when a file is opened or saved.
module BjolangLsp.Program
open System
open System.Reflection
open System.Text.Json.Nodes
/// Points the compiler at the Bjolang checkout this server was built against,
/// unless BJOLANG_HOME already names one. Done before anything touches
/// `Bjolang.Paths`, whose locations are computed once, when it is first used.
let private setBjolangHome () =
match Environment.GetEnvironmentVariable "BJOLANG_HOME" with
| null
| "" ->
Assembly.GetExecutingAssembly().GetCustomAttributes<AssemblyMetadataAttribute>()
|> Seq.tryFind (fun a -> a.Key = "BjolangHome")
|> Option.iter (fun a -> Environment.SetEnvironmentVariable("BJOLANG_HOME", a.Value))
| _ -> ()
/// Makes the checks the installed compiler's: staleness judged against
/// `bin/compiler/Bjolang.dll` rather than this server's copy of the compiler,
/// and a stale import built by running that compiler. Built here, an import's
/// build record would name this server, and the command line would build it
/// again.
///
/// The variable is only read while the backend is installed, and is cleared
/// again so that the compiler it starts builds its own imports as usual.
let private useInstalledCompiler () =
let installed = IO.Path.Combine(Bjolang.Paths.root, "bin", "compiler", "Bjolang.dll")
if IO.File.Exists installed then
Bjolang.Paths.compilerAssembly.Value <- installed
Environment.SetEnvironmentVariable("BJOLANG_OUT_OF_PROCESS_DEPS", "1")
Bjolang.Build.installDependencyBackend ()
Environment.SetEnvironmentVariable("BJOLANG_OUT_OF_PROCESS_DEPS", null)
else
Rpc.log $"no compiler at %s{installed}; run build_compiler.sh there. Files that import a stale module will fail to check."
let private uriToPath (uri: string) = Uri(uri).LocalPath
let private str (node: JsonNode) (path: string list) =
path |> List.fold (fun (n: JsonNode) key -> if isNull n then null else n[key]) node
|> fun n -> if isNull n then None else Some(n.GetValue<string>())
/// The text of each open file as the editor has it, saved or not. Symbols,
/// definitions, completions and checks are all read from it, so that they
/// follow the buffer.
let private texts = Collections.Generic.Dictionary<string, string>()
/// Whether the client takes `workspace/inlayHint/refresh`, as it says when it
/// starts.
let mutable private refreshesHints = false
/// 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
let note: Check.Found list =
match Project.prepare (uriToPath uri) with
| Some message ->
[ { Line = 0
Column = 0
EndLine = 1
EndColumn = 0
IsError = false
Message = message
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
Bjolang.Compilation.inNew (fun () -> Check.file job.Buffers (uriToPath job.Uri))
with ex ->
Rpc.log $"check of %s{job.Uri} failed: %O{ex}"
[]
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.
let private dueChecks = Collections.Generic.Dictionary<string, DateTime>()
let private pause = TimeSpan.FromMilliseconds 400.0
let private textOf (uri: string) =
match texts.TryGetValue uri with
| true, text -> text
| _ -> IO.File.ReadAllText(uriToPath uri)
/// A compiler range as an LSP one. Lines are 1-based in the compiler and
/// 0-based in LSP; columns are 0-based in both.
let private range (r: Bjolang.Lexer.Range) : JsonNode =
let position (p: Bjolang.Lexer.Position) =
JsonObject(dict [ "line", JsonValue.Create(max 0 (p.Line - 1)) :> JsonNode; "character", JsonValue.Create p.Column ])
:> JsonNode
JsonObject(dict [ "start", position r.Start; "end", position r.End ])
let rec private documentSymbol (s: Symbols.Symbol) : JsonNode =
JsonObject(
dict
[ "name", JsonValue.Create s.Name :> JsonNode
"detail", JsonValue.Create s.Detail
"kind", JsonValue.Create(int s.Kind)
"range", range s.Range
"selectionRange", range s.NameRange
"children", JsonArray(s.Children |> List.map documentSymbol |> Array.ofList) ]
)
/// The last symbols each file read to, kept for while it does not read: a
/// half-typed form would otherwise empty the outline on every keystroke.
let private lastSymbols = Collections.Generic.Dictionary<string, Symbols.Symbol list>()
let private symbolsOf (uri: string) : JsonNode =
let symbols =
match Symbols.ofText (uriToPath uri) (textOf uri) with
| Some symbols ->
lastSymbols[uri] <- symbols
symbols
| None ->
match lastSymbols.TryGetValue uri with
| true, symbols -> symbols
| _ -> []
JsonArray(symbols |> List.map documentSymbol |> Array.ofList)
/// The name at an LSP position, where it is, and its definition.
let private lookup (uri: string) (line: int) (character: int) =
let path = uriToPath uri
let text = textOf uri
Symbols.nameAt path text (line + 1) character
|> Option.bind (fun (name, at) -> Symbols.definition path text name |> Option.map (fun found -> at, found))
/// The local binding the name at an LSP position refers to, if it is one, and
/// where the name is.
let private localAt (uri: string) (line: int) (character: int) : (Scope.Binder * Bjolang.Lexer.Range) option =
let path = uriToPath uri
let text = textOf uri
match Symbols.nameAt path text (line + 1) character, Symbols.forms path text with
| Some(name, at), Some forms -> Scope.find forms (line + 1) character name |> Option.map (fun b -> b, at)
| _ -> None
let private location (r: Bjolang.Lexer.Range) : JsonNode =
JsonObject(dict [ "uri", JsonValue.Create(Uri(r.File).AbsoluteUri) :> JsonNode; "range", range r ])
let private definitionAt (uri: string) (line: int) (character: int) : JsonNode =
match localAt uri line character with
| Some(b, _) -> location b.Range
| None ->
match lookup uri line character with
| None -> null
| Some(_, found) -> location found.Symbol.NameRange
let private markdownContent (text: string) : JsonNode =
JsonObject(dict [ "kind", JsonValue.Create "markdown" :> JsonNode; "value", JsonValue.Create text ])
/// What a hover says about `name`: of its definition, or of the builtin it
/// is.
let private describe (uri: string) (name: string) : string option =
match Symbols.definition (uriToPath uri) (textOf uri) name with
| Some found ->
// What the compiler inferred, for a definition the last check of a
// file saw, which a hover shows where no signature is written.
let inferred = Types.boundAt found.Symbol.NameRange.File name found.Symbol.NameRange
Some(Hover.text found inferred)
| None -> Hover.builtin name
/// The type the last check inferred for the local `b`: at the use written at
/// `at`, or where it is bound.
let private localType (uri: string) (b: Scope.Binder) (at: Bjolang.Lexer.Range) : string option =
let path = uriToPath uri
match Types.useAt path b.Name at with
| Some u -> Some u.Type
| None -> Types.boundAt path b.Name b.Range
/// The record, struct or union a type as shown names, if this file sees its
/// definition: `Leg`, `module/Leg`, `(Pair int)`.
let private typeDefinition (uri: string) (shown: string) : Symbols.Found option =
let head =
if shown.StartsWith "(" then
shown.Substring(1).Split([| ' '; ')' |], StringSplitOptions.RemoveEmptyEntries) |> Array.tryHead
else
Some shown
head
|> Option.map (fun h -> h.Substring(h.LastIndexOf '/' + 1))
|> Option.filter (fun h -> h <> "" && Char.IsUpper h[0])
|> Option.bind (Symbols.definition (uriToPath uri) (textOf uri))
|> Option.filter (fun found -> found.Symbol.Kind = Symbols.Kind.Struct || found.Symbol.Kind = Symbols.Kind.Class)
let private hoverAt (uri: string) (line: int) (character: int) : JsonNode =
let answer (text: string) (at: Bjolang.Lexer.Range) =
JsonObject(dict [ "contents", markdownContent text; "range", range at ]) :> JsonNode
match localAt uri line character with
| Some(b, at) ->
let inferred = localType uri b at
// A record's or a struct's definition beside a local of its type.
let ofType =
inferred
|> Option.bind (typeDefinition uri)
|> Option.map (fun found -> Hover.text found None)
|> Option.toList
answer (String.concat "\n\n---\n\n" (Hover.local b inferred (Symbols.sliceOf (textOf uri) b.Shown) :: ofType)) at
| None ->
match Symbols.nameAt (uriToPath uri) (textOf uri) (line + 1) character with
| None -> null
// `(.x r)`: the field read, with its type there.
| Some(name, at) when
name.Length > 1
&& name.StartsWith "."
&& (Types.fieldAt (uriToPath uri) (name.Substring 1) at).IsSome
->
let f = (Types.fieldAt (uriToPath uri) (name.Substring 1) at).Value
answer (Hover.field f.Field f.Type f.Record (typeDefinition uri f.Record)) at
| Some(name, at) ->
let here =
match Types.useAt (uriToPath uri) name at with
| Some u when u.Generic -> [ Hover.instantiated name u.Type ]
| _ -> []
match describe uri name with
| None when here.IsEmpty -> null
| None -> answer (String.concat "\n\n" here) at
| Some text -> answer (String.concat "\n\n" (text :: here)) at
/// The completions at a position. Each replaces the whole word before the
/// cursor. Only names that start with the word's first character are sent,
/// as the client filters the rest of the way itself, and every name at once
/// is two thousand of them.
let private completionAt (uri: string) (line: int) (character: int) : JsonNode =
let text = textOf uri
let lines = text.Replace("\r\n", "\n").Split('\n')
let lineText = if line < lines.Length then lines[line] else ""
let column = min character lineText.Length
let start = Completion.wordStart lineText column
let word = lineText.Substring(start, column - start)
let own = IO.Path.GetFileName(uriToPath uri)
let position (c: int) =
JsonObject(dict [ "line", JsonValue.Create line :> JsonNode; "character", JsonValue.Create c ]) :> JsonNode
let replace = JsonObject(dict [ "start", position start; "end", position column ])
let rank (item: Completion.Item) =
match item.From with
| "local" -> 0
| f when f = own -> 1
| "builtin" -> 3
| "special form" -> 4
| _ -> 2
// The locals in scope, innermost first and each name once: an inner
// binding hides an outer one, and both hide a top-level name.
let locals =
match Symbols.forms (uriToPath uri) text with
| Some forms ->
Scope.at forms (line + 1) column
|> List.rev
|> List.distinctBy (fun b -> b.Name)
// The word being typed is not yet a name in scope, unless it is
// the binder itself, which is not worth offering either.
|> List.filter (fun b -> not (b.Range.Start.Line = line + 1 && b.Range.Start.Column = start))
| None -> []
let localNames = locals |> List.map (fun b -> b.Name) |> Set.ofList
let candidates =
if Completion.inText lineText column then
[]
else
(locals |> List.map (fun b -> ({ Label = b.Name; Kind = Completion.ItemKind.Variable; From = "local" }: Completion.Item)))
@ (Completion.items (uriToPath uri) text |> List.filter (fun item -> not (localNames.Contains item.Label)))
let localDoc =
locals
|> List.map (fun b -> b.Name, Hover.local b (Types.boundAt (uriToPath uri) b.Name b.Range) (Symbols.sliceOf text b.Shown))
|> Map.ofList
let items =
candidates
|> List.filter (fun item -> word = "" || Char.ToLowerInvariant item.Label[0] = Char.ToLowerInvariant word[0])
|> List.map (fun item ->
let fields =
[ "label", JsonValue.Create item.Label :> JsonNode
"kind", JsonValue.Create(int item.Kind)
"labelDetails", JsonObject(dict [ "description", JsonValue.Create item.From :> JsonNode ])
"sortText", JsonValue.Create($"%d{rank item}%s{item.Label}")
"textEdit",
JsonObject(dict [ "range", replace.DeepClone(); "newText", JsonValue.Create item.Label :> JsonNode ]) ]
// A local's doc is at hand; anything else's is found when the
// client asks for it.
let more =
match item.From, Map.tryFind item.Label localDoc with
| "local", Some doc -> [ "documentation", markdownContent doc ]
| _ -> [ "data", JsonObject(dict [ "uri", JsonValue.Create uri :> JsonNode; "name", JsonValue.Create item.Label ]) :> JsonNode ]
JsonObject(dict (fields @ more)) :> JsonNode)
JsonObject(dict [ "isIncomplete", JsonValue.Create false :> JsonNode; "items", JsonArray(Array.ofList items) ])
/// The inlay hints in an LSP range of lines.
let private hintsIn (uri: string) (first: int) (last: int) : JsonNode =
Inlay.between (uriToPath uri) (textOf uri) (first + 1) (last + 1)
|> List.map (fun h ->
JsonObject(
dict
[ "position",
JsonObject(
dict [ "line", JsonValue.Create(h.At.Line - 1) :> JsonNode; "character", JsonValue.Create h.At.Column ]
)
:> JsonNode
"label", JsonValue.Create h.Label
"kind", JsonValue.Create 1
"tooltip", JsonValue.Create h.Tooltip ]
)
:> JsonNode)
|> Array.ofList
|> JsonArray
:> JsonNode
/// A completion item with its doc, which is the hover of its name.
let private resolve (item: JsonNode) : JsonNode =
let data = item["data"]
if not (isNull data) then
let uri = data["uri"].GetValue<string>()
let name = data["name"].GetValue<string>()
match describe uri name with
| Some text -> item["documentation"] <- markdownContent text
| None -> ()
item.DeepClone()
/// A file's text: the editor's, where it has the file open, else what is on
/// disk.
let private textOfPath (path: string) : string =
let full = IO.Path.GetFullPath path
match texts |> Seq.tryFind (fun kv -> IO.Path.GetFullPath(uriToPath kv.Key) = full) with
| Some kv -> kv.Value
| None -> if IO.File.Exists full then IO.File.ReadAllText full else ""
/// `text` with each of `edits` replaced by `newText`. Lines are 1-based and
/// columns 0-based, as a compiler range has them.
let private applyEdits (text: string) (edits: Rename.Edit list) (newText: string) : string =
let lineStarts =
[| yield 0
for i in 0 .. text.Length - 1 do
if text[i] = '\n' then yield i + 1 |]
let offset (p: Bjolang.Lexer.Position) = lineStarts[p.Line - 1] + p.Column
edits
|> List.sortByDescending (fun e -> offset e.Range.Start)
|> List.fold
(fun (t: string) e ->
let start = offset e.Range.Start
t.Substring(0, start) + newText + t.Substring(offset e.Range.End))
text
/// The range of the name `prepareRename` asks about, and the name, or why it
/// cannot be renamed.
let private prepareRenameAt (uri: string) (line: int) (character: int) : Result<JsonNode, string> =
Rename.plan textOfPath (uriToPath uri) (line + 1) character
|> Result.map (fun p ->
match Symbols.nameAt (uriToPath uri) (textOf uri) (line + 1) character with
| Some(_, at) ->
JsonObject(dict [ "range", range at; "placeholder", JsonValue.Create p.Old :> JsonNode ]) :> JsonNode
| None -> null)
/// The edit that renames the name at a position to `newName`, or why it is
/// refused.
///
/// The renamed text is checked before it is offered, against a check of the
/// text as it is: an error the renamed program has and this one does not is
/// a rename that changed what something means, and is refused with it. The
/// check after it leaves the file's types those of the renamed text, so the
/// file is checked again as it stands.
let private renameAt (uri: string) (line: int) (character: int) (newName: string) : Result<JsonNode, string> =
let path = IO.Path.GetFullPath(uriToPath uri)
match Rename.plan textOfPath path (line + 1) character with
| Error why -> Error why
| Ok p ->
match Rename.capture textOfPath path p newName with
| Some why -> Error why
| None ->
let byFile = p.Edits |> List.groupBy (fun e -> e.File)
let buffers =
texts |> Seq.map (fun kv -> IO.Path.GetFullPath(uriToPath kv.Key), kv.Value) |> Map.ofSeq
let renamed =
byFile
|> List.fold
(fun (acc: Map<string, string>) (file, edits) ->
Map.add file (applyEdits (textOfPath file) edits newName) acc)
buffers
let errors (found: Check.Found list) =
found |> List.filter (fun f -> f.IsError) |> List.map (fun f -> f.Message)
// A message about the old name, as it reads about the new one. Only
// the whole name is replaced: `n` is in "not" too.
let renamedIn (message: string) =
Text.RegularExpressions.Regex.Replace(
message,
@"(?<![A-Za-z0-9_?!*/<>=+&.-])" + Text.RegularExpressions.Regex.Escape p.Old + @"(?![A-Za-z0-9_?!*/<>=+&.-])",
newName
)
let before = Check.file buffers path |> errors |> List.map renamedIn |> Set.ofList
let after = Check.file renamed path |> errors
dueChecks[uri] <- DateTime.UtcNow
match after |> List.tryFind (fun m -> not (before.Contains m)) with
| Some m ->
Error $"Renaming '%s{p.Old}' to '%s{newName}' would give the program an error it does not have now: %s{m}"
| None ->
let uriOf (file: string) =
if file = path then uri else Uri(file).AbsoluteUri
let changes =
byFile
|> List.map (fun (file, edits) ->
uriOf file,
JsonArray(
edits
|> List.map (fun e ->
JsonObject(dict [ "range", range e.Range; "newText", JsonValue.Create newName :> JsonNode ])
:> JsonNode)
|> Array.ofList
)
:> JsonNode)
Ok(JsonObject(dict [ "changes", JsonObject(dict changes) :> JsonNode ]) :> JsonNode)
/// The uses of the name at a position, in its module, as LSP locations; the
/// definition among them only if `withDefinition`.
let private referencesAt (uri: string) (line: int) (character: int) (withDefinition: bool) : JsonNode =
let path = IO.Path.GetFullPath(uriToPath uri)
let uriOf (file: string) = if file = path then uri else Uri(file).AbsoluteUri
match Uses.at textOfPath path (line + 1) character with
| None -> null
| Some(_, uses) ->
JsonArray(
uses
|> List.filter (fun u -> withDefinition || not u.IsDefinition)
|> List.map (fun u ->
JsonObject(dict [ "uri", JsonValue.Create(uriOf u.File) :> JsonNode; "range", range u.Range ]) :> JsonNode)
|> Array.ofList
)
:> JsonNode
/// The uses of the name at a position in this file, for the editor to mark:
/// the definition as a write, the rest as reads.
let private highlightsAt (uri: string) (line: int) (character: int) : JsonNode =
let path = IO.Path.GetFullPath(uriToPath uri)
match Uses.at textOfPath path (line + 1) character with
| None -> null
| Some(_, uses) ->
JsonArray(
uses
|> List.filter (fun u -> u.File = path)
|> List.map (fun u ->
JsonObject(dict [ "range", range u.Range; "kind", JsonValue.Create(if u.IsDefinition then 3 else 2) :> JsonNode ])
:> JsonNode)
|> Array.ofList
)
:> JsonNode
/// The code actions for the span from `first` to `last` of a file: what its
/// last check worked out there, if the text is still what it checked.
let private actionsAt (uri: string) (first: Bjolang.Lexer.Position) (last: Bjolang.Lexer.Position) : JsonNode =
let path = IO.Path.GetFullPath(uriToPath uri)
let text = textOf uri
let actions =
match Types.checkedText path with
| Some checkedText when checkedText = text -> Actions.at path text first last
| _ -> []
JsonArray(
actions
|> List.map (fun a ->
let edit =
JsonObject(dict [ "range", range a.Range; "newText", JsonValue.Create a.NewText :> JsonNode ])
JsonObject(
dict
[ "title", JsonValue.Create a.Title :> JsonNode
"kind", JsonValue.Create "quickfix"
"edit", JsonObject(dict [ "changes", JsonObject(dict [ uri, JsonArray(edit) :> JsonNode ]) :> JsonNode ]) ]
)
:> JsonNode)
|> Array.ofList
)
:> JsonNode
/// `textDocument/signatureHelp`: the function whose call the position is in,
/// its parameters, and the one that is being written.
///
/// - The function is the innermost form around the position whose head is a
/// function this file sees: a definition of the file or of a module it
/// sees, or a builtin. A special form or a macro is passed over, so that
/// an argument written inside a `let` has the help of the call around it.
/// - A definition shows its head as written, `(name a #:key default)`. An
/// import of a .NET member, a method of a trait and a builtin show their
/// type.
/// - A local function has no help.
let private signatureHelpAt (uri: string) (line: int) (character: int) : JsonNode =
let path = uriToPath uri
let text = (textOf uri).Replace("\r\n", "\n")
// The text as far as the position.
let prefix =
let lines = text.Split('\n')
if line >= lines.Length then
text
else
let last = lines[line]
String.Join("\n", Array.append (Array.truncate line lines) [| last.Substring(0, min character last.Length) |])
let shapeOf (name: string) : SignatureHelp.Shape option =
match Symbols.definition path text name with
| Some found ->
let m = found.Module
let s = found.Symbol
SignatureHelp.formAt s.Signature m.Forms
|> Option.bind (fun form ->
if s.Kind = Symbols.Kind.Function && s.Detail.StartsWith "def" then
SignatureHelp.ofHead m.Slice form
else
SignatureHelp.functionTypeIn form |> Option.bind (SignatureHelp.ofType m.Slice name))
| None ->
Hover.builtinDeclaration name
|> Option.bind (fun declared ->
Symbols.forms "" declared
|> Option.bind List.tryHead
|> Option.bind SignatureHelp.functionTypeIn
|> Option.bind (SignatureHelp.ofType (Symbols.sliceOf declared) name))
let found =
SignatureHelp.calls path prefix
|> List.tryPick (fun call -> shapeOf call.Head |> Option.map (fun shape -> call, shape))
match found with
| None -> null
| Some(call, shape) ->
let parameters =
shape.Parameters
|> List.map (fun (first, last) ->
JsonObject(dict [ "label", JsonArray(JsonValue.Create first, JsonValue.Create last) :> JsonNode ]) :> JsonNode)
let signature =
JsonObject(
dict
[ "label", JsonValue.Create shape.Label :> JsonNode
"parameters", JsonArray(Array.ofList parameters) ]
)
describe uri call.Head |> Option.iter (fun doc -> signature["documentation"] <- markdownContent doc)
let help =
JsonObject(dict [ "signatures", JsonArray(signature) :> JsonNode; "activeSignature", JsonValue.Create 0 ])
// With no parameter to mark, as for an argument too many, the field
// is left out. A client then marks the first one.
SignatureHelp.active shape call |> Option.iter (fun index -> help["activeParameter"] <- JsonValue.Create index)
help
/// `textDocument/formatting`: one edit that replaces the whole text with what
/// `bjo fmt` makes of it, or no edit when the text is laid out already.
let private formattingOf (uri: string) : Result<JsonNode, string> =
let text = textOf uri
match Format.source text with
| Error why -> Error why
| Ok laidOut when laidOut = text -> Ok(JsonArray())
| Ok laidOut ->
let lines = text.Replace("\r\n", "\n").Split('\n')
let position (l: int) (c: int) =
JsonObject(dict [ "line", JsonValue.Create l :> JsonNode; "character", JsonValue.Create c ]) :> JsonNode
let whole =
JsonObject(dict [ "start", position 0 0; "end", position (lines.Length - 1) lines[lines.Length - 1].Length ])
Ok(JsonArray(JsonObject(dict [ "range", whole :> JsonNode; "newText", JsonValue.Create laidOut ])))
let private capabilities () : JsonNode =
JsonNode.Parse
"""
{ "capabilities":
{ "textDocumentSync": { "openClose": true, "change": 1, "save": { "includeText": false } },
"documentSymbolProvider": true,
"definitionProvider": true,
"hoverProvider": true,
"inlayHintProvider": true,
"renameProvider": { "prepareProvider": true },
"referencesProvider": true,
"documentHighlightProvider": true,
"codeActionProvider": { "codeActionKinds": [ "quickfix" ] },
"signatureHelpProvider": { "triggerCharacters": [ "(", " " ] },
"documentFormattingProvider": true,
"completionProvider": { "resolveProvider": true, "triggerCharacters": [ "(" ] } },
"serverInfo": { "name": "bjolang-lsp", "version": "0.8.0" } }
"""
[<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
// Messages are read on a thread of their own and handled on this one.
// Compiler work has to stay on one thread, as `Session` swaps the
// compiler's global state around each piece of it; reading apart from it
// is what lets this one notice that typing has paused.
let inbox = new Collections.Concurrent.BlockingCollection<JsonNode option>()
let reader =
Threading.Thread(
(fun () ->
let rec go () =
match Rpc.read () with
| Some m ->
inbox.Add(Some m)
go ()
| None -> inbox.Add None
try
go ()
with ex ->
Rpc.log $"reading failed: %O{ex}"
inbox.Add None),
IsBackground = true
)
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 =
if dueChecks.Count = 0 then
inbox.Take()
else
let soonest = dueChecks.Values |> Seq.min
let untilDue = soonest - DateTime.UtcNow
let wait = if untilDue < TimeSpan.Zero then TimeSpan.Zero else untilDue
let mutable message: JsonNode option = None
if inbox.TryTake(&message, wait) then
message
else
let due =
dueChecks |> Seq.filter (fun kv -> kv.Value <= DateTime.UtcNow) |> Seq.map (fun kv -> kv.Key) |> List.ofSeq
for uri in due do
dueChecks.Remove uri |> ignore
startCheck uri
next ()
let rec serve () =
match next () with
| None -> if shutdownAsked then 0 else 1
| Some message ->
let id = message["id"]
let methodName = str message [ "method" ] |> Option.defaultValue ""
let uri () = str message [ "params"; "textDocument"; "uri" ]
match methodName with
| "exit" -> if shutdownAsked then 0 else 1
| _ ->
try
match methodName with
| "initialize" ->
refreshesHints <-
[ "params"; "capabilities"; "workspace"; "inlayHint"; "refreshSupport" ]
|> List.fold (fun (n: JsonNode) key -> if isNull n then null else n[key]) message
|> function
| null -> false
| v -> v.GetValue<bool>()
Rpc.respond id (capabilities ())
| "shutdown" ->
shutdownAsked <- true
Rpc.respond id null
| "textDocument/didOpen" ->
uri ()
|> Option.iter (fun u ->
str message [ "params"; "textDocument"; "text" ] |> Option.iter (fun t -> texts[u] <- t)
startCheck u)
// Full sync: the one change is the whole text.
| "textDocument/didChange" ->
match uri (), message["params"]["contentChanges"] with
| Some u, (:? JsonArray as changes) when changes.Count > 0 ->
let last = changes[changes.Count - 1]
texts[u] <- last["text"].GetValue<string>()
dueChecks[u] <- DateTime.UtcNow + pause
| _ -> ()
| "textDocument/didSave" ->
uri ()
|> Option.iter (fun u ->
dueChecks.Remove u |> ignore
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" ->
uri ()
|> 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" ->
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>()
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>()
let character = position["character"].GetValue<int>()
Rpc.respond id (uri () |> Option.map (fun u -> completionAt u line character) |> Option.defaultValue null)
| "completionItem/resolve" -> Rpc.respond id (resolve message["params"])
| "textDocument/signatureHelp" ->
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 -> signatureHelpAt u line character) |> Option.defaultValue null)
// A text that cannot be laid out is an error answer, with
// what `bjo fmt` says of it.
| "textDocument/formatting" ->
match uri () |> Option.map formattingOf with
| Some(Ok edits) -> Rpc.respond id edits
| Some(Error why) -> Rpc.respondError id -32803 why
| None -> Rpc.respond id null
| "textDocument/references"
| "textDocument/documentHighlight" ->
let p = message["params"]
let position = p["position"]
let line = position["line"].GetValue<int>()
let character = position["character"].GetValue<int>()
let withDefinition =
match p["context"] with
| null -> true
| c ->
match c["includeDeclaration"] with
| null -> true
| v -> v.GetValue<bool>()
let answer =
uri ()
|> Option.map (fun u ->
if methodName = "textDocument/references" then referencesAt u line character withDefinition
else highlightsAt u line character)
|> Option.defaultValue null
Rpc.respond id answer
// What is offered is from the last check, which a check
// that is due replaces first, as for a hover.
| "textDocument/codeAction" ->
let r = message["params"]["range"]
let position (n: JsonNode) : Bjolang.Lexer.Position =
{ Line = n["line"].GetValue<int>() + 1
Column = n["character"].GetValue<int>() }
let first = position r["start"]
let last = position r["end"]
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"
| "textDocument/rename" ->
let p = message["params"]
let position = p["position"]
let line = position["line"].GetValue<int>()
let character = position["character"].GetValue<int>()
let answer =
match uri () with
| None -> Error "No document."
| Some u when methodName = "textDocument/prepareRename" -> prepareRenameAt u line character
| Some u -> renameAt u line character (p["newName"].GetValue<string>())
match answer with
| Ok result -> Rpc.respond id result
| Error why -> Rpc.respondError id -32803 why
// Not run first when a check is due, as a hover is: a
// client asks for hints on every change. The check sends
// a refresh when it has run.
| "textDocument/inlayHint" ->
let r = message["params"]["range"]
let startsAt = r["start"]
let endsAt = r["end"]
let first = startsAt["line"].GetValue<int>()
let last = endsAt["line"].GetValue<int>()
Rpc.respond id (uri () |> Option.map (fun u -> hintsIn u first last) |> Option.defaultValue (JsonArray()))
// Not part of LSP: the expansion of the macro call at a
// position, from the file's last check. A check that is
// due runs first, so that the expansion is of the text as
// it stands.
| "bjolang/expandMacro" ->
let p = message["params"]
let position = p["position"]
let flag (key: string) (otherwise: bool) =
match p[key] with
| null -> otherwise
| v -> v.GetValue<bool>()
let line = position["line"].GetValue<int>() + 1
let character = position["character"].GetValue<int>()
let full = flag "full" true
let hygienic = 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
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"
// Any other notification, `initialized` included, needs no
// answer.
| _ -> ()
with ex ->
Rpc.log $"%s{methodName} failed: %O{ex}"
if not (isNull id) then
Rpc.respondError id -32603 ex.Message
serve ()
serve ()