diff --git a/BjolangLsp.fsproj b/BjolangLsp.fsproj
index 54952a6..b8bf787 100644
--- a/BjolangLsp.fsproj
+++ b/BjolangLsp.fsproj
@@ -33,6 +33,7 @@
+
diff --git a/Hover.fs b/Hover.fs
index c2dad14..0c8fe07 100644
--- a/Hover.fs
+++ b/Hover.fs
@@ -80,14 +80,52 @@ let markdown (text: string) : string =
// The space between two `@item`s is left at the end of a line.
RegularExpressions.Regex.Replace(out.ToString(), " +\n", "\n")
-/// The `(: name Type)` declaration of `name` among `forms`, if it has one.
-let rec private declaration (name: string) (forms: SExpr list) : SExpr option =
- forms
- |> List.tryPick (fun form ->
+/// The declaration of `name` among `forms`, as it reads with the name in it:
+/// a `(: name Type)`, or a `(: Type)` written just above the definition, which
+/// is shown as `(: name Type)`. `slice` gives a form's text.
+let rec private declaration (slice: Range -> string) (name: string) (forms: SExpr list) : string option =
+ // The form that defines `name`: `(def name ...)`, `(defun (name ...) ...)`.
+ let defines (form: SExpr) =
match form with
- | SList(SAtom { Token = Colon } :: SAtom { Token = Symbol n } :: _, _) when n = name -> Some form
- | SList(SAtom { Token = Symbol("begin" | "module") } :: rest, _) -> declaration name rest
- | _ -> None)
+ | SList(SAtom { Token = Symbol head } :: binder :: _, _) when head.StartsWith "def" ->
+ match binder with
+ | SAtom { Token = Symbol n }
+ | SList(SAtom { Token = Symbol n } :: _, _)
+ | SList(SAtom { Token = Colon } :: SAtom { Token = Symbol n } :: _, _) -> n = name
+ | _ -> false
+ | _ -> false
+
+ // `(: Type)`, with what may follow the type, such as `#:sync`.
+ let nameless (form: SExpr) =
+ match form with
+ | SList(SAtom { Token = Colon } :: (SList _ as t) :: rest, _)
+ | SList(SAtom { Token = Colon } :: (SAtom { Token = (Symbol _ | TypeVar _) } as t) :: rest, _) when
+ rest
+ |> List.forall (function
+ | SAtom { Token = Keyword _ } -> true
+ | _ -> false)
+ ->
+ Some t
+ | _ -> None
+
+ let named =
+ forms
+ |> List.tryPick (fun form ->
+ match form with
+ | SList(SAtom { Token = Colon } :: SAtom { Token = Symbol n } :: _ :: _, r) when n = name -> Some(slice r)
+ | SList(SAtom { Token = Symbol("begin" | "module") } :: rest, _) -> declaration slice name rest
+ | _ -> None)
+
+ named
+ |> Option.orElse (
+ forms
+ |> List.pairwise
+ |> List.tryPick (fun (before, form) ->
+ if defines form then
+ nameless before |> Option.map (fun t -> $"(: %s{name} %s{slice (getRange t)})")
+ else
+ None)
+ )
/// The `(:doc ...)` entries among `forms`. One that does not read is left
/// out: the compiler reports it, and a hover has nothing to say about it.
@@ -113,12 +151,16 @@ let private clip (text: string) =
let private fence (code: string) = $"```lisp\n%s{code}\n```"
-/// The signature: the `(: name Type)` declaration if there is one, and the
-/// form's head with its parameters, as written.
-let private signature (found: Found) : string =
+/// The signature: the `(: name Type)` declaration if there is one, or else
+/// the type the compiler inferred, and the form's head with its parameters,
+/// as written.
+let private signature (found: Found) (inferred: string option) : string =
let s = found.Symbol
let m = found.Module
- let declared = declaration s.Name m.Forms |> Option.map (fun d -> m.Slice(getRange d))
+
+ let declared =
+ declaration m.Slice s.Name m.Forms
+ |> Option.orElse (inferred |> Option.map (fun t -> $"(: %s{s.Name} %s{t})"))
let shape = m.Slice s.Signature
let head =
@@ -264,7 +306,7 @@ let builtin (name: string) : string option =
|> String.concat "\n\n")
/// The hover for `found`: its signature, where it is, and its doc.
-let text (found: Found) : string =
+let text (found: Found) (inferred: string option) : string =
let where =
let file = IO.Path.GetFileName found.Symbol.NameRange.File
@@ -274,7 +316,7 @@ let text (found: Found) : string =
| Kind.Method -> $"A method of the trait `%s{found.Symbol.Detail}`, in %s{file}."
| _ -> $"In %s{file}."
- [ yield signature found
+ [ yield signature found inferred
yield! Option.toList (doc found)
yield $"*%s{where}*" ]
|> String.concat "\n\n"
diff --git a/Program.fs b/Program.fs
index 8c93bd8..f979884 100644
--- a/Program.fs
+++ b/Program.fs
@@ -167,7 +167,11 @@ let private markdownContent (text: string) : JsonNode =
/// is.
let private describe (uri: string) (name: string) : string option =
match Symbols.definition (uriToPath uri) (textOf uri) name with
- | Some found -> Some(Hover.text found)
+ | Some found ->
+ // What the compiler inferred, for a definition the last check of a
+ // file saw, which a hover shows where no signature is written.
+ let inferred = Types.boundAt found.Symbol.NameRange.File name found.Symbol.NameRange
+ Some(Hover.text found inferred)
| None -> Hover.builtin name
/// The type the last check inferred for the local `b`: at the use written at
@@ -309,6 +313,110 @@ let private resolve (item: JsonNode) : JsonNode =
item.DeepClone()
+/// A file's text: the editor's, where it has the file open, else what is on
+/// disk.
+let private textOfPath (path: string) : string =
+ let full = IO.Path.GetFullPath path
+
+ match texts |> Seq.tryFind (fun kv -> IO.Path.GetFullPath(uriToPath kv.Key) = full) with
+ | Some kv -> kv.Value
+ | None -> if IO.File.Exists full then IO.File.ReadAllText full else ""
+
+/// `text` with each of `edits` replaced by `newText`. Lines are 1-based and
+/// columns 0-based, as a compiler range has them.
+let private applyEdits (text: string) (edits: Rename.Edit list) (newText: string) : string =
+ let lineStarts =
+ [| yield 0
+ for i in 0 .. text.Length - 1 do
+ if text[i] = '\n' then yield i + 1 |]
+
+ let offset (p: Bjolang.Lexer.Position) = lineStarts[p.Line - 1] + p.Column
+
+ edits
+ |> List.sortByDescending (fun e -> offset e.Range.Start)
+ |> List.fold
+ (fun (t: string) e ->
+ let start = offset e.Range.Start
+ t.Substring(0, start) + newText + t.Substring(offset e.Range.End))
+ text
+
+/// The range of the name `prepareRename` asks about, and the name, or why it
+/// cannot be renamed.
+let private prepareRenameAt (uri: string) (line: int) (character: int) : Result =
+ Rename.plan textOfPath (uriToPath uri) (line + 1) character
+ |> Result.map (fun p ->
+ match Symbols.nameAt (uriToPath uri) (textOf uri) (line + 1) character with
+ | Some(_, at) ->
+ JsonObject(dict [ "range", range at; "placeholder", JsonValue.Create p.Old :> JsonNode ]) :> JsonNode
+ | None -> null)
+
+/// The edit that renames the name at a position to `newName`, or why it is
+/// refused.
+///
+/// The renamed text is checked before it is offered, against a check of the
+/// text as it is: an error the renamed program has and this one does not is
+/// a rename that changed what something means, and is refused with it. The
+/// check after it leaves the file's types those of the renamed text, so the
+/// file is checked again as it stands.
+let private renameAt (uri: string) (line: int) (character: int) (newName: string) : Result =
+ let path = IO.Path.GetFullPath(uriToPath uri)
+
+ match Rename.plan textOfPath path (line + 1) character with
+ | Error why -> Error why
+ | Ok p ->
+ match Rename.capture textOfPath path p newName with
+ | Some why -> Error why
+ | None ->
+ let byFile = p.Edits |> List.groupBy (fun e -> e.File)
+
+ let buffers =
+ texts |> Seq.map (fun kv -> IO.Path.GetFullPath(uriToPath kv.Key), kv.Value) |> Map.ofSeq
+
+ let renamed =
+ byFile
+ |> List.fold
+ (fun (acc: Map) (file, edits) ->
+ Map.add file (applyEdits (textOfPath file) edits newName) acc)
+ buffers
+
+ let errors (found: Check.Found list) =
+ found |> List.filter (fun f -> f.IsError) |> List.map (fun f -> f.Message)
+
+ // A message about the old name, as it reads about the new one. Only
+ // the whole name is replaced: `n` is in "not" too.
+ let renamedIn (message: string) =
+ Text.RegularExpressions.Regex.Replace(
+ message,
+ @"(?=+&.-])" + Text.RegularExpressions.Regex.Escape p.Old + @"(?![A-Za-z0-9_?!*/<>=+&.-])",
+ newName
+ )
+
+ let before = Check.file buffers path |> errors |> List.map renamedIn |> Set.ofList
+ let after = Check.file renamed path |> errors
+ dueChecks[uri] <- DateTime.UtcNow
+
+ match after |> List.tryFind (fun m -> not (before.Contains m)) with
+ | Some m ->
+ Error $"Renaming '%s{p.Old}' to '%s{newName}' would give the program an error it does not have now: %s{m}"
+ | None ->
+ let uriOf (file: string) =
+ if file = path then uri else Uri(file).AbsoluteUri
+
+ let changes =
+ byFile
+ |> List.map (fun (file, edits) ->
+ uriOf file,
+ JsonArray(
+ edits
+ |> List.map (fun e ->
+ JsonObject(dict [ "range", range e.Range; "newText", JsonValue.Create newName :> JsonNode ])
+ :> JsonNode)
+ |> Array.ofList
+ )
+ :> JsonNode)
+
+ Ok(JsonObject(dict [ "changes", JsonObject(dict changes) :> JsonNode ]) :> JsonNode)
+
let private capabilities () : JsonNode =
JsonNode.Parse
"""
@@ -318,8 +426,9 @@ let private capabilities () : JsonNode =
"definitionProvider": true,
"hoverProvider": true,
"inlayHintProvider": true,
+ "renameProvider": { "prepareProvider": true },
"completionProvider": { "resolveProvider": true, "triggerCharacters": [ "(" ] } },
- "serverInfo": { "name": "bjolang-lsp", "version": "0.5.0" } }
+ "serverInfo": { "name": "bjolang-lsp", "version": "0.6.0" } }
"""
[]
@@ -452,6 +561,24 @@ 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"])
+ // A refusal is an error answer: the client shows its
+ // message, which says why.
+ | "textDocument/prepareRename"
+ | "textDocument/rename" ->
+ let p = message["params"]
+ let position = p["position"]
+ let line = position["line"].GetValue()
+ let character = position["character"].GetValue()
+
+ let answer =
+ match uri () with
+ | None -> Error "No document."
+ | Some u when methodName = "textDocument/prepareRename" -> prepareRenameAt u line character
+ | Some u -> renameAt u line character (p["newName"].GetValue())
+
+ match answer with
+ | Ok result -> Rpc.respond id result
+ | Error why -> Rpc.respondError id -32803 why
// 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.
diff --git a/README.md b/README.md
index a24edce..48cfd5c 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,8 @@
# BjolangLsp
A language server for Bjolang. It checks a file against its project's
-packages (see "Projects"), and it does five things:
+packages (see "Projects"). Inferred types and renaming have sections of
+their own below; besides those, it does these:
- Diagnostics: it checks a file with the compiler's frontend, as
`bjolang --check` does, and sends the errors and warnings to the editor.
@@ -84,6 +85,40 @@ Local names are the ones the parser's own forms bind: parameters of a
patterns, the clauses of `loop`, `seql` and a comprehension, and `def` or
`defun` inside a body, for the forms after it.
+## Rename
+
+`textDocument/rename`, with `textDocument/prepareRename` so that the editor
+says why a name cannot be renamed before a new one is typed. It renames
+
+- a local binding: a parameter, a `let`, a `def` or `defun` in a body, a
+ pattern's variable, a loop variable or accumulator. A parameter of a
+ top-level function is renamed in its `(:doc ...)` too, in `(arg ...)` and
+ `(rest ...)`;
+- a top-level `def` or `defun` the module does not export, with its
+ signature, its `(:doc ...)` and its other mentions, in the files the module
+ includes as well.
+
+The places are the ones go to definition would take to the binding: every
+symbol of that name that means it, in an interpolated string's `${...}`
+too. Quoted data, the names of a `#'` template that are not unquoted, and a
+type's declaration are left.
+
+It is refused, with what the editor shows as the reason, where it could
+change what the program means:
+
+- the new name would take a use from another binding: a binding of it
+ inside the renamed one's scope, or a use of it there;
+- a keyword parameter, as callers write its name as `#:name`;
+- an exported name, a macro, `main`, and a name defined elsewhere;
+- a new name that is not one symbol, starts with an upper case letter, or
+ has a `.`;
+- a new name the module already sees, for a top-level definition.
+
+Before it answers, the server checks the renamed text. A renamed program
+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.
+
## Building
It expects the Bjolang checkout beside this one, at `../Bjolang`, and runs
@@ -196,7 +231,8 @@ With eglot instead:
- 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.
-- Find references, rename.
+- Find references, and renaming an exported name, a keyword parameter, a
+ type, a constructor, a field or a trait method (see "Rename").
- More than one project. A server serves the project of the first file it is
asked about; see "Projects" above.
- Stale imports are built by the installed compiler, which was tested only
diff --git a/Rename.fs b/Rename.fs
new file mode 100644
index 0000000..9b10342
--- /dev/null
+++ b/Rename.fs
@@ -0,0 +1,279 @@
+/// 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.
+///
+/// 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,
+/// for a keyword parameter, whose name its callers write, and for a name
+/// another module may use. `Program` also checks the renamed text before it
+/// answers, and refuses one that has an error the text before did not.
+module BjolangLsp.Rename
+
+open System
+open System.IO
+open Bjolang
+open Bjolang.Lexer
+open Bjolang.Ast
+
+type Edit = { File: string; Range: Range }
+
+/// What a rename renames, and every place it is written.
+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
+
+/// Why `name` cannot be what something is renamed to, if it cannot.
+let private invalidName (path: string) (name: string) : string option =
+ let tokens =
+ try
+ Session.isolated (fun () -> Lexer.tokenize path name)
+ with _ ->
+ []
+
+ match tokens with
+ | [ { Token = Symbol n } ] when n = name ->
+ if name = "_" then Some "'_' binds nothing."
+ elif Char.IsUpper name[0] then Some $"'%s{name}' starts with an upper case letter, which is a type's or a constructor's."
+ elif name.Contains "." then Some $"'%s{name}' has a '.', which makes it a member access."
+ else None
+ | _ -> Some $"'%s{name}' is not a name: it does not read as one symbol."
+
+let private at (r: Range) = $"%s{Path.GetFileName r.File}:%d{r.Start.Line}:%d{r.Start.Column + 1}"
+
+/// Where a top-level name is exported, if it is.
+let private exportedAt (files: (string * string * SExpr list) list) (name: string) : Range option =
+ files
+ |> List.collect (fun (_, _, fs) -> fs)
+ |> List.tryPick (fun form ->
+ match form with
+ | SList(SAtom { Token = Symbol("export" | "re-export") } :: names, r) when
+ names
+ |> List.exists (function
+ | SAtom { Token = Symbol n } -> n = name
+ | _ -> false)
+ ->
+ Some r
+ | _ -> None)
+
+/// The places to rename for the name at `line` (1-based) and `column`
+/// (0-based) of `path`, or why it cannot be renamed. `textOf` gives a file's
+/// text, the editor's where it has one.
+let plan (textOf: string -> string) (path: string) (line: int) (column: int) : Result =
+ let path = Path.GetFullPath path
+ let text = textOf path
+
+ match Symbols.nameAt path text line column, Symbols.forms path text with
+ | None, _ -> Error "There is no name here to rename."
+ | _, None -> Error "This file does not read, so its names cannot be found."
+ | Some(name, nameRange), Some forms ->
+ match Scope.find forms line column name with
+ | Some binder when binder.Description.Contains "by keyword" ->
+ Error $"'%s{name}' is a keyword parameter, and its callers write it as #:%s{name}. Renaming one is not supported yet."
+ | 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 })
+
+ // A parameter of a top-level function is also named by the
+ // function's doc: `(arg x "...")` and `(rest xs "...")`.
+ let owner =
+ let d = binder.Description
+ let start = d.IndexOf "a parameter of `"
+
+ if start = 0 then
+ let rest = d.Substring("a parameter of `".Length)
+ Some(rest.Substring(0, rest.IndexOf '`'))
+ else
+ None
+
+ let documented =
+ match owner with
+ | Some fname when (Symbols.ofText path text |> Option.defaultValue [] |> List.exists (fun s -> s.Name = fname)) ->
+ moduleFiles textOf path
+ |> List.collect (fun (file, t, fs) ->
+ fs
+ |> List.collect (fun form ->
+ match form with
+ | SList(SAtom { Token = Keyword "doc" } :: SAtom { Token = Symbol f } :: clauses, _) when f = fname ->
+ clauses
+ |> List.choose (function
+ | SList(SAtom { Token = Symbol("arg" | "rest") } :: SAtom { Token = Symbol n; Range = r } :: _, _) when
+ n = name && written t name r
+ ->
+ Some { File = file; Range = r }
+ | _ -> None)
+ | _ -> []))
+ | _ -> []
+
+ Ok { Old = name; Edits = edits @ documented }
+ | None ->
+ let files = moduleFiles textOf path
+
+ let own =
+ files
+ |> List.collect (fun (_, t, _) ->
+ Symbols.ofText path t |> Option.defaultValue [])
+ |> List.tryFind (fun s -> s.Name = name)
+
+ match own with
+ | None ->
+ match Symbols.definition path text name with
+ | Some found -> Error $"'%s{name}' is defined in %s{Path.GetFileName found.Module.File}, not here. Rename it there."
+ | None -> Error $"'%s{name}' is not defined in this module: it is built into the compiler, or nothing defines it."
+ | Some s when s.Kind <> Symbols.Kind.Function && s.Kind <> Symbols.Kind.Variable ->
+ Error $"'%s{name}' is a %s{s.Detail}, and only a local binding, a def or a defun can be renamed so far."
+ | Some s when s.Detail.StartsWith "def/" && s.Detail <> "def/mutable" ->
+ Error $"'%s{name}' is defined by %s{s.Detail}, and is published with the module. Renaming one is not supported yet."
+ | Some _ when name = "main" -> Error "'main' is the program's entry point, which is found by its name."
+ | Some _ ->
+ match exportedAt files name with
+ | Some r ->
+ Error
+ $"'%s{name}' is exported at %s{at r}, so other modules may use it. Renaming an exported name is not supported yet."
+ | None ->
+ // Every symbol of that name that no local binding takes.
+ let edits =
+ 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 }))
+
+ Ok { Old = name; Edits = edits }
+
+/// Why renaming by `plan` to `newName` would change what the program means,
+/// if it would: a use of `newName` the renamed binding would take over, or a
+/// binding of `newName` that would take over a renamed use.
+let capture (textOf: string -> string) (path: string) (p: Plan) (newName: string) : string option =
+ match invalidName path newName with
+ | Some why -> Some why
+ | None when newName = p.Old -> Some $"'%s{newName}' is already its name."
+ | None ->
+
+ let path = Path.GetFullPath path
+ let byFile = p.Edits |> List.groupBy (fun e -> e.File)
+
+ let formsOf (file: string) = Symbols.forms file (textOf file) |> Option.defaultValue []
+
+ // A renamed use that a binding of the new name inside the renamed one
+ // would take. One outside it is shadowed, which is a rename's business;
+ // whether something still uses it is the check below.
+ let taken =
+ byFile
+ |> List.tryPick (fun (file, edits) ->
+ let fs = formsOf file
+
+ edits
+ |> List.tryPick (fun e ->
+ // Innermost last.
+ let scope = Scope.at fs e.Range.Start.Line e.Range.Start.Column
+ let ours = scope |> List.tryFindIndexBack (fun b -> b.Name = p.Old)
+
+ match scope |> List.tryFindIndexBack (fun b -> b.Name = newName), ours with
+ | Some theirs, Some o when theirs > o -> Some scope[theirs]
+ | Some theirs, None -> Some scope[theirs]
+ | _ -> None
+ |> Option.map (fun b ->
+ $"'%s{newName}' is bound at %s{at b.Range}, so the use of '%s{p.Old}' at %s{at e.Range} would mean that instead.")))
+
+ match taken with
+ | Some why -> Some why
+ | None ->
+
+ // A use of the new name where the renamed binding is in scope.
+ let local =
+ p.Edits
+ |> List.tryPick (fun e ->
+ let fs = formsOf e.File
+ let text = textOf e.File
+
+ match Scope.find fs e.Range.Start.Line e.Range.Start.Column p.Old with
+ | Some b when b.Range = e.Range -> Some(e.File, fs, text, b)
+ | _ -> None)
+
+ match local with
+ | Some(file, fs, text, binder) ->
+ fs
+ |> List.collect (symbolsNamed newName)
+ |> List.filter (written text newName)
+ |> List.tryPick (fun r ->
+ if Scope.at fs r.Start.Line r.Start.Column |> List.exists (fun b -> b.Range = binder.Range) then
+ Some
+ $"'%s{newName}' is used at %s{at r}, where '%s{p.Old}' is in scope, and it would mean the renamed binding there."
+ else
+ None)
+ | None ->
+ // A top-level name: the new one must not be another definition the
+ // module sees, and no use of it in the module may become this one.
+ match Symbols.definition path (textOf path) newName with
+ | Some found ->
+ Some $"'%s{newName}' is already defined, in %s{Path.GetFileName found.Module.File}."
+ | None when (Hover.builtinDeclaration newName).IsSome ->
+ Some $"'%s{newName}' is built into the compiler, and every use of it in this module would mean this instead."
+ | None ->
+ moduleFiles textOf path
+ |> List.tryPick (fun (file, text, fs) ->
+ fs
+ |> List.collect (symbolsNamed newName)
+ |> List.filter (written text newName)
+ |> List.tryHead
+ |> Option.map (fun r -> $"'%s{newName}' is used at %s{at r}, and would mean the renamed definition there."))
diff --git a/test/smoke.py b/test/smoke.py
index 5605fd0..510078f 100755
--- a/test/smoke.py
+++ b/test/smoke.py
@@ -521,6 +521,8 @@ INFERRED = """(import (std prelude))
(def (: m int) (+ k 1))
(def bumped (+ m 1))
bumped)
+
+(def numbers (list 4 5 6))
"""
# One declaration that does not check, and one that does.
@@ -559,7 +561,18 @@ def inferred(server, tmp):
h = hover(INFERRED, needle, 0)
expect("inferred hover: " + name, h and wanted in h, h)
+ h = hover(INFERRED, "(def numbers", 5)
+ expect("inferred hover: a top-level def with no signature shows the type inferred",
+ h and "(: numbers (List int))" in h, h)
+
+ # The status bar shows a hover's first line, so it has to be the type. The
+ # prelude writes its signatures nameless, above the definition.
h = hover(INFERRED, "(list-map")
+ expect(
+ "hover: a nameless signature, shown with the name, first",
+ h and h.split("\n")[1].startswith("(: list-map (-> (-?-> %a %b) (List %a) (List %b)))"),
+ h,
+ )
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,
@@ -628,6 +641,122 @@ def inferred(server, tmp):
server.diagnostics_after("textDocument/didClose", uri)
+RENAMING = """(export area)
+
+(:doc helper
+ (summary "Twice the number.")
+ (arg x "A number.")
+ (returns "Twice x."))
+(: helper (-> int int))
+(defun (helper x) (* 2 x))
+
+(: area (-> int int string))
+(defun (area w h)
+ (def product (* w h))
+ (defun (twice s) (* 2 s))
+ (let ((n (helper 3))
+ (xs (list 1 2 3)))
+ (println #"n is ${n}")
+ (println '(n xs))
+ (let ((count 10))
+ (println count))
+ (str (displayed (twice product)) (displayed (+ n (length xs))))))
+
+(: greet (-> string (#:greeting string) string))
+(defun (greet who #:greeting "hello") (str greeting ", " who))
+
+(defun (main) (println (area 2 3)) (println (greet "x")) 0)
+"""
+
+
+def renaming(server, tmp):
+ path = os.path.join(tmp, "renaming.bjo")
+ uri = "file://" + path
+ with open(path, "w") as f:
+ f.write(RENAMING)
+ found = server.diagnostics_after("textDocument/didOpen", uri, RENAMING)
+ expect("rename: the file checks", [d for d in found if d["severity"] == 1] == [], found)
+
+ def ask(method, needle, offset, new=None):
+ params = {"textDocument": {"uri": uri}, "position": position_of(RENAMING, needle, 0, offset)}
+ if new is not None:
+ params["newName"] = new
+ return server.send(method, params, request=True)
+
+ def renamed(needle, offset, new):
+ """The text with the rename applied, or the refusal's message."""
+ answer = ask("textDocument/rename", needle, offset, new)
+ if "error" in answer:
+ return None, answer["error"]["message"]
+ lines = RENAMING.split("\n")
+ edits = answer["result"]["changes"].get(uri, [])
+ for e in sorted(edits, key=lambda e: (-e["range"]["start"]["line"], -e["range"]["start"]["character"])):
+ a, b = e["range"]["start"], e["range"]["end"]
+ line = lines[a["line"]]
+ lines[a["line"]] = line[: a["character"]] + e["newText"] + line[b["character"] :]
+ return "\n".join(lines), None
+
+ prepared = ask("textDocument/prepareRename", "((n (helper", 2)["result"]
+ expect(
+ "rename: prepareRename gives the name and where it is",
+ prepared and prepared["placeholder"] == "n"
+ and prepared["range"]["start"] == position_of(RENAMING, "((n (helper", 0, 2),
+ prepared,
+ )
+
+ text, why = renamed("((n (helper", 2, "num")
+ expect(
+ "rename: a local, in an interpolation too, and not in quoted data",
+ text is not None
+ and "((num (helper 3))" in text
+ and "${num}" in text
+ and "'(n xs)" in text
+ and "(+ num (length xs))" in text,
+ why or text,
+ )
+
+ text, why = renamed("(def product", 5, "prod")
+ expect("rename: a def in a body", text is not None and "(def prod (* w h))" in text and "(displayed (twice prod))" in text,
+ why or text)
+
+ text, why = renamed("(defun (helper x)", 8, "double")
+ expect(
+ "rename: a top-level defun the module does not export, its signature and doc too",
+ text is not None
+ and "(:doc double" in text
+ and "(: double (-> int int))" in text
+ and "(defun (double x)" in text
+ and "((n (double 3))" in text,
+ why or text,
+ )
+
+ text, why = renamed("(defun (helper x)", 15, "k")
+ expect("rename: a parameter, and the (arg ...) of its function's doc",
+ text is not None and '(arg k "A number.")' in text and "(defun (helper k) (* 2 k))" in text,
+ why or text)
+
+ for label, needle, offset, new, wanted in [
+ ("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 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"),
+ ("a name that is not one", "((n (helper", 2, "two words", "is not a name"),
+ ("a rename the check refuses", "(defun (twice s)", 8, "when", "would give the program an error"),
+ ]:
+ text, why = renamed(needle, offset, new)
+ expect(f"rename refused: {label}", text is None and why and wanted in why, why or text)
+
+ # The renamed text is what the editor ends up with, and it checks.
+ text, _ = renamed("((n (helper", 2, "num")
+ server.change(uri, text, 2)
+ found = server.next_diagnostics(uri)
+ expect("rename: the renamed text checks", [d for d in found if d["severity"] == 1] == [], found)
+ server.diagnostics_after("textDocument/didClose", uri)
+
+
CHAIN_MACROS = """;; Two macros, one expanding to the other.
(import (std syntax-match))
@@ -842,6 +971,7 @@ with tempfile.TemporaryDirectory() as tmp:
completing(server, tmp)
locals_(server, tmp)
inferred(server, tmp)
+ renaming(server, tmp)
expanding(server, tmp)
answer = server.send("shutdown", request=True)