diff --git a/BjolangLsp.fsproj b/BjolangLsp.fsproj
index 0f37b68..54952a6 100644
--- a/BjolangLsp.fsproj
+++ b/BjolangLsp.fsproj
@@ -27,9 +27,11 @@
+
+
diff --git a/Check.fs b/Check.fs
index 502b037..34ec30d 100644
--- a/Check.fs
+++ b/Check.fs
@@ -219,11 +219,21 @@ let file (buffers: Map) (path: string) : Found list =
Diagnostics.reset ()
Paths.sourceOverrides <- buffers
+ // The text the check reads, for what to mark at a column and for where
+ // the types it infers are.
+ let text =
+ match buffers.TryFind(Path.GetFullPath path) with
+ | Some t -> Some t
+ | None when File.Exists path -> Some(File.ReadAllText path)
+ | None -> None
+
let status, printed =
try
Diagnostics.captured (fun () ->
try
- Expansion.recording path (fun () -> Session.isolated (fun () -> Build.compile options path))
+ Expansion.recording path (fun () ->
+ Types.recording path (Option.defaultValue "" text) (fun () ->
+ Session.isolated (fun () -> Build.compile options path)))
with ex ->
printfn "%s" (Diagnostics.humanize ex.Message)
1)
@@ -235,13 +245,6 @@ let file (buffers: Map) (path: string) : Found list =
let _, report = Diagnostics.captured Timing.report
Rpc.log report
- // The text the check read, for what to mark at a column.
- let text =
- match buffers.TryFind(Path.GetFullPath path) with
- | Some t -> Some t
- | None when File.Exists path -> Some(File.ReadAllText path)
- | None -> None
-
let collected = Diagnostics.snapshot () |> List.map (found text path)
if status <> 0 && not (collected |> List.exists (fun f -> f.IsError)) then
diff --git a/Hover.fs b/Hover.fs
index 8a83858..c2dad14 100644
--- a/Hover.fs
+++ b/Hover.fs
@@ -225,14 +225,21 @@ let private doc (found: Found) : string option =
|> Option.map (fun entry -> docText entry (Some found.Symbol.Name))
| _ -> None
-/// The hover for a local name: its binding as written, and what binds it.
-let local (b: Scope.Binder) (shown: string) : string =
+/// The hover for a local name: its type, if the last check inferred one, its
+/// binding as written, and what binds it.
+let local (b: Scope.Binder) (inferred: string option) (shown: string) : string =
let what = b.Description
let sentence = string (Char.ToUpperInvariant what[0]) + what.Substring 1
- [ fence (clip shown); $"*%s{sentence}.*" ]
+ let declared = inferred |> Option.map (fun t -> $"(: %s{b.Name} %s{t})") |> Option.toList
+
+ [ fence (String.concat "\n" (declared @ [ clip shown ])); $"*%s{sentence}.*" ]
|> String.concat "\n\n"
+/// What a hover over a use of a generic binding adds: the type it has there.
+let instantiated (name: string) (t: string) : string =
+ "*At this use:*\n\n" + fence $"(: %s{name} %s{t})"
+
/// The type of a builtin, one the compiler defines rather than a module, as a
/// declaration: `(: seq-unfold (-> ...))`. `None` for a name that is not one.
let builtinDeclaration (name: string) : string option =
diff --git a/Inlay.fs b/Inlay.fs
new file mode 100644
index 0000000..8cb7631
--- /dev/null
+++ b/Inlay.fs
@@ -0,0 +1,83 @@
+/// Inlay hints: the type the compiler inferred for each local name where it
+/// is bound, after the name, where the program writes no type.
+///
+/// A local is found as go to definition finds one (`Scope`), and its type is
+/// the last check's (`Types`). A top-level function's parameters have none:
+/// its signature, which says their types, is written above it.
+module BjolangLsp.Inlay
+
+open System
+open Bjolang.Lexer
+open Bjolang.Ast
+
+type Hint =
+ { /// Right after the name. Lines are 1-based, columns 0-based.
+ At: Position
+ Label: string
+ Tooltip: string }
+
+/// How much of a type a hint shows; the tooltip has the rest.
+let private longest = 40
+
+/// The symbols in `s` that could be a local's binding: not the name in a
+/// `(: name Type)`, which has its type written, and not a top-level
+/// function's parameters.
+let rec private candidates (topLevel: bool) (s: SExpr) : (string * Range) list =
+ match s with
+ | SAtom { Token = Symbol n; Range = r } -> [ n, r ]
+ | SList(SAtom { Token = Colon } :: _, _) -> []
+ | SList(SAtom { Token = Symbol head } as h :: SList _ :: rest, _) when topLevel && head.StartsWith "def" ->
+ candidates false h @ (rest |> List.collect (candidates false))
+ | SList(items, _) -> items |> List.collect (candidates false)
+ | _ -> []
+
+let private before (a: Position) (b: Position) =
+ a.Line < b.Line || (a.Line = b.Line && a.Column <= b.Column)
+
+/// Where `now` first differs from `seen`, as a position; `None` when they
+/// are the same.
+let private firstChange (seen: string) (now: string) : Position option =
+ if seen = now then
+ None
+ else
+ let common = Seq.zip seen now |> Seq.takeWhile (fun (a, b) -> a = b) |> Seq.length
+ let prefix = seen.Substring(0, common)
+ let line = prefix |> Seq.filter ((=) '\n') |> Seq.length
+ let lineStart = prefix.LastIndexOf '\n' + 1
+ Some { Line = line + 1; Column = common - lineStart }
+
+/// The hints between `first` and `last` (1-based lines, inclusive) of `path`,
+/// whose text is `text`.
+///
+/// The types are from the last check. Where the text has changed since, a
+/// hint after the first change could be at the wrong place, so those wait for
+/// the next check; the ones before it are where they were.
+let between (path: string) (text: string) (first: int) (last: int) : Hint list =
+ match Symbols.forms path text, Types.checkedText path with
+ | Some forms, Some seen ->
+ let stale = firstChange seen text
+
+ forms
+ |> List.filter (fun f ->
+ let r = getRange f
+ r.End.Line >= first && r.Start.Line <= last)
+ |> List.collect (candidates true)
+ |> List.filter (fun (n, r) ->
+ n <> "_"
+ && r.Start.Line >= first
+ && r.Start.Line <= last
+ && (match stale with
+ | Some change -> before r.End change
+ | None -> true))
+ |> List.choose (fun (n, r) ->
+ match Scope.find forms r.Start.Line r.Start.Column n with
+ | Some b when b.Range.Start = r.Start ->
+ Types.boundAt path n b.Range
+ |> Option.map (fun t ->
+ let shown = if t.Length <= longest then t else t.Substring(0, longest - 1) + "…"
+
+ { At = r.End
+ Label = ": " + shown
+ Tooltip = $"(: %s{n} %s{t})" })
+ | _ -> None)
+ | _ -> []
diff --git a/Program.fs b/Program.fs
index 5d0e64c..8c93bd8 100644
--- a/Program.fs
+++ b/Program.fs
@@ -48,6 +48,10 @@ let private str (node: JsonNode) (path: string list) =
/// follow the buffer.
let private texts = Collections.Generic.Dictionary()
+/// Whether the client takes `workspace/inlayHint/refresh`, as it says when it
+/// starts.
+let mutable private refreshesHints = false
+
let private publish (uri: string) =
let buffers =
texts |> Seq.map (fun kv -> IO.Path.GetFullPath(uriToPath kv.Key), kv.Value) |> Map.ofSeq
@@ -74,6 +78,11 @@ let private publish (uri: string) =
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
+
/// 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()
@@ -161,19 +170,34 @@ let private describe (uri: string) (name: string) : string option =
| Some found -> Some(Hover.text found)
| 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
+
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) -> answer (Hover.local b (Symbols.sliceOf (textOf uri) b.Shown)) at
+ | Some(b, at) -> answer (Hover.local b (localType uri b at) (Symbols.sliceOf (textOf uri) b.Shown)) at
| None ->
match Symbols.nameAt (uriToPath uri) (textOf uri) (line + 1) character with
| None -> null
| 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 -> null
- | Some text -> answer text at
+ | 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,
@@ -225,7 +249,7 @@ let private completionAt (uri: string) (line: int) (character: int) : JsonNode =
let localDoc =
locals
- |> List.map (fun b -> b.Name, Hover.local b (Symbols.sliceOf text b.Shown))
+ |> 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 =
@@ -251,6 +275,26 @@ let private completionAt (uri: string) (line: int) (character: int) : 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"]
@@ -273,8 +317,9 @@ let private capabilities () : JsonNode =
"documentSymbolProvider": true,
"definitionProvider": true,
"hoverProvider": true,
+ "inlayHintProvider": true,
"completionProvider": { "resolveProvider": true, "triggerCharacters": [ "(" ] } },
- "serverInfo": { "name": "bjolang-lsp", "version": "0.4.0" } }
+ "serverInfo": { "name": "bjolang-lsp", "version": "0.5.0" } }
"""
[]
@@ -345,7 +390,15 @@ let main _ =
| _ ->
try
match methodName with
- | "initialize" -> Rpc.respond id (capabilities ())
+ | "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()
+
+ Rpc.respond id (capabilities ())
| "shutdown" ->
shutdownAsked <- true
Rpc.respond id null
@@ -385,6 +438,12 @@ let main _ =
let character = position["character"].GetValue()
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)
| "textDocument/completion" ->
let position = message["params"]["position"]
@@ -393,6 +452,17 @@ let main _ =
Rpc.respond id (uri () |> Option.map (fun u -> completionAt u line character) |> Option.defaultValue null)
| "completionItem/resolve" -> Rpc.respond id (resolve message["params"])
+ // 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()
+ let last = endsAt["line"].GetValue()
+
+ 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
@@ -422,6 +492,8 @@ let main _ =
|> Option.defaultValue null
Rpc.respond id answer
+ // 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.
diff --git a/README.md b/README.md
index 71a46f6..308f0c1 100644
--- a/README.md
+++ b/README.md
@@ -26,7 +26,8 @@ packages (see "Projects"), and it does five things:
`field` line. A builtin, which the compiler defines rather than a module,
shows its type and its doc from the prelude's docs. A local name shows
its binding as written, a typed parameter with its type, and what binds
- it.
+ it. A hover also shows the types the compiler inferred (see "Inferred
+ types").
- Completion (`textDocument/completion`): the local names in scope, then
the top-level names of the file and of every module it sees, the
builtins, and the special forms, each name once and the nearest first. An
@@ -49,6 +50,34 @@ reader: no macro is expanded and nothing is type checked, so they answer on
every request. A form being typed is read as if it were closed; text that
does not read even so leaves the last outline in place.
+## Inferred types
+
+A check keeps what the compiler inferred: the compiler hands each program it
+type checked to `Inference.observe`, and `Types.fs` reads the names in it
+with their types. A hover then shows
+
+- for a local name, `(: name type)` above its binding: a parameter written
+ without a type, a `let` binding, a `fun`'s parameter, a pattern's
+ variable, a loop variable, a local `defun`;
+- for a use of a generic function, the type it has there, under "At this
+ use": `list-map` at the types of the list it is given.
+
+The types are those of the last check. A hover runs a check that is due
+first, so that they are of the text as it stands. A declaration that does
+not check has no types until it does; the others keep theirs.
+
+Inlay hints (`textDocument/inlayHint`) show the same types in the text,
+after each local name where it is bound, where no type is written:
+`(let ((n: int (length xs))) ...)`. A top-level function's parameters have
+none, as its signature above it says their types. A long type is cut short,
+and its tooltip is the whole of it.
+
+An editor asks for hints as the text changes, before the check of the
+change has run. The hints before the first change since the last check are
+where they were and are sent; the ones after it wait for the check. When it
+has run, the server asks the editor to ask again
+(`workspace/inlayHint/refresh`), if the editor says it can be asked.
+
Local names are the ones the parser's own forms bind: parameters of a
`defun`, `fun` and the other `def…` heads, `let`, `let*`, `letrec`,
`let/mono`, named `let` and `with-open` bindings, `with-return`, `match`
@@ -119,6 +148,12 @@ would:
(add-hook 'bjo-mode-hook #'lsp)
```
+lsp-mode shows inlay hints only when asked to:
+
+```elisp
+(setq lsp-inlay-hint-enable t)
+```
+
`emacs/bjolang-dape.el` debugs a program with `dape` and
[netcoredbg](https://github.com/Samsung/netcoredbg/releases):
@@ -157,8 +192,8 @@ With eglot instead:
location in the message.
- Hover for a special form (`record-ref`, `loop`, `match`), which has no
definition to find and no doc.
-- Types that are inferred rather than written. A hover shows the
- declaration if there is one, and nothing about a name without it.
+- The type of an expression that is not a name, and of a local `defun`'s
+ name where it is defined, which is not seen as a local there.
- Completion of record fields after `record-ref`, of module paths in an
`import`, or of keyword arguments. A string that began on an earlier line
is not seen as one, so a multi-line string gets completions.
diff --git a/Rpc.fs b/Rpc.fs
index 4090b3f..5ef1580 100644
--- a/Rpc.fs
+++ b/Rpc.fs
@@ -80,6 +80,22 @@ let respondError (id: JsonNode) (code: int) (message: string) =
let notify (methodName: string) (parameters: JsonNode) =
write (JsonObject(dict [ "method", JsonValue.Create methodName :> JsonNode; "params", parameters ]))
+let mutable private nextRequest = 0
+
+/// A request to the client. Its answer arrives as a message with no method,
+/// which the server reads and passes over: nothing it asks for needs one.
+let request (methodName: string) (parameters: JsonNode) =
+ nextRequest <- nextRequest + 1
+
+ write (
+ JsonObject(
+ dict
+ [ "id", JsonValue.Create $"bjolang-%d{nextRequest}" :> JsonNode
+ "method", JsonValue.Create methodName
+ "params", parameters ]
+ )
+ )
+
/// A line for the server's log, which is stderr: the client shows it, and it
/// never mixes with the protocol on stdout.
let log (message: string) =
diff --git a/Types.fs b/Types.fs
new file mode 100644
index 0000000..ad29ec6
--- /dev/null
+++ b/Types.fs
@@ -0,0 +1,214 @@
+/// The types the compiler inferred for a file, from its last check.
+///
+/// The compiler hands each program it checked to `Inference.observe`, and the
+/// names in it are read off with their types: each use of a name, at the type
+/// it has there, and each binding, at the type it binds. A declaration that
+/// failed to check has no types, so a name in it has none until it checks.
+module BjolangLsp.Types
+
+open System
+open Bjolang
+open Bjolang.Lexer
+open Bjolang.TypedAST
+
+/// A name as an expression, and the type it has there. `Generic` when it is
+/// a generic binding, which this use instantiated.
+type Use =
+ { Name: string
+ Range: Range
+ Type: string
+ Generic: bool }
+
+/// A name a form binds, and the type it binds it at. `Within` is the binding
+/// form: where the name is written in it is the reader's business, and the
+/// form holds it.
+type Bound =
+ { Name: string
+ Within: Range
+ Type: string }
+
+type Index = { Uses: Use list; Bounds: Bound list }
+
+let private empty = { Uses = []; Bounds = [] }
+
+/// A name the compiler invented in place of one the program wrote: `x__3`,
+/// a generated suspending copy `f__bjo`, and `unused__4` for `_`.
+let private invented (name: string) =
+ name.EndsWith "__bjo" || name.StartsWith "unused__" || name.StartsWith "#"
+
+/// What the program wrote: a renamed binder without its `__12`.
+let private written (name: string) =
+ Text.RegularExpressions.Regex.Replace(name, @"__\d+$", "")
+
+/// Reads `decls` into an index of the names in `file`, showing each type
+/// with `env`'s registry: an associated type at a known implementor shows as
+/// what it is there.
+let private read (env: Env) (file: string) (decls: TDecl list) : Index =
+ let uses = ResizeArray