lsp-bjolang/Scope.fs
Linus Björnstam 9a365b260b Local names and top-level names as the compiler binds them
- Scope: a run of body defs and defuns is one recursive group; pattern
  parameters; a let of plain names; with-open in sequence; :as; a named
  loop's name; def*, begin and :leave arms. A :view's step, a loop's =>
  call and a comprehension's head are not binders.
- Symbols: a pattern def or def* gives what it binds; :alias; a
  def/grammar's productions and cases; unit forms as constants.
- Completion: the special forms as the compiler has them now.

🤖 Generated with [ECA](https://eca.dev) (anthropic/claude-opus-5-5)

Co-Authored-By: eca-agent <git@eca.dev>
2026-11-09 15:02:46 +01:00

377 lines
18 KiB
FSharp

/// The local names in scope at a position: parameters, `let` bindings,
/// pattern variables, loop variables, and definitions inside a body.
///
/// Read off the forms as the reader gives them, as `Symbols` reads the
/// top-level names, with the scoping rules of the forms the parser knows. A
/// macro's binding forms are not known, so a name a macro binds is not seen;
/// the parser's own forms cover most of what is written.
module BjolangLsp.Scope
open System
open Bjolang.Lexer
open Bjolang.Ast
type Binder =
{ Name: string
/// Where the name is written in its binding form.
Range: Range
/// What a hover shows of the binding: the parameter with its type, the
/// `let` binding with its value, the pattern.
Shown: Range
/// What binds it, for a hover: "a parameter of `f`", "bound by `let`".
Description: string }
/// Whether `r` holds the position. The end is included, so a cursor right
/// after a name is in it, as it is while the name is being typed.
let private holds (line: int) (column: int) (r: Range) =
(line > r.Start.Line || (line = r.Start.Line && column >= r.Start.Column))
&& (line < r.End.Line || (line = r.End.Line && column <= r.End.Column))
let private binder name range shown description =
{ Name = name
Range = range
Shown = shown
Description = description }
/// The names a pattern binds: every lowercase symbol that is not the head of
/// a list, as the head is the constructor.
///
/// A `(:view step p)` binds what `p` binds: `step` is an expression. A
/// comparison, `(:between lo hi)` and its kin, binds nothing.
let rec private patternNames (description: string) (shown: Range) (s: SExpr) : Binder list =
match s with
| SAtom { Token = Symbol n; Range = r } when n <> "_" && n <> "else" && not (Char.IsUpper n[0]) ->
[ binder n r shown description ]
| SList([ SAtom { Token = Keyword "view" }; _; inner ], _) -> patternNames description shown inner
| SList(SAtom { Token = Keyword("at-least" | "at-most" | "greater-than" | "less-than" | "between") } :: _, _) -> []
| SList(SAtom { Token = Symbol _ } :: args, _) -> args |> List.collect (patternNames description shown)
| SList(items, _) -> items |> List.collect (patternNames description shown)
| _ -> []
/// The parameters of an argument list: `x`, `(: x Type)`, `#:rest xs`, and a
/// keyword parameter `(#:key default)` or `#:key default`, which binds `key`.
let private parameters (owner: string) (args: SExpr list) : Binder list =
let description = if owner = "" then "a parameter" else $"a parameter of `%s{owner}`"
let rec go (args: SExpr list) =
match args with
| [] -> []
| SAtom { Token = Symbol n; Range = r } :: rest -> binder n r r description :: go rest
| (SList([ SAtom { Token = Colon }; SAtom { Token = Symbol n; Range = r }; _ ], whole)) :: rest ->
binder n r whole description :: go rest
| SList([ SAtom { Token = Keyword k; Range = r }; _ ], whole) :: rest ->
binder k r whole (description + ", by keyword") :: go rest
| SAtom { Token = Keyword "rest" } :: SAtom { Token = Symbol n; Range = r } :: rest ->
binder n r r (description + ", the rest of the arguments") :: go rest
| SAtom { Token = Keyword k; Range = r } :: value :: rest ->
binder k r (getRange value) (description + ", by keyword") :: go rest
// A pattern, `(Tuple a b)`, and a typed one, `(: (Tuple a b) T)`.
| (SList(SAtom { Token = Symbol head } :: _, whole) as pattern) :: rest when Char.IsUpper head[0] ->
patternNames (description + ", from its pattern") whole pattern @ go rest
| SList([ SAtom { Token = Colon }; (SList _ as pattern); _ ], whole) :: rest ->
patternNames (description + ", from its pattern") whole pattern @ go rest
| _ :: rest -> go rest
go args
/// The names of a list of plain names, `(a b)` or `(Tuple a b)`, which `let`
/// and `def` read as a tuple. `None` for any other form. As the compiler's
/// `isPlainDefBinder`: the head is `Tuple` or lowercase.
let private plainNames (description: string) (shown: Range) (s: SExpr) : Binder list option =
match s with
| SList((SAtom { Token = Symbol head } :: _) as names, _) when
(head = "Tuple" || not (Char.IsUpper head[0]))
&& names
|> List.forall (function
| SAtom { Token = Symbol _ }
| SAtom { Token = Comma } -> true
| _ -> false)
->
names
|> List.choose (function
| SAtom { Token = Symbol n; Range = r } when n <> "Tuple" && n <> "_" -> Some(binder n r shown description)
| _ -> None)
|> Some
| _ -> None
/// The names a `def` binder binds: a name, `(: name T)`, a tuple of plain
/// names, or a pattern.
let private defBinderNames (description: string) (shown: Range) (target: SExpr) : Binder list =
match target with
| SAtom { Token = Symbol n; Range = r } -> [ binder n r shown description ]
| SList(SAtom { Token = Colon } :: SAtom { Token = Symbol n; Range = r } :: _, _) -> [ binder n r shown description ]
| _ ->
match plainNames description shown target with
| Some names -> names
| None -> patternNames description shown target
/// What a body form defines for the forms after it: `(def x ...)`,
/// `(def (: x T) ...)`, a `def` of a tuple or a pattern, each clause of a
/// `def*`, `(defun (f ...) ...)` and their kin.
let private definedBy (form: SExpr) : Binder list =
match form with
| SList(SAtom { Token = Symbol("def" | "def/mutable") } :: target :: _, whole) ->
defBinderNames "defined in this body" whole target
| SList(SAtom { Token = Symbol "def*" } :: clauses, _) ->
clauses
|> List.collect (function
| SList(target :: _ :: _, whole) -> defBinderNames "defined by a `def*` in this body" whole target
| _ -> [])
| SList(SAtom { Token = Symbol head } :: SList(SAtom { Token = Symbol n; Range = r } :: _, sig') :: _, _) when
head = "defun" || head = "defbjo" || head = "defbjouble"
->
[ binder n r sig' $"a `%s{head}` in this body" ]
| _ -> []
/// The bindings of a `let`'s list, each as its names and its value.
let private letBindings (description: string) (bindings: SExpr list) : (Binder list * SExpr option) list =
bindings
|> List.map (fun b ->
match b with
| SList([ SAtom { Token = Symbol n; Range = r }; value ], whole) -> [ binder n r whole description ], Some value
| SList([ SList(SAtom { Token = Colon } :: SAtom { Token = Symbol n; Range = r } :: _, _); value ], whole) ->
[ binder n r whole description ], Some value
| SList([ pattern; value ], whole) ->
(plainNames description whole pattern |> Option.defaultWith (fun () -> patternNames description whole pattern)),
Some value
| other -> [], Some other)
/// The names a loop's clauses bind, which its other clauses, its `=>` and,
/// in a comprehension, the expression before them see. A loop variable is in
/// scope across the whole form rather than only after its clause; that is
/// more than the loop allows, and enough to find a name by.
let rec private loopNames (items: SExpr list) : Binder list =
items
|> List.collect (fun item ->
match item with
| SList(SAtom { Token = Keyword("for" | "with" | "let" | "when-let" | "finish-let" | "break-let" | "as" as k) }
:: pattern
:: _,
whole) -> patternNames $"bound by a `:%s{k}` clause" whole pattern
| SList(SAtom { Token = Keyword "acc" } :: SAtom { Token = Symbol n; Range = r } :: _, whole) ->
[ binder n r whole "a loop accumulator" ]
// A `:subloop` form's `=> (name expr)` is its last two forms.
| SList(SAtom { Token = Keyword "subloop" } :: inner, _) ->
match List.rev inner with
| (SList([ SAtom { Token = Symbol n; Range = r }; _ ], whole)) :: SAtom { Token = Symbol "=>" } :: clauses ->
loopNames (List.rev clauses) @ [ binder n r whole "a subloop's result" ]
| _ -> loopNames inner
| _ -> [])
/// Whether a `def`'s failure part has `:leave`, after which every form is an
/// arm.
let private hasLeave (tail: SExpr list) =
tail
|> List.exists (function
| SAtom { Token = Keyword "leave" } -> true
| _ -> false)
/// The forms of a definition run, with each non-empty `(begin ...)` spliced
/// in, as the compiler reads a body.
let rec private spliced (forms: SExpr list) : SExpr list =
forms
|> List.collect (function
| SList(SAtom { Token = Symbol "begin" } :: (_ :: _ as inner), _) -> spliced inner
| form -> [ form ])
/// Whether a body form is in a run of definitions that the compiler makes
/// one recursive group: `(def name value)`, `(def (: name T) value)`,
/// `(defun (f ...) ...)`, and a declaration `(: name T)`.
let private inRun (form: SExpr) =
match form with
| SList([ SAtom { Token = Symbol "def" }; SAtom { Token = Symbol _ }; _ ], _)
| SList([ SAtom { Token = Symbol "def" }; SList([ SAtom { Token = Colon }; SAtom { Token = Symbol _ }; _ ], _); _ ], _)
| SList(SAtom { Token = Symbol "defun" } :: SList(SAtom { Token = Symbol _ } :: _, _) :: _, _)
| SList(SAtom { Token = Colon } :: SAtom { Token = Symbol _ } :: _, _) -> true
| _ -> false
/// The names in scope at the position, innermost last, inside `s`; `None`
/// if the position is not in it.
let rec private inForm (line: int) (column: int) (env: Binder list) (s: SExpr) : Binder list option =
if not (holds line column (getRange s)) then
None
else
match s with
| SAtom _ -> Some env
| SList(items, _) -> Some(inList line column env items)
and private inList (line: int) (column: int) (env: Binder list) (items: SExpr list) : Binder list =
let body env forms = inBody line column env forms
match items with
| SAtom { Token = Symbol head } :: SList(SAtom { Token = Symbol name } :: args, _) :: _ when
head.StartsWith "def" && head <> "def" && head <> "def/mutable" && head <> "def*"
->
// `(defun (f x y) body...)`: the parameters over the whole form, the
// head included, so that a parameter is found where it is written.
body (env @ parameters name args) items
| SAtom { Token = Symbol("fun" | "bjoroutine") } :: SList(args, _) :: _ -> body (env @ parameters "" args) items
// `(def pattern scrutinee ... :leave arm ...)`: an arm binds its pattern
// over its body, as a `match` arm does. A `def*` clause the same.
| SAtom { Token = Symbol "def" } :: _ :: _ :: tail when hasLeave tail ->
inLeaveArms line column env tail |> Option.defaultWith (fun () -> body env items)
| SAtom { Token = Symbol "def*" } :: clauses ->
clauses
|> List.tryPick (function
| SList(_ :: _ :: tail, r) when hasLeave tail && holds line column r -> inLeaveArms line column env tail
| _ -> None)
|> Option.defaultWith (fun () -> body env items)
// `(let/mono name value body ...)`, which the compiler writes.
| SAtom { Token = Symbol "let/mono" } :: SAtom { Token = Symbol n; Range = r } :: value :: bodyForms ->
match inForm line column env value with
| Some found -> found
| None ->
let own = binder n r r "bound by `let/mono`"
if holds line column r then env @ [ own ] else body (env @ [ own ]) bodyForms
// `(loop name clause ...)`: the name is called in the last `:do`.
| SAtom { Token = Symbol "loop" } :: SAtom { Token = Symbol n; Range = r } :: rest when n <> "=>" ->
body (env @ [ binder n r r "the name of a named `loop`, called to go on" ] @ loopNames rest) items
| SAtom { Token = Symbol("let" | "let*" | "letrec" | "let/mono" | "with-open" as head) } :: rest ->
let named, bindingList, bodyForms =
match rest with
| SAtom { Token = Symbol n; Range = r } :: SList(bs, _) :: forms ->
[ binder n r r "the name of a named `let`, called to loop" ], bs, forms
| SList(bs, _) :: forms -> [], bs, forms
| forms -> [], [], forms
let bindings = letBindings $"bound by `%s{head}`" bindingList
let all = named @ (bindings |> List.collect fst)
// A value sees what is around the `let`, and in a `let*` or a
// `letrec` the bindings before it, or all of them.
let inValue =
bindings
|> List.indexed
|> List.tryPick (fun (i, (_, value)) ->
value
|> Option.bind (fun v ->
let seen =
match head with
| "letrec" -> env @ all
| "let*"
| "with-open" -> env @ named @ (bindings |> List.take i |> List.collect fst)
| _ -> env
inForm line column seen v))
match inValue with
| Some found -> found
| None ->
let inBinders = all |> List.exists (fun b -> holds line column b.Range)
if inBinders then env @ all else body (env @ all) bodyForms
| SAtom { Token = Symbol "with-return" } :: SAtom { Token = Symbol n; Range = r } :: forms ->
body (env @ [ binder n r r "the escape of a `with-return`, called to return" ]) forms
| SAtom { Token = Symbol "match" } :: scrutinee :: arms ->
match inForm line column env scrutinee with
| Some found -> found
| None ->
arms
|> List.tryPick (fun arm ->
match arm with
| SList(pattern :: _, _) ->
let bound = patternNames "bound by a `match` pattern" (getRange pattern) pattern
inForm line column (env @ bound) arm
| _ -> inForm line column env arm)
|> Option.defaultValue env
| SAtom { Token = Symbol("loop" | "seql" | "comprehension") } :: rest -> body (env @ loopNames rest) items
| _ -> body env items
/// The names in scope at the position in the arms after a `def`'s `:leave`,
/// or `None` if it is not in one.
and private inLeaveArms (line: int) (column: int) (env: Binder list) (tail: SExpr list) : Binder list option =
let arms =
match
tail
|> List.skipWhile (function
| SAtom { Token = Keyword "leave" } -> false
| _ -> true)
with
| _ :: arms -> arms
| [] -> []
arms
|> List.tryPick (fun arm ->
match arm with
| SList(pattern :: _, _) ->
let bound = patternNames "bound by a `:leave` arm's pattern" (getRange pattern) pattern
inForm line column (env @ bound) arm
| _ -> None)
/// The names in scope in a body at the position:
/// - A definition scopes over the forms after it.
/// - A run of `def`s and `defun`s is one recursive group, as the compiler
/// makes it: each sees every name of the run, a `def`'s value all but its
/// own. A name defined twice ends the run.
/// - A `(begin ...)` is spliced into the body.
and private inBody (line: int) (column: int) (env: Binder list) (forms: SExpr list) : Binder list =
let rec takeRun (seen: Set<string>) (forms: SExpr list) =
match forms with
| form :: rest when inRun form ->
let names = definedBy form |> List.map (fun b -> b.Name)
if names |> List.exists seen.Contains then
[], forms
else
let run, after = takeRun (Set.union seen (Set.ofList names)) rest
form :: run, after
| _ -> [], forms
let rec go (env: Binder list) (forms: SExpr list) =
match forms with
| [] -> env
| form :: _ when inRun form ->
let run, rest = takeRun Set.empty forms
let defined = run |> List.collect definedBy
match defined |> List.tryFind (fun b -> holds line column b.Range) with
| Some own -> env @ [ own ]
| None ->
let inMember =
run
|> List.tryPick (fun member' ->
let seen =
match member' with
| SList(SAtom { Token = Symbol "def" } :: _, _) ->
let own = definedBy member' |> List.map (fun b -> b.Name)
defined |> List.filter (fun b -> not (List.contains b.Name own))
| _ -> defined
inForm line column (env @ seen) member')
match inMember with
| Some found -> found
| None -> go (env @ defined) rest
| form :: rest ->
let defined = definedBy form
// On a name the form defines, that is where the name is bound.
// Anywhere else in the form, the name is not in scope yet.
match defined |> List.tryFind (fun b -> holds line column b.Range) with
| Some own -> env @ [ own ]
| None ->
match inForm line column env form with
| Some found -> found
| None -> go (env @ defined) rest
go env (spliced forms)
/// The local names in scope at `line` (1-based) and `column` (0-based) among
/// a file's top-level forms, innermost last. A top-level definition is not
/// among them: `Symbols` has those.
let at (forms: SExpr list) (line: int) (column: int) : Binder list =
forms |> List.tryPick (inForm line column []) |> Option.defaultValue []
/// The binding `name` refers to at the position, if it is a local one: the
/// innermost of that name.
let find (forms: SExpr list) (line: int) (column: int) (name: string) : Binder option =
at forms line column |> List.tryFindBack (fun b -> b.Name = name)