diff --git a/Actions.fs b/Actions.fs
new file mode 100644
index 0000000..431fb44
--- /dev/null
+++ b/Actions.fs
@@ -0,0 +1,98 @@
+/// Code actions: edits the compiler has worked out, offered where the code
+/// they are for is.
+///
+/// - Add the clauses a match lacks, each with a hole for its body, after its
+/// last clause and lined up with it. The next check then says what each
+/// body has to be.
+/// - 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.
+///
+/// What is offered is from the file's last check (`Fixes`), and only for text
+/// that is still what was checked.
+module BjolangLsp.Actions
+
+open Bjolang
+open Bjolang.Lexer
+open Bjolang.Ast
+
+type Action =
+ { Title: string
+ /// The text to replace, an empty range to insert at.
+ Range: Range
+ NewText: string }
+
+let private before (a: Position) (b: Position) =
+ a.Line < b.Line || (a.Line = b.Line && a.Column < b.Column)
+
+/// Whether `r` and the span from `first` to `last` share a position, ends
+/// included, so that a cursor right after a hole is at it.
+let private touches (r: Range) (first: Position) (last: Position) =
+ not (before r.End first || before last r.Start)
+
+let private rangeOf = Ast.getRange
+
+/// The `(match ...)` form that starts where `at` does.
+let rec private matchAt (at: Position) (forms: SExpr list) : (SExpr * SExpr list * Range) option =
+ forms
+ |> List.tryPick (fun form ->
+ match form with
+ | SList(SAtom { Token = Symbol "match" } :: scrutinee :: clauses, r) when r.Start = at -> Some(scrutinee, clauses, r)
+ | SList(items, _) -> matchAt at items
+ | _ -> None)
+
+/// The parameters a `fun` of `n` of them is written with.
+let private parameterNames (n: int) =
+ match n with
+ | n when n <= 3 -> [ "x"; "y"; "z" ] |> List.truncate n
+ | n -> List.init n (fun i -> $"x%d{i + 1}")
+
+/// How many bindings that fit a hole are offered; the hole's message names
+/// the rest of them.
+let private fitsOffered = 12
+
+/// The actions for the code from `first` to `last` of `path`, whose text is
+/// `text`, as the last check left it.
+let at (path: string) (text: string) (first: Position) (last: Position) : Action list =
+ let facts = Fixes.ofFile path
+ let forms = Symbols.forms path text |> Option.defaultValue []
+
+ let clauses =
+ facts.Missing
+ |> List.filter (fun m -> touches m.Range first last)
+ |> List.choose (fun m ->
+ matchAt m.Range.Start forms
+ |> Option.map (fun (scrutinee, existing, r) ->
+ let after, column =
+ match List.tryLast existing with
+ | Some clause -> (rangeOf clause).End, (rangeOf clause).Start.Column
+ | None -> (rangeOf scrutinee).End, r.Start.Column + 2
+
+ let newText =
+ m.Patterns
+ |> List.map (fun p -> "\n" + String.replicate column " " + "(" + p + " _)")
+ |> String.concat ""
+
+ let title =
+ match m.Patterns with
+ | [ one ] -> $"Add the missing clause %s{one}"
+ | several -> $"Add the %d{several.Length} missing clauses"
+
+ { Title = title
+ Range = { r with Start = after; End = after }
+ NewText = newText }))
+
+ let fills =
+ facts.Holes
+ |> List.filter (fun h -> touches h.Range first last && (Symbols.sliceOf text h.Range).StartsWith "_")
+ |> List.collect (fun h ->
+ let functions =
+ match h.Parameters with
+ | Some n -> [ "(fun (" + String.concat " " (parameterNames n) + ") _)" ]
+ | None -> []
+
+ (List.truncate fitsOffered h.Fits @ h.Constructors @ functions)
+ |> List.distinct
+ |> List.map (fun filler -> { Title = $"Fill with %s{filler}"; Range = h.Range; NewText = filler }))
+
+ clauses @ fills
diff --git a/BjolangLsp.fsproj b/BjolangLsp.fsproj
index b8bf787..e09db93 100644
--- a/BjolangLsp.fsproj
+++ b/BjolangLsp.fsproj
@@ -28,12 +28,15 @@
+
+
+
diff --git a/Check.fs b/Check.fs
index 34ec30d..1fc5a76 100644
--- a/Check.fs
+++ b/Check.fs
@@ -232,8 +232,9 @@ let file (buffers: Map) (path: string) : Found list =
Diagnostics.captured (fun () ->
try
Expansion.recording path (fun () ->
- Types.recording path (Option.defaultValue "" text) (fun () ->
- Session.isolated (fun () -> Build.compile options path)))
+ Fixes.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)
diff --git a/Fixes.fs b/Fixes.fs
new file mode 100644
index 0000000..83c63bb
--- /dev/null
+++ b/Fixes.fs
@@ -0,0 +1,43 @@
+/// 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.
+module BjolangLsp.Fixes
+
+open System.IO
+open Bjolang
+open Bjolang.Lexer
+
+type Facts =
+ { Missing: Exhaustiveness.MissingClauses list
+ Holes: Holes.Fillers list }
+
+let private none = { Missing = []; Holes = [] }
+
+let private byFile = System.Collections.Generic.Dictionary()
+
+/// Runs `check` of `path` with the compiler handing over what it refused, and
+/// keeps what is in `path` as the file's.
+let recording (path: string) (check: unit -> 'a) : 'a =
+ let full = Path.GetFullPath path
+ let inFile (r: Range) = r.File <> "" && Path.GetFullPath r.File = full
+ let missing = ResizeArray()
+ let holes = 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)
+
+ try
+ check ()
+ finally
+ Exhaustiveness.observe <- None
+ Holes.observe <- None
+
+ byFile[full] <-
+ { Missing = missing |> Seq.distinctBy (fun m -> m.Range) |> List.ofSeq
+ Holes = holes |> Seq.distinctBy (fun h -> h.Range) |> List.ofSeq }
+
+/// The facts of `path`'s last check.
+let ofFile (path: string) : Facts =
+ match byFile.TryGetValue(Path.GetFullPath path) with
+ | true, facts -> facts
+ | _ -> none
diff --git a/Program.fs b/Program.fs
index f979884..f952dbc 100644
--- a/Program.fs
+++ b/Program.fs
@@ -417,6 +417,70 @@ let private renameAt (uri: string) (line: int) (character: int) (newName: string
Ok(JsonObject(dict [ "changes", JsonObject(dict changes) :> JsonNode ]) :> JsonNode)
+/// The uses of the name at a position, in its module, as LSP locations; the
+/// definition among them only if `withDefinition`.
+let private referencesAt (uri: string) (line: int) (character: int) (withDefinition: bool) : JsonNode =
+ let path = IO.Path.GetFullPath(uriToPath uri)
+ let uriOf (file: string) = if file = path then uri else Uri(file).AbsoluteUri
+
+ match Uses.at textOfPath path (line + 1) character with
+ | None -> null
+ | Some(_, uses) ->
+ JsonArray(
+ uses
+ |> List.filter (fun u -> withDefinition || not u.IsDefinition)
+ |> List.map (fun u ->
+ JsonObject(dict [ "uri", JsonValue.Create(uriOf u.File) :> JsonNode; "range", range u.Range ]) :> JsonNode)
+ |> Array.ofList
+ )
+ :> JsonNode
+
+/// The uses of the name at a position in this file, for the editor to mark:
+/// the definition as a write, the rest as reads.
+let private highlightsAt (uri: string) (line: int) (character: int) : JsonNode =
+ let path = IO.Path.GetFullPath(uriToPath uri)
+
+ match Uses.at textOfPath path (line + 1) character with
+ | None -> null
+ | Some(_, uses) ->
+ JsonArray(
+ uses
+ |> List.filter (fun u -> u.File = path)
+ |> List.map (fun u ->
+ JsonObject(dict [ "range", range u.Range; "kind", JsonValue.Create(if u.IsDefinition then 3 else 2) :> JsonNode ])
+ :> JsonNode)
+ |> Array.ofList
+ )
+ :> JsonNode
+
+/// The code actions for the span from `first` to `last` of a file: what its
+/// last check worked out there, if the text is still what it checked.
+let private actionsAt (uri: string) (first: Bjolang.Lexer.Position) (last: Bjolang.Lexer.Position) : JsonNode =
+ let path = IO.Path.GetFullPath(uriToPath uri)
+ let text = textOf uri
+
+ let actions =
+ match Types.checkedText path with
+ | Some checkedText when checkedText = text -> Actions.at path text first last
+ | _ -> []
+
+ JsonArray(
+ actions
+ |> List.map (fun a ->
+ let edit =
+ JsonObject(dict [ "range", range a.Range; "newText", JsonValue.Create a.NewText :> JsonNode ])
+
+ JsonObject(
+ dict
+ [ "title", JsonValue.Create a.Title :> JsonNode
+ "kind", JsonValue.Create "quickfix"
+ "edit", JsonObject(dict [ "changes", JsonObject(dict [ uri, JsonArray(edit) :> JsonNode ]) :> JsonNode ]) ]
+ )
+ :> JsonNode)
+ |> Array.ofList
+ )
+ :> JsonNode
+
let private capabilities () : JsonNode =
JsonNode.Parse
"""
@@ -427,8 +491,11 @@ let private capabilities () : JsonNode =
"hoverProvider": true,
"inlayHintProvider": true,
"renameProvider": { "prepareProvider": true },
+ "referencesProvider": true,
+ "documentHighlightProvider": true,
+ "codeActionProvider": { "codeActionKinds": [ "quickfix" ] },
"completionProvider": { "resolveProvider": true, "triggerCharacters": [ "(" ] } },
- "serverInfo": { "name": "bjolang-lsp", "version": "0.6.0" } }
+ "serverInfo": { "name": "bjolang-lsp", "version": "0.7.0" } }
"""
[]
@@ -561,6 +628,46 @@ 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/references"
+ | "textDocument/documentHighlight" ->
+ let p = message["params"]
+ let position = p["position"]
+ let line = position["line"].GetValue()
+ let character = position["character"].GetValue()
+
+ let withDefinition =
+ match p["context"] with
+ | null -> true
+ | c ->
+ match c["includeDeclaration"] with
+ | null -> true
+ | v -> v.GetValue()
+
+ let answer =
+ uri ()
+ |> Option.map (fun u ->
+ if methodName = "textDocument/references" then referencesAt u line character withDefinition
+ else highlightsAt u line character)
+ |> Option.defaultValue null
+
+ Rpc.respond id answer
+ // What is offered is from the last check, which a check
+ // that is due replaces first, as for a hover.
+ | "textDocument/codeAction" ->
+ let r = message["params"]["range"]
+
+ let position (n: JsonNode) : Bjolang.Lexer.Position =
+ { Line = n["line"].GetValue() + 1
+ Column = n["character"].GetValue() }
+
+ let answer =
+ uri ()
+ |> Option.map (fun u ->
+ if dueChecks.Remove u then publish u
+ actionsAt u (position r["start"]) (position r["end"]))
+ |> Option.defaultValue (JsonArray())
+
+ Rpc.respond id answer
// A refusal is an error answer: the client shows its
// message, which says why.
| "textDocument/prepareRename"
diff --git a/README.md b/README.md
index 48cfd5c..4eebc2d 100644
--- a/README.md
+++ b/README.md
@@ -19,6 +19,15 @@ their own below; besides those, it does these:
it is bound, the innermost binding of it; a top-level name to the file's
own definition, else one in a module it imports or includes, searched
nearest first, and then the prelude.
+- References (`textDocument/references`) and highlights
+ (`textDocument/documentHighlight`): the uses of the name at point in its
+ module, its own file and what that includes. A use is a symbol the name
+ means there, found as go to definition finds a binding, so a shadowing
+ local of the same name, quoted data and a `#'` template's own names are
+ not uses. Any name has them: a local, a top-level definition, a type or a
+ constructor, and an imported name or a builtin, where this module uses it.
+ Uses in other modules are not looked for. A highlight marks the binding
+ or definition as a write and the rest as reads.
- Hover (`textDocument/hover`) for the same names. A top-level name shows
the `(: name Type)` declaration and the definition's head as written, then
its doc from the module's `(:doc ...)` forms and `.bjodoc` files, with the
@@ -119,6 +128,29 @@ with an error the program before it did not have is refused, with the
error: `(defun (twice s) ...)` renamed to `when` makes `(twice v)` the
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`):
+
+- 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
+ body: `((Square _) _)`. They are found one missing value at a time, so
+ that together they cover what the match does not, nested cases spelled
+ out, `((Some (Square _)) _)`. A value of an integer or a char, or a vec of
+ one length, is widened to all of them; past 20 clauses a `_` takes the
+ rest.
+- At a typed hole: fill it with a binding in scope that fits it, as the
+ hole's message ranks them (the first twelve); with a constructor of its
+ 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) _)`.
+
+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
+first, as for a hover, and only of text that is still what it checked.
+
## Building
It expects the Bjolang checkout beside this one, at `../Bjolang`, and runs
diff --git a/Rename.fs b/Rename.fs
index 9b10342..8065a36 100644
--- a/Rename.fs
+++ b/Rename.fs
@@ -1,12 +1,8 @@
/// Renaming a name: a local binding, or a top-level `def` or `defun` the
/// module does not export.
///
-/// The places to rename are found as go to definition finds a name's binding
-/// (`Scope`), on the forms as the reader gives them, in the module's own file
-/// and the files it includes. What is not a reference is left: quoted data,
-/// the part of a `#'` template that is not unquoted, a type's declaration, and
-/// what the reader wrote itself, such as the `fun` of `#(...)`, which has no
-/// text of its own.
+/// The places to rename are the name's uses in the module, as `Uses` finds
+/// them.
///
/// A rename is refused rather than guessed at where it could change what the
/// program means: where the new name would capture a use of another binding,
@@ -28,49 +24,9 @@ type Plan =
{ Old: string
Edits: Edit list }
-/// A module's files: its own, and what it includes, each with its forms.
-let private moduleFiles (textOf: string -> string) (path: string) : (string * string * SExpr list) list =
- let rec go (seen: Set) (file: string) =
- let text = textOf file
- let fs = Symbols.forms file text |> Option.defaultValue []
-
- let included =
- fs
- |> List.choose (fun form ->
- match form with
- | SList([ SAtom { Token = Symbol "include" }; SAtom { Token = StringLit rel } ], _) -> Some rel
- | _ -> Docs.fileForm form |> Option.map fst)
- |> List.map (fun rel -> Path.GetFullPath(Path.Combine(Path.GetDirectoryName file, rel)))
- |> List.filter (fun f -> File.Exists f && not (seen.Contains f))
-
- (file, text, fs)
- :: (included |> List.collect (fun f -> go (Set.add f seen) f))
-
- let full = Path.GetFullPath path
- go (Set.singleton full) full
-
-/// The symbols named `name` in `form` that can be references: not quoted data,
-/// not a `#'` template's own names (an unquoted part of either is code), and
-/// nothing in a type's declaration.
-let rec private symbolsNamed (name: string) (form: SExpr) : Range list =
- let rec quoted (items: SExpr list) =
- match items with
- | SAtom { Token = (Comma | CommaAt) } :: unquoted :: rest -> symbolsNamed name unquoted @ quoted rest
- | SList(inner, _) :: rest -> quoted inner @ quoted rest
- | _ :: rest -> quoted rest
- | [] -> []
-
- match form with
- | SAtom { Token = Symbol n; Range = r } when n = name -> [ r ]
- | SList(SAtom { Token = Symbol("quoted-list" | "syntax-quote") } :: items, _) -> quoted items
- | SList(SAtom { Token = Symbol("type" | "type-rec") } :: _, _) -> []
- | SList(items, _) -> items |> List.collect (symbolsNamed name)
- | _ -> []
-
-/// Whether the source at `r` is `name`: the reader writes some symbols
-/// itself, at the range of the form that made them.
-let private written (text: string) (name: string) (r: Range) =
- r.Start.Line = r.End.Line && Symbols.sliceOf text r = name
+let private moduleFiles = Uses.moduleFiles
+let private symbolsNamed = Uses.symbolsNamed
+let private written = Uses.written
/// Why `name` cannot be what something is renamed to, if it cannot.
let private invalidName (path: string) (name: string) : string option =
@@ -122,14 +78,9 @@ let plan (textOf: string -> string) (path: string) (line: int) (column: int) : R
| Some binder ->
// Every symbol of that name that this binding is what it means.
let edits =
- forms
- |> List.collect (symbolsNamed name)
- |> List.filter (fun r ->
- written text name r
- && (match Scope.find forms r.Start.Line r.Start.Column name with
- | Some b -> b.Range = binder.Range
- | None -> false))
- |> List.map (fun r -> { File = path; Range = r })
+ Uses.ofLocal path text forms binder
+ |> List.filter (fun u -> written text name u.Range)
+ |> List.map (fun u -> { File = u.File; Range = u.Range })
// A parameter of a top-level function is also named by the
// function's doc: `(arg x "...")` and `(rest xs "...")`.
diff --git a/Uses.fs b/Uses.fs
new file mode 100644
index 0000000..ca4286b
--- /dev/null
+++ b/Uses.fs
@@ -0,0 +1,135 @@
+/// Where a name is used: every symbol in the module's own file, and the files
+/// it includes, that means the binding the name at a position means.
+///
+/// Found as go to definition finds a name's binding (`Scope`), on the forms as
+/// the reader gives them. What is not a use is left: quoted data, the part of
+/// a `#'` template that is not unquoted, a type's declaration, and what the
+/// reader wrote itself, such as the `fun` of `#(...)`, which has no text of
+/// its own. Another module's uses are not looked for.
+module BjolangLsp.Uses
+
+open System.IO
+open Bjolang
+open Bjolang.Lexer
+open Bjolang.Ast
+
+type Use =
+ { File: string
+ Range: Range
+ /// Whether this is where the name is bound or defined.
+ IsDefinition: bool }
+
+/// A module's files: its own, and what it includes, each with its text and
+/// forms. `textOf` gives a file's text, the editor's where it has one.
+let moduleFiles (textOf: string -> string) (path: string) : (string * string * SExpr list) list =
+ let rec go (seen: Set) (file: string) =
+ let text = textOf file
+ let fs = Symbols.forms file text |> Option.defaultValue []
+
+ let included =
+ fs
+ |> List.choose (fun form ->
+ match form with
+ | SList([ SAtom { Token = Symbol "include" }; SAtom { Token = StringLit rel } ], _) -> Some rel
+ | _ -> Docs.fileForm form |> Option.map fst)
+ |> List.map (fun rel -> Path.GetFullPath(Path.Combine(Path.GetDirectoryName file, rel)))
+ |> List.filter (fun f -> File.Exists f && not (seen.Contains f))
+
+ (file, text, fs)
+ :: (included |> List.collect (fun f -> go (Set.add f seen) f))
+
+ let full = Path.GetFullPath path
+ go (Set.singleton full) full
+
+/// The symbols named `name` in `form` that can be uses: not quoted data, not a
+/// `#'` template's own names (an unquoted part of either is code), and nothing
+/// in a type's declaration.
+let rec symbolsNamed (name: string) (form: SExpr) : Range list =
+ let rec quoted (items: SExpr list) =
+ match items with
+ | SAtom { Token = (Comma | CommaAt) } :: unquoted :: rest -> symbolsNamed name unquoted @ quoted rest
+ | SList(inner, _) :: rest -> quoted inner @ quoted rest
+ | _ :: rest -> quoted rest
+ | [] -> []
+
+ match form with
+ | SAtom { Token = Symbol n; Range = r } when n = name -> [ r ]
+ | SList(SAtom { Token = Symbol("quoted-list" | "syntax-quote") } :: items, _) -> quoted items
+ | SList(SAtom { Token = Symbol("type" | "type-rec") } :: _, _) -> []
+ | SList(items, _) -> items |> List.collect (symbolsNamed name)
+ | _ -> []
+
+/// Whether the source at `r` is `name`: the reader writes some symbols
+/// itself, at the range of the form that made them.
+let written (text: string) (name: string) (r: Range) =
+ r.Start.Line = r.End.Line && Symbols.sliceOf text r = name
+
+/// The uses of the local binding `binder`, in the file of `forms`, the binding
+/// itself among them.
+let ofLocal (path: string) (text: string) (forms: SExpr list) (binder: Scope.Binder) : Use list =
+ let uses =
+ forms
+ |> List.collect (symbolsNamed binder.Name)
+ |> List.filter (fun r ->
+ written text binder.Name r
+ && (match Scope.find forms r.Start.Line r.Start.Column binder.Name with
+ | Some b -> b.Range = binder.Range
+ | None -> false))
+ |> List.map (fun r -> { File = path; Range = r; IsDefinition = r = binder.Range })
+
+ // A keyword parameter is bound by a keyword, `#:name`, not a symbol.
+ if uses |> List.exists (fun u -> u.IsDefinition) then
+ uses
+ else
+ { File = path; Range = binder.Range; IsDefinition = true } :: uses
+
+/// The uses of a name no local binding takes, in the module's files: one the
+/// module defines, imports, or has built in. Its definition is among them if
+/// the module has it.
+let ofTopLevel (textOf: string -> string) (path: string) (name: string) : Use list =
+ let files = moduleFiles textOf path
+
+ let definedAt =
+ files
+ |> List.collect (fun (file, t, _) -> Symbols.ofText file t |> Option.defaultValue [] |> Symbols.flatten)
+ |> List.filter (fun s -> s.Name = name)
+ |> List.map (fun s -> s.NameRange)
+ |> Set.ofList
+
+ let found =
+ files
+ |> List.collect (fun (file, t, fs) ->
+ fs
+ |> List.collect (symbolsNamed name)
+ |> List.filter (fun r -> written t name r && (Scope.find fs r.Start.Line r.Start.Column name).IsNone)
+ |> List.map (fun r -> { File = file; Range = r; IsDefinition = definedAt.Contains r }))
+
+ // A type's or a constructor's name is not a use in its declaration, so
+ // the definition is added when the search left it out.
+ let missed =
+ definedAt
+ |> Seq.filter (fun r -> not (found |> List.exists (fun u -> u.Range = r)))
+ |> Seq.map (fun r -> { File = r.File; Range = r; IsDefinition = true })
+ |> List.ofSeq
+
+ missed @ found
+
+/// The name at `line` (1-based) and `column` (0-based) of `path`, and its
+/// uses in the module, in the order they are written.
+let at (textOf: string -> string) (path: string) (line: int) (column: int) : (string * Use list) option =
+ let path = Path.GetFullPath path
+ let text = textOf path
+
+ match Symbols.nameAt path text line column, Symbols.forms path text with
+ | Some(name, _), Some forms ->
+ let uses =
+ match Scope.find forms line column name with
+ | Some binder -> ofLocal path text forms binder
+ | None -> ofTopLevel textOf path name
+
+ Some(
+ name,
+ uses
+ |> List.sortBy (fun u -> u.File <> path, u.File, u.Range.Start.Line, u.Range.Start.Column)
+ )
+ | _ -> None
diff --git a/test/smoke.py b/test/smoke.py
index 510078f..c6345c2 100755
--- a/test/smoke.py
+++ b/test/smoke.py
@@ -757,6 +757,208 @@ def renaming(server, tmp):
server.diagnostics_after("textDocument/didClose", uri)
+SHAPES = """(type (: Shape (Union (: Circle int) (: Square int))))
+
+(: size (-> Shape int))
+(defun (size s)
+ (match s
+ ((Circle r) r)
+ ((Square w) w)))
+
+(defun (main) (println (int->string (size (Circle 2)))) 0)
+"""
+
+
+def referencing(server, tmp):
+ path = os.path.join(tmp, "renaming.bjo")
+ uri = "file://" + path
+ with open(path, "w") as f:
+ f.write(RENAMING)
+ server.diagnostics_after("textDocument/didOpen", uri, RENAMING)
+
+ def ask(method, text, file_uri, needle, offset, nth=0, definition=True):
+ params = {"textDocument": {"uri": file_uri}, "position": position_of(text, needle, nth, offset)}
+ if method == "textDocument/references":
+ params["context"] = {"includeDeclaration": definition}
+ return server.send(method, params, request=True)["result"]
+
+ def at(text, found):
+ """Each location as the line it is on and what it covers."""
+ lines = text.split("\n")
+ return sorted(
+ (l["range"]["start"]["line"],
+ lines[l["range"]["start"]["line"]][l["range"]["start"]["character"]:l["range"]["end"]["character"]])
+ for l in found or [])
+
+ def lines(text, *needles):
+ return sorted(line_of(text, n) for n in needles)
+
+ found = ask("textDocument/references", RENAMING, uri, "(+ n", 3)
+ expect("references: a local's binding and uses, in an interpolation too, not in quoted data",
+ [l for l, _ in at(RENAMING, found)] == lines(RENAMING, "((n (helper", "${n}", "(+ n")
+ and all(name == "n" for _, name in at(RENAMING, found)),
+ at(RENAMING, found))
+
+ found = ask("textDocument/references", RENAMING, uri, "(+ n", 3, definition=False)
+ expect("references: without the declaration, a local's uses only",
+ [l for l, _ in at(RENAMING, found)] == lines(RENAMING, "${n}", "(+ n"), at(RENAMING, found))
+
+ found = ask("textDocument/references", RENAMING, uri, "(helper 3)", 1)
+ expect("references: a top-level defun, in its doc and signature too",
+ [l for l, _ in at(RENAMING, found)]
+ == lines(RENAMING, "(:doc helper", "(: helper", "(defun (helper", "(helper 3)"),
+ at(RENAMING, found))
+
+ found = ask("textDocument/references", RENAMING, uri, "(defun (area", 8)
+ expect("references: an exported name, in this module",
+ [l for l, _ in at(RENAMING, found)]
+ == lines(RENAMING, "(export area)", "(: area", "(defun (area", "(println (area"),
+ at(RENAMING, found))
+
+ found = ask("textDocument/references", RENAMING, uri, "(length xs)", 1)
+ expect("references: an imported name, where this module uses it",
+ at(RENAMING, found) == [(line_of(RENAMING, "(length xs)"), "length")], at(RENAMING, found))
+
+ found = ask("textDocument/references", RENAMING, uri, "(str greeting", 5)
+ expect("references: a keyword parameter, in its function",
+ [l for l, _ in at(RENAMING, found)] == lines(RENAMING, "#:greeting \"hello\"", "(str greeting"),
+ at(RENAMING, found))
+
+ found = ask("textDocument/documentHighlight", RENAMING, uri, "(+ n", 3)
+ kinds = sorted((h["range"]["start"]["line"], h["kind"]) for h in found or [])
+ expect("highlight: the binding as a write, the uses as reads",
+ kinds == sorted([(line_of(RENAMING, "((n (helper"), 3), (line_of(RENAMING, "${n}"), 2),
+ (line_of(RENAMING, "(+ n"), 2)]),
+ kinds)
+ server.diagnostics_after("textDocument/didClose", uri)
+
+ path = os.path.join(tmp, "shapes.bjo")
+ uri = "file://" + path
+ with open(path, "w") as f:
+ f.write(SHAPES)
+ server.diagnostics_after("textDocument/didOpen", uri, SHAPES)
+
+ found = ask("textDocument/references", SHAPES, uri, "(-> Shape", 4)
+ expect("references: a type, its declaration and the signature that names it",
+ at(SHAPES, found) == sorted([(0, "Shape"), (line_of(SHAPES, "(-> Shape"), "Shape")]), at(SHAPES, found))
+
+ found = ask("textDocument/references", SHAPES, uri, "(Circle 2)", 1)
+ expect("references: a constructor, its case, a pattern and a use",
+ at(SHAPES, found)
+ == sorted([(0, "Circle"), (line_of(SHAPES, "((Circle r)"), "Circle"), (line_of(SHAPES, "(Circle 2)"), "Circle")]),
+ at(SHAPES, found))
+ server.diagnostics_after("textDocument/didClose", uri)
+
+
+INCOMPLETE = """(type (: Shape (Union (: Circle int) (: Square int) Empty)))
+
+(: size (-> Shape int))
+(defun (size s)
+ (match s
+ ((Circle r) r)))
+
+(: pick (-> (Option Shape) int))
+(defun (pick o)
+ (match o
+ ((Some (Circle r)) r)
+ (None 0)))
+
+(defun (main) (println (int->string (+ (size Empty) (pick None)))) 0)
+"""
+
+HOLES = """(type (: Shape (Union (: Circle int) (: Square int) Empty)))
+
+(: add-size (-> Shape int int))
+(defun (add-size s n) n)
+
+(: total-size (-> (List Shape) int))
+(defun (total-size shapes)
+ (list-foldl _ 0 shapes))
+
+(: default-shape (-> Shape))
+(defun (default-shape) _)
+
+(defun (main) (println (int->string (total-size (list (default-shape))))) 0)
+"""
+
+
+def applied(text, edits):
+ """`text` with LSP text edits made, the last first."""
+ lines = text.split("\n")
+ offsets = [0]
+ for line in lines:
+ offsets.append(offsets[-1] + len(line) + 1)
+
+ def offset(p):
+ return offsets[p["line"]] + p["character"]
+
+ for e in sorted(edits, key=lambda e: -offset(e["range"]["start"])):
+ a, b = offset(e["range"]["start"]), offset(e["range"]["end"])
+ text = text[:a] + e["newText"] + text[b:]
+ return text
+
+
+def acting(server, tmp):
+ def open_(name, text):
+ path = os.path.join(tmp, name)
+ uri = "file://" + path
+ with open(path, "w") as f:
+ f.write(text)
+ return uri, server.diagnostics_after("textDocument/didOpen", uri, text)
+
+ def actions(uri, text, needle, offset=1):
+ at = position_of(text, needle, 0, offset)
+ params = {"textDocument": {"uri": uri}, "range": {"start": at, "end": at}, "context": {"diagnostics": []}}
+ return server.send("textDocument/codeAction", params, request=True)["result"] or []
+
+ def edit_of(found, title, uri):
+ chosen = [a for a in found if a["title"] == title]
+ return chosen[0]["edit"]["changes"][uri] if chosen else None
+
+ uri, found = open_("incomplete.bjo", INCOMPLETE)
+ expect("actions: the incomplete matches are reported",
+ len([d for d in found if "does not cover every value" in d["message"]]) == 2, found)
+
+ found = actions(uri, INCOMPLETE, "(match s", 1)
+ first = edit_of(found, "Add the 2 missing clauses", uri)
+ expect("actions: a match lacking two cases is offered both", first is not None, [a["title"] for a in found])
+ fixed = applied(INCOMPLETE, first or [])
+ expect("actions: the clauses go after the last one, lined up with it",
+ " ((Circle r) r)\n ((Square _) _)\n (Empty _))" in fixed, fixed)
+
+ # Both actions are of the text as checked, so both go into it together.
+ found = actions(uri, INCOMPLETE, "(match o", 1)
+ second = edit_of(found, "Add the 2 missing clauses", uri)
+ fixed = applied(INCOMPLETE, (first or []) + (second or []))
+ expect("actions: a nested case is spelled out",
+ " (None 0)\n ((Some (Square _)) _)\n ((Some Empty) _))" in fixed, fixed)
+
+ server.change(uri, fixed, 2)
+ after = server.next_diagnostics(uri)
+ expect("actions: with the clauses added, every match covers its type and the bodies are holes",
+ not any("does not cover" in d["message"] for d in after)
+ and len([d for d in after if d["message"].startswith("Hole at")]) == 4,
+ [d["message"].splitlines()[0] for d in after])
+ server.diagnostics_after("textDocument/didClose", uri)
+
+ uri, found = open_("holes.bjo", HOLES)
+ found = actions(uri, HOLES, "(list-foldl _", 12)
+ titles = [a["title"] for a in found]
+ expect("actions: a hole is offered the binding that fits it, and a fun",
+ "Fill with add-size" in titles and "Fill with (fun (x y) _)" in titles, titles)
+ filled = applied(HOLES, edit_of(found, "Fill with add-size", uri) or [])
+ expect("actions: filling replaces the hole", "(list-foldl add-size 0 shapes)" in filled, filled)
+
+ found = actions(uri, HOLES, "(defun (default-shape) _", 23)
+ titles = [a["title"] for a in found]
+ expect("actions: a hole of a union's type is offered its cases, each once",
+ sorted(titles) == ["Fill with (Circle _)", "Fill with (Square _)", "Fill with Empty"], titles)
+
+ expect("actions: nothing is offered away from a hole", actions(uri, HOLES, "(defun (add-size", 8) == [],
+ actions(uri, HOLES, "(defun (add-size", 8))
+ server.diagnostics_after("textDocument/didClose", uri)
+
+
CHAIN_MACROS = """;; Two macros, one expanding to the other.
(import (std syntax-match))
@@ -972,6 +1174,8 @@ with tempfile.TemporaryDirectory() as tmp:
locals_(server, tmp)
inferred(server, tmp)
renaming(server, tmp)
+ referencing(server, tmp)
+ acting(server, tmp)
expanding(server, tmp)
answer = server.send("shutdown", request=True)