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() + let bounds = ResizeArray() + let inFile (r: Range) = r.File <> "" && IO.Path.GetFullPath r.File = file + + let show (t: HMType) = + let settled = + try + Unification.prune env.Registry t + with _ -> + t + + DotNetInterop.showType settled + + let bind (name: string) (within: Range) (t: HMType) = + if inFile within && not (invented name) then + bounds.Add + { Name = written name + Within = within + Type = show t } + + let rec pattern (p: TypedPattern) = + match p.Node with + | TPIdent n -> bind n p.Range p.Type + | TPAs(inner, n) -> + bind n p.Range p.Type + pattern inner + | TPList(ps, rest) + | TPVec(ps, rest) + | TPArray(ps, rest) -> + List.iter pattern ps + Option.iter pattern rest + | TPTuple ps + | TPConstruct(_, ps) + | TPOr ps + | TPAnd ps -> List.iter pattern ps + | TPRecord(_, fields) -> fields |> List.iter (snd >> pattern) + | TPApp(_, inner) -> pattern inner + | _ -> () + + let parameters (names: string list) (t: HMType) (within: Range) = + match Unification.prune env.Registry t with + | TFun(args, _, _) when args.Length = names.Length -> List.iter2 (fun n a -> bind n within a) names args + | _ -> () + + let node () (e: TypedExpr) = + match e.Node with + | TIdent(name, tArgs) when inFile e.Range && not (invented name) -> + uses.Add + { Name = written name + Range = e.Range + Type = show e.Type + Generic = not tArgs.IsEmpty } + | TLet(name, _, _, value, _) -> bind name e.Range value.Type + | TLetMutable(name, value, _) -> bind name e.Range value.Type + | TLetRec(bindings, _) -> for (name, _, _, value) in bindings do bind name e.Range value.Type + | TLetTuple(names, value, _) -> + match Unification.prune env.Registry value.Type with + | TTuple items when items.Length = names.Length -> List.iter2 (fun n t -> bind n e.Range t) names items + | _ -> () + | TLambda(names, _) -> parameters names e.Type e.Range + | TMatch(_, clauses) -> for c in clauses do pattern c.Pattern + | TDefMatch(binder, _, _, arms) -> + pattern binder + for a in arms do pattern a.Pattern + | _ -> () + + let expr (e: TypedExpr) = TypeVisitor.foldExpr node () e + + let rec decl (d: TDecl) = + match d with + | TModule(_, inner, _) -> List.iter decl inner + | TImpl(_, _, _, _, _, _, methods, _) -> List.iter decl methods + | TDefun(name, _, _, _, _, _, _, _, _) when invented name -> () + | TDefun(name, _, mandatory, keywords, rest, ret, effect, body, r) -> + let restArray = rest |> Option.map (fun (_, t) -> TCon("Array", [ t ])) |> Option.toList + let funType = TFun((mandatory |> List.map snd) @ (keywords |> List.map (fun (_, t, _) -> t)) @ restArray, ret, effect) + bind name r funType + + for (n, t) in mandatory do + bind n r t + + for (n, t, value) in keywords do + bind n r t + expr value + + rest |> Option.iter (fun (n, t) -> bind n r (TCon("Array", [ t ]))) + expr body + | TDef(name, value, t, r) + | TDefMutable(name, value, t, r) -> + bind name r t + expr value + | TDefTuple(names, value, t, r) -> + match Unification.prune env.Registry t with + | TTuple items when items.Length = names.Length -> List.iter2 (fun n t -> bind n r t) names items + | _ -> () + + expr value + | TDefPattern(p, value, _, _) -> + pattern p + expr value + | _ -> () + + List.iter decl decls + { Uses = List.ofSeq uses; Bounds = List.ofSeq bounds } + +/// Each file's index, from its last check. +let private byFile = Collections.Generic.Dictionary() + +/// Each file's text as its last check read it: where an index's ranges are. +let private checkedTexts = Collections.Generic.Dictionary() + +/// The text of `path` its last check read, if it was checked. +let checkedText (path: string) : string option = + match checkedTexts.TryGetValue(IO.Path.GetFullPath path) with + | true, text -> Some text + | _ -> None + +/// Runs `check` of `text`, the text of `path`, with the compiler handing over +/// what it checked, and keeps the index of the names in `path` as the file's. +/// A check that got no further than the reader leaves the file with none. +let recording (path: string) (text: string) (check: unit -> 'a) : 'a = + let full = IO.Path.GetFullPath path + let mutable index = empty + + Inference.observe <- + Some(fun env decls -> + // The first program with names in the file is the file's: one + // checked before it is a dependency's. + if index.Uses.IsEmpty && index.Bounds.IsEmpty then + index <- read env full decls) + + try + check () + finally + Inference.observe <- None + byFile[full] <- index + checkedTexts[full] <- text + +let private holds (inner: Range) (outer: Range) = + (inner.Start.Line > outer.Start.Line + || (inner.Start.Line = outer.Start.Line && inner.Start.Column >= outer.Start.Column)) + && (inner.End.Line < outer.End.Line + || (inner.End.Line = outer.End.Line && inner.End.Column <= outer.End.Column)) + +let private size (r: Range) = (r.End.Line - r.Start.Line) * 100000 + (r.End.Column - r.Start.Column) + +let private indexOf (path: string) = + match byFile.TryGetValue(IO.Path.GetFullPath path) with + | true, index -> Some index + | _ -> None + +/// The use of `name` written at `at`, if the last check typed it. +let useAt (path: string) (name: string) (at: Range) : Use option = + indexOf path + |> Option.bind (fun index -> + index.Uses + |> List.tryFind (fun u -> u.Name = name && u.Range.Start = at.Start)) + +/// The type `name`, written at `at` in its binding form, is bound at: the +/// innermost binding of that name that holds it. +let boundAt (path: string) (name: string) (at: Range) : string option = + indexOf path + |> Option.bind (fun index -> + index.Bounds + |> List.filter (fun b -> b.Name = name && holds at b.Within) + |> List.sortBy (fun b -> size b.Within) + |> List.tryHead + |> Option.map (fun b -> b.Type)) diff --git a/test/smoke.py b/test/smoke.py index a11162e..a312da4 100755 --- a/test/smoke.py +++ b/test/smoke.py @@ -502,6 +502,124 @@ def locals_(server, tmp): server.diagnostics_after("textDocument/didClose", uri) +INFERRED = """(import (std prelude)) + +(: total (-> (List int) int)) +(defun (total xs) + (let ((pairs (list-map (fun (x) (Tuple x "s")) xs))) + (match (first pairs) + ((Some (Tuple n label)) (+ n (string-count label))) + (None (loop (:for y xs) (:acc sum (summing y)) => sum))))) + +(: lengths (-> (Vec string) (Vec int))) +(defun (lengths names) + (defun (twice s) (* 2 (string-count s))) + (vec-map twice names)) + +(: annotated (-> int int)) +(defun (annotated k) + (def (: m int) (+ k 1)) + m) +""" + +# One declaration that does not check, and one that does. +INFERRED_BROKEN = INFERRED.replace('(Tuple x "s")', '(+ x "s")') + +# The same, with what `pairs` holds changed and not saved. +INFERRED_EDITED = INFERRED.replace('(Tuple x "s")', '(Tuple x 2.5)').replace("(string-count label)", "1") + + +def inferred(server, tmp): + path = os.path.join(tmp, "inferred.bjo") + uri = "file://" + path + with open(path, "w") as f: + f.write(INFERRED) + found = server.diagnostics_after("textDocument/didOpen", uri, INFERRED) + expect("inferred: the file checks", found == [], json.dumps(found, indent=1)) + + def hover(text, needle, offset=1, nth=0): + at = position_of(text, needle, nth, offset) + h = server.send("textDocument/hover", {"textDocument": {"uri": uri}, "position": at}, request=True)["result"] + return h and h["contents"]["value"] + + cases = [ + ("a parameter without a type", "xs)\n", "(: xs (List int))"), + ("a let binding", "pairs (list-map", "(: pairs (List (Tuple int string)))"), + ("a fun's parameter, at a use", "x \"s\"", "(: x int)"), + ("a match pattern's variable", "n label)", "(: n int)"), + ("another, at a use", "label)))", "(: label string)"), + ("a loop variable", "y xs)", "(: y int)"), + ("a local defun, at a use", "twice names", "(: twice (-?-> string int))"), + ("a local defun's parameter", "s)))\n (vec-map", "(: s string)"), + ] + for name, needle, wanted in cases: + h = hover(INFERRED, needle, 0) + expect("inferred hover: " + name, h and wanted in h, h) + + h = hover(INFERRED, "(list-map") + expect( + "inferred hover: a generic function, at this use", + h and "At this use" in h and "(: list-map (-> (-> int (Tuple int string)) (List int) (List (Tuple int string))))" in h, + h, + ) + + def hints(text): + """Each hint as (the text before it on its line, its label).""" + lines = text.split("\n") + whole = {"start": {"line": 0, "character": 0}, "end": {"line": len(lines), "character": 0}} + found = server.send("textDocument/inlayHint", {"textDocument": {"uri": uri}, "range": whole}, request=True)["result"] + return [(lines[h["position"]["line"]][: h["position"]["character"]], h["label"]) for h in found] + + found = hints(INFERRED) + labels = {before.split()[-1].lstrip("("): label for before, label in found} + expect( + "inlay hints: a type after each local's binding", + labels.get("pairs") == ": (List (Tuple int string))" + and labels.get("x") == ": int" + and labels.get("n") == ": int" + and labels.get("label") == ": string" + and labels.get("y") == ": int" + and labels.get("s") == ": string", + found, + ) + expect( + "inlay hints: none for a top-level function's parameters", + "xs" not in labels and "names" not in labels and "k" not in labels, + found, + ) + expect("inlay hints: none where the type is written", "m" not in labels, found) + + # An edit not checked yet, between `y` and `s`: the hints before it + # stay, and the one after it waits for the check. + edited = INFERRED.replace("(defun (lengths names)", "(defun (lengths names)") + server.change(uri, edited, 2) + labels = {before.split()[-1].lstrip("("): label for before, label in hints(edited)} + expect( + "inlay hints: before an unchecked edit they stay, after it they wait", + labels.get("y") == ": int" and "s" not in labels, + labels, + ) + server.next_diagnostics(uri) + labels = {before.split()[-1].lstrip("("): label for before, label in hints(edited)} + expect("inlay hints: after the check, all of them", labels.get("s") == ": string", labels) + + # A type error in `total`: `lengths` still has its types, and `total`'s + # names have none rather than wrong ones. + server.change(uri, INFERRED_BROKEN, 3) + server.next_diagnostics(uri) + h = hover(INFERRED_BROKEN, "twice names", 0) + expect("inferred hover: another declaration's error leaves this one's", h and "(: twice (-?-> string int))" in h, h) + h = hover(INFERRED_BROKEN, "pairs (list-map", 0) + expect("inferred hover: a declaration that failed has none", h and "(: pairs" not in h, h) + + # Hovered straight after typing, before the check would have run: the + # hover checks first, and the types are of the text as it stands. + server.change(uri, INFERRED_EDITED, 4) + h = hover(INFERRED_EDITED, "pairs (list-map", 0) + expect("inferred hover: an unsaved edit is checked first", h and "(: pairs (List (Tuple int double)))" in h, h) + server.diagnostics_after("textDocument/didClose", uri) + + CHAIN_MACROS = """;; Two macros, one expanding to the other. (import (std syntax-match)) @@ -715,6 +833,7 @@ with tempfile.TemporaryDirectory() as tmp: documented(server, tmp) completing(server, tmp) locals_(server, tmp) + inferred(server, tmp) expanding(server, tmp) answer = server.send("shutdown", request=True)