/// 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."))