diff --git a/Check.fs b/Check.fs index 1fc5a76..c4a3a6c 100644 --- a/Check.fs +++ b/Check.fs @@ -16,7 +16,12 @@ type Found = EndLine: int EndColumn: int IsError: bool - Message: string } + Message: string + /// For a diagnostic in another file, such as an imported module: where + /// it is there. The diagnostic itself is then at the top of the file + /// that was checked, and the client gets this as related information, + /// which an editor shows as a place to go to. + Elsewhere: Lexer.Range option } /// `at file.bjo:12:3`, as `Lexer.formatPos` and `Lexer.formatAt` write a /// location into a message, the column counted from 1, or `at file.bjo:12`. @@ -125,6 +130,11 @@ let private formAt (text: string) (line: int) (column: int) = /// Where a diagnostic is, if it is in `file`. Anywhere else, such as in an /// imported module, it is `None`, and the caller puts it at the top of `file` /// with the location left in the message. +/// +/// The compiler's range of the diagnostic is used where it has one +/// (`Diagnostics.rangeOf`): it has the end, which the location in the message +/// does not. A location with no range behind it, such as the tokenizer's, is +/// read from the message, and the form that starts there is marked. let private placeIn (text: string option) (file: string) (d: Diagnostics.Diagnostic) = let markFrom (line: int) (column: int) = text |> Option.bind (fun t -> formAt t line column) @@ -137,7 +147,7 @@ let private placeIn (text: string option) (file: string) (d: Diagnostics.Diagnos else other = Path.GetFileName file - match d.Where with + match Diagnostics.rangeOf d with | Some r when sameFile r.File -> // The lexer's lines are 1-based and its columns 0-based, as LSP's are. let line = max 0 (r.Start.Line - 1) @@ -187,7 +197,8 @@ let private found (text: string option) (file: string) (d: Diagnostics.Diagnosti EndLine = p.EndLine EndColumn = p.EndColumn IsError = isError - Message = withoutLocations d.Message } + Message = withoutLocations d.Message + Elsewhere = None } | None -> let where = match d.Where with @@ -196,12 +207,18 @@ let private found (text: string option) (file: string) (d: Diagnostics.Diagnosti let p = wholeLine 0 + // A range of another file, with a path that a client can open. + let elsewhere = + Diagnostics.rangeOf d + |> Option.filter (fun r -> Path.IsPathRooted r.File && Path.GetFullPath r.File <> Path.GetFullPath file) + { Line = p.Line Column = p.Column EndLine = p.EndLine EndColumn = p.EndColumn IsError = isError - Message = d.Message + where } + Message = d.Message + where + Elsewhere = elsewhere } let private options: Build.Options = { Build.dependencyOptions with IsLibrary = false; Check = true } @@ -260,7 +277,8 @@ let file (buffers: Map) (path: string) : Found list = EndLine = 1 EndColumn = 0 IsError = true - Message = message } ] + Message = message + Elsewhere = None } ] else collected @@ -269,17 +287,43 @@ let publishParams (uri: string) (found: Found list) : JsonNode = let position (line: int) (character: int) = JsonObject(dict [ "line", JsonValue.Create line :> JsonNode; "character", JsonValue.Create character ]) + let range (startLine: int) (startColumn: int) (endLine: int) (endColumn: int) = + JsonObject(dict [ "start", position startLine startColumn :> JsonNode; "end", position endLine endColumn ]) + let diagnostic (f: Found) = - JsonObject( - dict - [ "range", - JsonObject(dict [ "start", position f.Line f.Column :> JsonNode; "end", position f.EndLine f.EndColumn ]) - :> JsonNode - "severity", JsonValue.Create(if f.IsError then 1 else 2) - "source", JsonValue.Create "bjolang" - "message", JsonValue.Create f.Message ] - ) - :> JsonNode + let node = + JsonObject( + dict + [ "range", range f.Line f.Column f.EndLine f.EndColumn :> JsonNode + "severity", JsonValue.Create(if f.IsError then 1 else 2) + "source", JsonValue.Create "bjolang" + "message", JsonValue.Create f.Message ] + ) + + match f.Elsewhere with + | Some r -> + // The lexer's lines are 1-based and its columns 0-based. + let line = max 0 (r.Start.Line - 1) + let endLine = max line (r.End.Line - 1) + let endColumn = if endLine = line then max (r.Start.Column + 1) r.End.Column else r.End.Column + + node["relatedInformation"] <- + JsonArray( + JsonObject( + dict + [ "location", + JsonObject( + dict + [ "uri", JsonValue.Create(Uri(r.File).AbsoluteUri) :> JsonNode + "range", range line r.Start.Column endLine endColumn ] + ) + :> JsonNode + "message", JsonValue.Create "The compiler found it here." ] + ) + ) + | None -> () + + node :> JsonNode JsonObject( dict diff --git a/Program.fs b/Program.fs index 8e510e1..d9b18ac 100644 --- a/Program.fs +++ b/Program.fs @@ -66,7 +66,8 @@ let private publish (uri: string) = EndLine = 1 EndColumn = 0 IsError = false - Message = message } ] + Message = message + Elsewhere = None } ] | None -> [] let found = diff --git a/README.md b/README.md index c90bb79..cb2b473 100644 --- a/README.md +++ b/README.md @@ -9,9 +9,15 @@ their own below; besides those, it does these: It checks the editor's text, saved or not: when a file is opened or saved, and 400 ms after typing pauses. Every open file is read from its buffer, so an unsaved include or `.bjodoc` counts too. A diagnostic marks - the form at the line and column the compiler names: an atom or a string - whole, a bracketed form to its closing bracket, and one over several lines - as far as its head, `(defun` or `(match`. + the range the compiler gives for it, from its start to its end + (`Diagnostics.rangeOf`): a quoted list, an array literal or an + interpolated string whole. A range over several lines is marked as far as + its head, `(defun` or `(match`, so that an error does not mark a whole + definition. Where the compiler has a line and a column only, as for an + error of the tokenizer, the form that starts there is marked. A + diagnostic in another file, an included or an imported one, is on the + first line of the file that was checked, with its place in the other file + as related information, which an editor shows as a link. - An outline (`textDocument/documentSymbol`): the file's top-level definitions, with a type's constructors or fields, a trait's methods and an `impl`'s functions under them. A `def` or `def*` of a pattern gives the @@ -178,8 +184,8 @@ dotnet build -c Release test/smoke.py ``` -The server is `bin/Release/net10.0/BjolangLsp.dll`, started as -`dotnet bin/Release/net10.0/BjolangLsp.dll`. It talks LSP on stdin and +The server is `bin/Release/net11.0/BjolangLsp.dll`, started as +`dotnet bin/Release/net11.0/BjolangLsp.dll`. It talks LSP on stdin and stdout, and logs to stderr. ## Projects @@ -224,7 +230,7 @@ would: (lsp-register-client (make-lsp-client :new-connection (lsp-stdio-connection - '("dotnet" "/home/linis/Programmering/BjolangLsp/bin/Release/net10.0/BjolangLsp.dll")) + '("dotnet" "/home/linis/Programmering/BjolangLsp/bin/Release/net11.0/BjolangLsp.dll")) :activation-fn (lsp-activate-on "bjolang") :server-id 'bjolang-lsp))) @@ -254,14 +260,12 @@ With eglot instead: ```elisp (add-to-list 'eglot-server-programs - '(bjo-mode . ("dotnet" "/home/linis/Programmering/BjolangLsp/bin/Release/net10.0/BjolangLsp.dll"))) + '(bjo-mode . ("dotnet" "/home/linis/Programmering/BjolangLsp/bin/Release/net11.0/BjolangLsp.dll"))) ``` ## What it does not do yet -- Exact ends. The compiler says where a diagnostic starts, and the form that - starts there is marked, as far as its head when it spans several lines. - That is the form the message is about in most cases, not in all. +- A range over several lines is marked as far as its head only. - A check of a large file waits for the requests before it, and they for it: everything that touches the compiler runs on one thread, because the compiler's state is global. @@ -270,9 +274,10 @@ With eglot instead: - Which definition. A name defined in two imported modules goes to the nearer one, which is not always the one the compiler would pick, and a module the file does not export from is searched like one it does. -- Errors in another file. A diagnostic located in an imported or included - file is shown on the first line of the file being checked, with its - location in the message. +- Diagnostics on another file. A diagnostic located in an imported or + included file is on the first line of the file being checked, and links to + its place. It is not published for the other file itself: that file's own + check, when it is open, would replace it. - 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. diff --git a/test/smoke.py b/test/smoke.py index 2871559..8560a4c 100755 --- a/test/smoke.py +++ b/test/smoke.py @@ -13,7 +13,7 @@ import sys import tempfile ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -SERVER = os.path.join(ROOT, "bin", "Release", "net10.0", "BjolangLsp.dll") +SERVER = os.path.join(ROOT, "bin", "Release", "net11.0", "BjolangLsp.dll") def frame(message): @@ -219,7 +219,8 @@ def symbols_and_definitions(server, tmp): d, ) d = definition(SYMBOLS, "(list-map") - expect("a name from the prelude", d and d["uri"].endswith("/lib/std/prelude.bjo"), d) + # The prelude's definitions are in (std prelude core), which it re-exports. + expect("a name from the prelude", d and d["uri"].endswith("/lib/std/prelude/core.bjo"), d) # `n` is a parameter: it goes to where the parameter is written. d = definition(SYMBOLS, "(* 2 n)", 5) expect( @@ -879,6 +880,97 @@ FIELDS = """(type (: Leg (Record (: distance double) (: name string)))) """ +# Each function has one mistake, at a form that the text alone does not show +# the end of. +RANGES = """(import (std prelude)) + +(: (-> int int)) +(defun (takes-int n) n) + +(: (-> int)) +(defun (quoted) + (takes-int '(1 2))) + +(: (-> int)) +(defun (array) + (takes-int #[1 2 3])) + +(: (-> int)) +(defun (interpolated) + (takes-int #"a ${(int->string 1)} b")) + +(: (-> (Option int) int)) +(defun (pattern o) + (match o + ((Some "x") 1) + (_ 0))) + +(: (-> int string)) +(defun (returned n) + (println "working") + (+ n 1)) + +(defun (main) 0) +""" + +INCLUDED = """(: (-> int string)) +(defun (from-include n) + (+ n 1)) +""" + +INCLUDES = """(import (std prelude)) +(include "ranges-included.bjo") + +(defun (main) (println (from-include 1)) 0) +""" + + +def ranges(server, tmp): + """A diagnostic is marked from where the compiler's range starts to where + it ends, and one in another file names the place there.""" + path = os.path.join(tmp, "ranges.bjo") + uri = "file://" + path + with open(path, "w") as f: + f.write(RANGES) + found = server.diagnostics_after("textDocument/didOpen", uri, RANGES) + errors = [d for d in found if d["severity"] == 1] + + def marked(needle, length=None): + at = position_of(RANGES, needle, 0, 0) + end = {"line": at["line"], "character": at["character"] + (length or len(needle))} + return any(d["range"]["start"] == at and d["range"]["end"] == end for d in errors) + + detail = json.dumps([d["range"] for d in errors]) + expect("ranges: a quoted list is marked whole", marked("'(1 2)"), detail) + expect("ranges: an array literal is marked whole", marked("#[1 2 3]"), detail) + expect("ranges: an interpolated string is marked whole", marked('#"a ${(int->string 1)} b"'), detail) + expect("ranges: a pattern is marked, not its match", marked('"x"'), detail) + expect("ranges: what a function returns is marked at its last form", marked("(+ n 1))", 7), detail) + + included = os.path.join(tmp, "ranges-included.bjo") + with open(included, "w") as f: + f.write(INCLUDED) + path = os.path.join(tmp, "ranges-includes.bjo") + uri = "file://" + path + with open(path, "w") as f: + f.write(INCLUDES) + found = server.diagnostics_after("textDocument/didOpen", uri, INCLUDES) + errors = [d for d in found if d["severity"] == 1] + related = [r for d in errors for r in d.get("relatedInformation", [])] + detail = json.dumps(errors, indent=1) + expect("ranges: an error of an included file is on the first line", any(d["range"]["start"]["line"] == 0 for d in errors), detail) + expect( + "ranges: and names the place in that file", + any( + r["location"]["uri"].endswith("/ranges-included.bjo") + and r["location"]["range"]["start"] == {"line": 2, "character": 2} + and r["location"]["range"]["end"] == {"line": 2, "character": 9} + for r in related + ), + detail, + ) + + def fields(server, tmp): path = os.path.join(tmp, "fields.bjo") uri = "file://" + path @@ -1014,7 +1106,7 @@ def renaming(server, tmp): ("a binding the new name would take a use from", "((n (helper", 2, "xs", "'xs' is bound at"), ("a use of the new name the renamed binding would take", "((n (helper", 2, "count", "'count' is used at"), ("an exported name", "(defun (area w", 8, "size", "is exported at"), - ("a name defined elsewhere", "(length xs)", 1, "len", "is defined in prelude.bjo"), + ("a name defined elsewhere", "(length xs)", 1, "len", "is defined in core.bjo"), ("a keyword parameter", "(str greeting", 5, "hi", "keyword parameter"), ("main", "(defun (main)", 8, "start", "entry point"), ("a name of a definition the module sees", "(defun (helper x)", 8, "length", "is already defined"), @@ -1482,6 +1574,7 @@ with tempfile.TemporaryDirectory() as tmp: declarations(server, tmp) inferred(server, tmp) fields(server, tmp) + ranges(server, tmp) renaming(server, tmp) referencing(server, tmp) acting(server, tmp)