From ce426b94df52491bc505a264435171f5bf5ccd54833d06086b797da589deb960 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20Bj=C3=B6rnstam?= Date: Wed, 25 Nov 2026 08:01:34 +0100 Subject: [PATCH] Signature help, formatting, and a fix that writes a missing signature - textDocument/signatureHelp: the function whose call the cursor is in, with the parameter that is being written marked. A definition shows its head as written; an import, a trait's method and a builtin show their type. It reads tokens as far as the cursor, so a call that is not closed has help. - textDocument/formatting: the whole text as bjo fmt lays it out. The server runs bjo -q fmt - on the buffer's text. - A quick fix at a function with no signature writes the one its body gives it, on a line above the definition (CheckDecl.observeMissingSignature, in the compiler). - The server says version 0.8.0. Needs the compiler at its commit "CheckDecl.observeMissingSignature". Co-Authored-By: Claude Fable 5.2 --- Actions.fs | 17 ++- BjolangLsp.fsproj | 2 + Fixes.fs | 20 ++-- Format.fs | 67 ++++++++++++ Program.fs | 111 ++++++++++++++++++- README.md | 34 +++++- SignatureHelp.fs | 266 ++++++++++++++++++++++++++++++++++++++++++++++ test/smoke.py | 189 ++++++++++++++++++++++++++++++++ 8 files changed, 695 insertions(+), 11 deletions(-) create mode 100644 Format.fs create mode 100644 SignatureHelp.fs diff --git a/Actions.fs b/Actions.fs index 431fb44..9780893 100644 --- a/Actions.fs +++ b/Actions.fs @@ -7,6 +7,8 @@ /// - Fill a hole with a binding in scope that fits it, a constructor of its /// type with holes for what it takes, or, for a function type, a `fun` /// with a hole for its body. +/// - Write the signature of a function that has none, on a line of its own +/// above the definition: the type that its body gives it. /// /// What is offered is from the file's last check (`Fixes`), and only for text /// that is still what was checked. @@ -95,4 +97,17 @@ let at (path: string) (text: string) (first: Position) (last: Position) : Action |> List.distinct |> List.map (fun filler -> { Title = $"Fill with %s{filler}"; Range = h.Range; NewText = filler })) - clauses @ fills + // Offered on the definition's first line, where the diagnostic is, and + // not in its body. + let signatures = + facts.Signatures + |> List.filter (fun s -> + touches s.Range first last + && first.Line = s.Range.Start.Line + && (Symbols.sliceOf text s.Range).StartsWith "(") + |> List.map (fun s -> + { Title = $"Write the signature %s{s.Signature}" + Range = { s.Range with End = s.Range.Start } + NewText = s.Signature + "\n" + String.replicate s.Range.Start.Column " " }) + + clauses @ fills @ signatures diff --git a/BjolangLsp.fsproj b/BjolangLsp.fsproj index acade4f..c3132e0 100644 --- a/BjolangLsp.fsproj +++ b/BjolangLsp.fsproj @@ -38,6 +38,8 @@ + + diff --git a/Fixes.fs b/Fixes.fs index 83c63bb..2b423f3 100644 --- a/Fixes.fs +++ b/Fixes.fs @@ -1,7 +1,10 @@ /// What the compiler offers to write, from a file's last check: the clauses a -/// match lacks, and what could fill a hole. The compiler hands them to -/// `Exhaustiveness.observe` and `Holes.observe` as it refuses the code, so -/// they cost nothing beyond the check. +/// match lacks, what could fill a hole, and the signature of a function that +/// has none. The compiler hands them to `Exhaustiveness.observe`, +/// `Holes.observe` and `CheckDecl.observeMissingSignature` as it refuses the +/// code. The first two cost nothing beyond the check. For the third, the +/// compiler checks the body of each function that has no signature, which it +/// does not do with no observer. module BjolangLsp.Fixes open System.IO @@ -10,9 +13,10 @@ open Bjolang.Lexer type Facts = { Missing: Exhaustiveness.MissingClauses list - Holes: Holes.Fillers list } + Holes: Holes.Fillers list + Signatures: CheckDecl.MissingSignature list } -let private none = { Missing = []; Holes = [] } +let private none = { Missing = []; Holes = []; Signatures = [] } let private byFile = System.Collections.Generic.Dictionary() @@ -23,18 +27,22 @@ let recording (path: string) (check: unit -> 'a) : 'a = let inFile (r: Range) = r.File <> "" && Path.GetFullPath r.File = full let missing = ResizeArray() let holes = ResizeArray() + let signatures = ResizeArray() Exhaustiveness.observe <- Some(fun m -> if inFile m.Range then missing.Add m) Holes.observe <- Some(fun h -> if inFile h.Range then holes.Add h) + CheckDecl.observeMissingSignature <- Some(fun s -> if inFile s.Range then signatures.Add s) try check () finally Exhaustiveness.observe <- None Holes.observe <- None + CheckDecl.observeMissingSignature <- None byFile[full] <- { Missing = missing |> Seq.distinctBy (fun m -> m.Range) |> List.ofSeq - Holes = holes |> Seq.distinctBy (fun h -> h.Range) |> List.ofSeq } + Holes = holes |> Seq.distinctBy (fun h -> h.Range) |> List.ofSeq + Signatures = signatures |> Seq.distinctBy (fun s -> s.Range) |> List.ofSeq } /// The facts of `path`'s last check. let ofFile (path: string) : Facts = diff --git a/Format.fs b/Format.fs new file mode 100644 index 0000000..e34af15 --- /dev/null +++ b/Format.fs @@ -0,0 +1,67 @@ +/// Formatting: the text of a file laid out as `bjo fmt` lays it out. +/// +/// The formatter is `bjo/format.bjo`, a Bjolang program, so the server runs +/// `bjo fmt -`, which reads the text on standard input and writes it laid out +/// on standard output. What an editor gets is then what the command line +/// writes. +module BjolangLsp.Format + +open System +open System.Diagnostics +open System.IO +open System.Text + +/// How long `bjo fmt -` may take. The first run after the compiler changed +/// builds `bjo`, which is the longest that it takes. +let private limit = TimeSpan.FromSeconds 120.0 + +/// `text` laid out, or why it cannot be: the text does not read, or `bjo` is +/// not there or failed. +/// +/// - `-q`: `bjo` then says nothing about a build of itself. +/// - Standard output and standard error are read while the process runs, so +/// that a long text does not fill a pipe and stop it. +let source (text: string) : Result = + let launcher = Path.Combine(Bjolang.Paths.root, "bjo", "bjo") + + if not (File.Exists launcher) then + Error $"There is no bjo at %s{launcher}." + else + let info = + ProcessStartInfo( + launcher, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + StandardInputEncoding = UTF8Encoding false, + StandardOutputEncoding = UTF8Encoding false, + StandardErrorEncoding = UTF8Encoding false + ) + + for argument in [ "-q"; "fmt"; "-" ] do + info.ArgumentList.Add argument + + try + use p = Process.Start info + let out = p.StandardOutput.ReadToEndAsync() + let err = p.StandardError.ReadToEndAsync() + p.StandardInput.Write text + p.StandardInput.Close() + + if not (p.WaitForExit(int limit.TotalMilliseconds)) then + try + p.Kill true + with _ -> + () + + Error "bjo fmt did not end in time." + elif p.ExitCode <> 0 then + // `bjo fmt: line 3: a ( that is never closed` + match err.Result.Trim() with + | "" -> Error $"bjo fmt failed with exit code %d{p.ExitCode}." + | why -> Error why + else + Ok out.Result + with ex -> + Error $"bjo fmt could not be run: %s{ex.Message}" diff --git a/Program.fs b/Program.fs index d9b18ac..175c166 100644 --- a/Program.fs +++ b/Program.fs @@ -515,6 +515,100 @@ let private actionsAt (uri: string) (first: Bjolang.Lexer.Position) (last: Bjola ) :> 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 = + 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 """ @@ -528,8 +622,10 @@ let private capabilities () : JsonNode = "referencesProvider": true, "documentHighlightProvider": true, "codeActionProvider": { "codeActionKinds": [ "quickfix" ] }, + "signatureHelpProvider": { "triggerCharacters": [ "(", " " ] }, + "documentFormattingProvider": true, "completionProvider": { "resolveProvider": true, "triggerCharacters": [ "(" ] } }, - "serverInfo": { "name": "bjolang-lsp", "version": "0.7.0" } } + "serverInfo": { "name": "bjolang-lsp", "version": "0.8.0" } } """ [] @@ -662,6 +758,19 @@ 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"]) + | "textDocument/signatureHelp" -> + let position = message["params"]["position"] + let line = position["line"].GetValue() + let character = position["character"].GetValue() + + 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"] diff --git a/README.md b/README.md index cb2b473..c7d07da 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,22 @@ their own below; besides those, it does these: so `string->` is one. Its doc is the hover's, sent along for a local and when the client asks for anything else (`completionItem/resolve`). Nothing is offered in a comment or a string. +- Signature help (`textDocument/signatureHelp`): the function whose call + the cursor is in, with the parameter that is being written marked. A + definition shows its head as written, `(area width height #:scale 1)`, + with its declaration and doc under it; an import of a .NET member, a + method of a trait and a builtin show their type. A keyword argument marks + its own parameter, at the keyword and at its value, and an argument past + the positional ones marks a `#:rest` parameter. The function is the + innermost form around the cursor whose head is a function the file sees, + so an argument written inside an `if` or a `let` has the help of the call + around it. It reads the text as tokens as far as the cursor, so a call + that is not closed has help. +- Formatting (`textDocument/formatting`): the whole text as `bjo fmt` lays + it out, which is as `bjo-mode` indents it. The server runs `bjo fmt -` on + the buffer's text. A text that does not read is refused, with what + `bjo fmt` says of it. The editor's tab size and other options are not + read: the layout is the one layout. And one request of its own, `bjolang/expandMacro`: the expansion of the macro call at a position, one step or all the way down, from the last check @@ -152,9 +168,10 @@ special form. ## Code actions -`textDocument/codeAction` offers two kinds of quick fix, both worked out by -the compiler while it checks and handed over through -`Exhaustiveness.observe` and `Holes.observe` (`Fixes.fs`): +`textDocument/codeAction` offers three kinds of quick fix, each worked out +by the compiler while it checks and handed over through +`Exhaustiveness.observe`, `Holes.observe` and +`CheckDecl.observeMissingSignature` (`Fixes.fs`): - At a match that does not cover every value: add the clauses it lacks, after its last clause and lined up with it, each with a hole for its @@ -168,6 +185,15 @@ the compiler while it checks and handed over through type, with holes for what it takes, `(Circle _)`, or a record with each of its fields; or, for a function type, with `(fun (x y) _)`. +- At a function of the module that has no signature, on the line its + definition starts: write the signature that its body gives it, on a line + of its own above the definition, `(: (-> int (#:prefix string) string))`. + A type variable that inference made is written `%a`, `%b`. The compiler + refuses such a function before it checks its body; for the server it + checks the body too, so a body that does not check has no signature to + offer, and a check of a file with such functions does that much more + work. + A hole in what was written is a new hole for the next check, so a fix is a 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 @@ -281,6 +307,8 @@ With eglot instead: - Hover for a special form (`record-ref`, `loop`, `match`), which has no definition to find and no doc. - The type of an expression that is not a name. +- Signature help for a local function, a constructor or a macro. +- Formatting of a part of a file (`textDocument/rangeFormatting`). - 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/SignatureHelp.fs b/SignatureHelp.fs new file mode 100644 index 0000000..4358777 --- /dev/null +++ b/SignatureHelp.fs @@ -0,0 +1,266 @@ +/// Signature help: the parameters of the function whose call the cursor is in, +/// and which of them is being written. +/// +/// It reads the text as far as the cursor as tokens, not as forms, so that a +/// call that is not closed yet, which is the usual case, has help. +module BjolangLsp.SignatureHelp + +open System +open System.Text +open System.Text.RegularExpressions +open Bjolang +open Bjolang.Lexer +open Bjolang.Ast + +/// A call around the cursor. +type Call = + { /// The symbol at the head of the form. + Head: string + /// The arguments before the one that is being written: for `#:name` + /// its name, for each other argument `None`. + Before: string option list + /// The argument that is being written, when the cursor is at the end + /// of `#:name`: that name. + Writing: string option } + +type private Frame = + { Open: Token + mutable HeadSeen: bool + mutable Head: string option + Items: ResizeArray } + +/// The calls around the end of `prefix`, the text of a file as far as the +/// cursor: the innermost first. A form whose head is not a symbol, and a +/// `[...]` or `{...}`, is not a call, and is the argument that is being +/// written of the call around it. +let calls (path: string) (prefix: string) : Call list = + let tokens = + try + Session.isolated (fun () -> Lexer.tokenize path prefix) + with _ -> + // The cursor is in a string that is not closed, or in text that + // the tokenizer refuses. + [] + + let frames = Collections.Generic.Stack() + + // Whether the last token is an argument that the cursor can be at the + // end of, and of the innermost form. + let mutable lastIsArgument = false + + let item (kind: string option) (isSymbol: string option) = + if frames.Count > 0 then + let f = frames.Peek() + + if not f.HeadSeen then + f.HeadSeen <- true + f.Head <- isSymbol + lastIsArgument <- false + else + f.Items.Add kind + lastIsArgument <- true + + for t in tokens do + match t.Token with + | LParen + | LBracket + | LBrace -> + frames.Push + { Open = t.Token + HeadSeen = false + Head = None + Items = ResizeArray() } + + lastIsArgument <- false + | RParen + | RBracket + | RBrace -> + if frames.Count > 0 then + frames.Pop() |> ignore + // A closed form is one argument of the form around it, and + // the cursor after it starts the next one. + item None None + lastIsArgument <- false + // A prefix of the form after it. + | Hash + | Quote + | SynQuote + | Comma + | CommaAt + | Spread -> () + | Keyword k -> item (Some k) None + | Symbol n -> item None (Some n) + | _ -> item None None + + // The cursor is at the end of the last token when no space is between + // them. + let atEndOfLast = + match List.tryLast tokens with + | Some t -> + let lines = prefix.Replace("\r\n", "\n").Split('\n') + lastIsArgument && t.Range.End.Line = lines.Length && t.Range.End.Column = lines[lines.Length - 1].Length + | None -> false + + frames + |> Seq.mapi (fun depth f -> + match f.Open, f.Head with + | LParen, Some head -> + let items = List.ofSeq f.Items + + // Only the innermost form has an argument that the cursor is at + // the end of. In each form around it, the form inside is the + // argument that is being written. + if depth = 0 && atEndOfLast then + let before = List.truncate (items.Length - 1) items + + Some + { Head = head + Before = before + Writing = List.last items } + else + Some + { Head = head + Before = items + Writing = None } + | _ -> None) + |> Seq.choose id + |> List.ofSeq + +/// The parameters of a function, as a label that shows them and where each +/// one is in it. +type Shape = + { Label: string + /// Each parameter: where it starts in the label and where it ends. + Parameters: (int * int) list + /// The positional parameters, as indexes of `Parameters`, in order. + Positional: int list + /// The keyword parameters, by name, as indexes of `Parameters`. + Keywords: Map + /// The `#:rest` parameter, as an index of `Parameters`. + Rest: int option } + +let private oneLine (text: string) = Regex.Replace(text.Trim(), @"\s+", " ") + +/// A shape from `parts`: the text before the parameters, each parameter as +/// its text and what it is, and the text after them. +type private Part = + | Positional of string + | Keyword of string * string + | Rest of string + +let private shape (before: string) (parts: Part list) (after: string) : Shape = + let label = StringBuilder(before) + let parameters = ResizeArray() + let positional = ResizeArray() + let mutable keywords = Map.empty + let mutable rest = None + + for part in parts do + label.Append ' ' |> ignore + let start = label.Length + + let text = + match part with + | Positional t + | Keyword(_, t) + | Rest t -> t + + label.Append text |> ignore + let index = parameters.Count + parameters.Add((start, label.Length)) + + match part with + | Positional _ -> positional.Add index + | Keyword(name, _) -> keywords <- Map.add name index keywords + | Rest _ -> rest <- Some index + + label.Append after |> ignore + + { Label = label.ToString() + Parameters = List.ofSeq parameters + Positional = List.ofSeq positional + Keywords = keywords + Rest = rest } + +/// The shape of a definition's head, `(name a (: b int) #:key default #:rest +/// more)`, with each parameter as it is written. `slice` gives the source of +/// a range. +let ofHead (slice: Range -> string) (head: SExpr) : Shape option = + match head with + | SList(SAtom { Token = Symbol name } :: items, _) -> + let text (s: SExpr) = oneLine (slice (getRange s)) + + let rec parts (items: SExpr list) = + match items with + | SAtom { Token = Lexer.Keyword "rest" } :: more :: tail -> Rest("#:rest " + text more) :: parts tail + | SAtom { Token = Lexer.Keyword k } :: fallback :: tail -> + Keyword(k, $"#:%s{k} " + text fallback) :: parts tail + | one :: tail -> Positional(text one) :: parts tail + | [] -> [] + + Some(shape ("(" + name) (parts items) ")") + | _ -> None + +/// The shape of a function type, `(-> a (#:key T) #:rest T result)`, for a +/// function that has no head to show: an import of a .NET member, a method of +/// a trait, a builtin. `None` for a type that is not a function's. +let ofType (slice: Range -> string) (name: string) (functionType: SExpr) : Shape option = + match functionType with + | SList(SAtom { Token = Symbol("->" | "-bjo->" | "-?->" as arrow) } :: items, _) when not items.IsEmpty -> + let text (s: SExpr) = oneLine (slice (getRange s)) + let result = List.last items + + let rec parts (items: SExpr list) = + match items with + | SAtom { Token = Lexer.Keyword "rest" } :: more :: tail -> Rest("#:rest " + text more) :: parts tail + | (SList(SAtom { Token = Lexer.Keyword k } :: _, _) as one) :: tail -> Keyword(k, text one) :: parts tail + | one :: tail -> Positional(text one) :: parts tail + | [] -> [] + + Some(shape $"(: %s{name} (%s{arrow}" (parts (List.truncate (items.Length - 1) items)) $" %s{text result}))") + | _ -> None + +/// The first function type in `form`, outermost first. +let rec functionTypeIn (form: SExpr) : SExpr option = + match form with + | SList(SAtom { Token = Symbol("->" | "-bjo->" | "-?->") } :: _, _) -> Some form + | SList(items, _) -> items |> List.tryPick functionTypeIn + | SAtom _ -> None + +/// The form of `forms` that has the range `r`. +let rec formAt (r: Range) (forms: SExpr list) : SExpr option = + forms + |> List.tryPick (fun form -> + let fr = getRange form + + if fr.Start = r.Start && fr.End = r.End && fr.File = r.File then + Some form + else + match form with + | SList(items, _) -> formAt r items + | SAtom _ -> None) + +/// The parameter of `shape` that `call` is writing, as an index of the +/// shape's parameters. `None` when the call has more arguments than the +/// function has parameters, or a keyword that the function does not have. +let active (shape: Shape) (call: Call) : int option = + // The arguments before: how many are positional, and the keyword whose + // value is not written yet, if the last of them is one. + let rec walk (items: string option list) (positional: int) = + match items with + | Some k :: [] -> positional, Some k + | Some _ :: _ :: tail -> walk tail positional + | None :: tail -> walk tail (positional + 1) + | [] -> positional, None + + let positional, pending = walk call.Before 0 + + match pending, call.Writing with + // The value of a keyword. + | Some k, _ -> Map.tryFind k shape.Keywords + // The keyword itself. + | None, Some k -> Map.tryFind k shape.Keywords + | None, None -> + match List.tryItem positional shape.Positional with + | Some index -> Some index + | None -> shape.Rest diff --git a/test/smoke.py b/test/smoke.py index 8560a4c..dbd2bbc 100755 --- a/test/smoke.py +++ b/test/smoke.py @@ -971,6 +971,126 @@ def ranges(server, tmp): ) +HELPED = """(import (std prelude)) + +(: (-> int int (#:scale int) (#:label string) int)) +(defun (area width height #:scale 1 #:label "a") + (* scale (* width height))) + +(: (-> int #:rest int int)) +(defun (total first #:rest more) first) + +(defun (main) + (println (int->string (area 2 3 #:scale 4))) + (println (int->string (total 1 2 3))) + (println (int->string (string-length (string-append "a" "b")))) + (println (int->string (area 2 (if #t 3 4)))) + 0) +""" + + +def helping(server, tmp): + """Signature help: the function of the call the cursor is in, and which + of its parameters is being written.""" + path = os.path.join(tmp, "helped.bjo") + uri = "file://" + path + with open(path, "w") as f: + f.write(HELPED) + found = server.diagnostics_after("textDocument/didOpen", uri, HELPED) + errors = [d for d in found if d["severity"] == 1] + expect("signature help: the file checks", errors == [], json.dumps(errors, indent=1)) + + def help_after(needle, nth=0): + at = position_of(HELPED, needle, nth, len(needle)) + return server.send("textDocument/signatureHelp", {"textDocument": {"uri": uri}, "position": at}, request=True)["result"] + + def marked(h): + """The text of the parameter that is marked, or None.""" + if not h or "activeParameter" not in h: + return None + signature = h["signatures"][0] + first, last = signature["parameters"][h["activeParameter"]]["label"] + return signature["label"][first:last] + + h = help_after("(area ") + expect( + "signature help: a definition's head as written", + h and h["signatures"][0]["label"] == '(area width height #:scale 1 #:label "a")', + h, + ) + expect("signature help: the first parameter", marked(h) == "width", h) + expect("signature help: its declaration is the documentation", + h and "(: area (-> int int (#:scale int) (#:label string) int))" in h["signatures"][0]["documentation"]["value"], h) + expect("signature help: the second parameter", marked(help_after("(area 2 ")) == "height") + expect("signature help: while an argument is written", marked(help_after("(area 2")) == "width") + expect("signature help: the value of a keyword", marked(help_after("(area 2 3 #:scale ")) == "#:scale 1") + expect("signature help: the keyword itself", marked(help_after("(area 2 3 #:scale")) == "#:scale 1") + expect("signature help: after a keyword and its value, none is marked", marked(help_after("(area 2 3 #:scale 4")) == "#:scale 1") + expect("signature help: a rest parameter", marked(help_after("(total 1 2 ")) == "#:rest more") + h = help_after('(string-append "a" ') + expect( + "signature help: the innermost call, of a function of the prelude", + h and "string-append" in h["signatures"][0]["label"] and h.get("activeParameter") == 1, + h, + ) + h = help_after("(area 2 (if #t ") + expect( + "signature help: a special form is passed over", + h and h["signatures"][0]["label"].startswith("(area ") and marked(h) == "height", + h, + ) + h = help_after("(defun (main)") + expect("signature help: none outside a call", h is None, h) + + +UNFORMATTED = """(import (std prelude)) + +(defun (main) +(println "a") + 0) +""" + +FORMATTED = """(import (std prelude)) + +(defun (main) + (println "a") + 0) +""" + + +def formatting(server, tmp): + """Formatting: the whole text, as `bjo fmt` lays it out.""" + path = os.path.join(tmp, "formatted.bjo") + uri = "file://" + path + with open(path, "w") as f: + f.write(UNFORMATTED) + server.diagnostics_after("textDocument/didOpen", uri, UNFORMATTED) + + def formatted(): + return server.send( + "textDocument/formatting", + {"textDocument": {"uri": uri}, "options": {"tabSize": 2, "insertSpaces": True}}, + request=True, + ) + + answer = formatted() + edits = answer.get("result") + expect("formatting: one edit", edits is not None and len(edits) == 1, answer) + if edits: + expect("formatting: of the whole text", edits[0]["range"] == {"start": {"line": 0, "character": 0}, "end": {"line": 5, "character": 0}}, edits) + expect("formatting: as bjo fmt lays it out", edits[0]["newText"] == FORMATTED, edits[0]["newText"]) + + server.change(uri, FORMATTED, 2) + server.next_diagnostics(uri) + answer = formatted() + expect("formatting: no edit for a text that is laid out", answer.get("result") == [], answer) + + server.change(uri, "(defun (main)\n", 3) + server.next_diagnostics(uri) + answer = formatted() + expect("formatting: a text that does not read is refused, with why", "never closed" in answer.get("error", {}).get("message", ""), answer) + + def fields(server, tmp): path = os.path.join(tmp, "fields.bjo") uri = "file://" + path @@ -1279,6 +1399,29 @@ def applied(text, edits): return text +UNSIGNED = """(import (std prelude)) + +(defun (double n) + (* n 2)) + +(defun (label n #:prefix "n = ") + (str prefix (int->string n))) + +(defun (pick first #:rest others) + (if (> (array-length others) 0) (array-ref others 0) first)) + + (defun (shout text) + (string-upcase text)) + +(defun (broken n) + (string-length n 1 2 3)) + +(defun (main) + (println (int->string (double 2))) + 0) +""" + + def acting(server, tmp): def open_(name, text): path = os.path.join(tmp, name) @@ -1355,6 +1498,50 @@ def acting(server, tmp): " (x #:when (some? x) 1)\n (None _)\n ((Some _) _)))" in fixed, fixed) server.diagnostics_after("textDocument/didClose", uri) + # A function with no signature is offered the one its body gives it. + uri, found = open_("unsigned.bjo", UNSIGNED) + expect("actions: each function with no signature is reported", + len([d for d in found if "requires a type signature" in d["message"]]) == 5, [d["message"] for d in found]) + + def signature_of(needle): + found = actions(uri, UNSIGNED, needle, 1) + titles = [a["title"] for a in found if a["title"].startswith("Write the signature ")] + return titles[0][len("Write the signature "):] if titles else None, found + + written, found = signature_of("(defun (double") + # `(* n 2)`: an int of any unit. The variable is one that inference + # made, and it is written as `%a`. + expect("actions: a signature with a variable that inference made", written == "(: (-> (int %a) (int %a)))", written) + fixed = applied(UNSIGNED, edit_of(found, "Write the signature " + (written or ""), uri) or []) + expect("actions: the signature goes on a line above the definition", + "\n(: (-> (int %a) (int %a)))\n(defun (double n)\n" in fixed, fixed) + written, _ = signature_of("(defun (label") + expect("actions: a keyword parameter in a signature", written == "(: (-> int (#:prefix string) string))", written) + written, _ = signature_of("(defun (pick") + expect("actions: a rest parameter in a signature", written == "(: (-> %a #:rest %a %a))", written) + written, found = signature_of("(defun (shout") + fixed = applied(UNSIGNED, edit_of(found, "Write the signature " + (written or ""), uri) or []) + expect("actions: an indented definition gets its signature at its column", + "\n (: (-> string string))\n (defun (shout text)\n" in fixed, fixed) + written, _ = signature_of("(defun (broken") + expect("actions: a body that does not check gives no signature", written is None, written) + _, found = signature_of("(* n 2)") + expect("actions: the signature is not offered in the body", found == [], found) + + # With the signatures written, the file has only the error it had. + fixed = UNSIGNED + edits = [] + for needle in ["(defun (double", "(defun (label", "(defun (pick", "(defun (shout"]: + written, found = signature_of(needle) + edits += edit_of(found, "Write the signature " + (written or ""), uri) or [] + fixed = applied(UNSIGNED, edits) + server.change(uri, fixed, 2) + after = server.next_diagnostics(uri) + expect("actions: with the signatures written, those functions check", + len([d for d in after if "requires a type signature" in d["message"]]) == 1, + [d["message"].splitlines()[0] for d in after]) + server.diagnostics_after("textDocument/didClose", uri) + CHAIN_MACROS = """;; Two macros, one expanding to the other. (import (std syntax-match)) @@ -1575,6 +1762,8 @@ with tempfile.TemporaryDirectory() as tmp: inferred(server, tmp) fields(server, tmp) ranges(server, tmp) + helping(server, tmp) + formatting(server, tmp) renaming(server, tmp) referencing(server, tmp) acting(server, tmp)