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>
This commit is contained in:
Linus Björnstam 2026-11-09 15:02:46 +01:00
parent 78d18c9854
commit 9a365b260b
5 changed files with 474 additions and 44 deletions

View file

@ -8,13 +8,15 @@ open System
open Bjolang
open BjolangLsp.Symbols
/// The heads the parsers recognise themselves, which no module defines. A
/// copy of the REPL's list in `Repl.fs`, which is private to it.
/// The heads the parsers recognise themselves, which no module defines. The
/// REPL's list in `Repl.fs`, which is private to it, and the declaration heads
/// `def/loop-clause`, `def/dimension`, `def/unit` and `def/prefix`.
let private specialForms =
[ "->"; "and"; "begin"; "bjo"; "bjoroutine"; "by-colour"; "case"; "cast"; "def"; "def*"; "def/hash-extend"
"def/dimension"; "def/grammar"; "def/loop-clause"; "def/prefix"; "def/unit"
"def/macro"; "def/mutable"; "def/pattern"; "def/trait"; "defbjo"; "defbjouble"; "defun"; "dyn"
"export"; "fun"; "if"; "impl"; "impl/extern"; "import"; "import/class"; "import/extern"; "include"
"let"; "let/mono"; "letrec"; "loop"; "match"; "module"; "not"; "or"; "parameterize"; "re-export"
"let"; "let/mono"; "letrec"; "loop"; "match"; "module"; "or"; "parameterize"; "re-export"
"record"; "record-ref"; "record-set"; "record-set!"; "seq"; "seql"; "set!"; "spawn"; "spawn-evt"
"spawn/daemon"; "spawn/detached"; "struct"; "struct-ref"; "struct-set"; "struct-set!"; "task->event"
"try"; "type"; "type-rec"; "unless"; "when"; "with-open"; "with-return"; "yield"; "yield-from" ]
@ -30,6 +32,7 @@ type ItemKind =
| Keyword = 14
| EnumMember = 20
| Struct = 22
| Constant = 21
type Item =
{ Label: string
@ -47,6 +50,7 @@ let private itemKind (k: Kind) =
| Kind.Field -> ItemKind.Field
| Kind.EnumMember -> ItemKind.EnumMember
| Kind.Struct -> ItemKind.Struct
| Kind.Constant -> ItemKind.Constant
| _ -> ItemKind.Variable
/// The word the cursor ends, as the start column of it on its line. A word

View file

@ -14,7 +14,9 @@ their own below; besides those, it does these:
as far as its head, `(defun` or `(match`.
- 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.
`impl`'s functions under them. A `def` or `def*` of a pattern gives the
names it binds, an `(:alias new old)` its new name, and a `def/grammar`
its productions, each a type with the cases of its `:or`.
- Go to definition (`textDocument/definition`): a local name goes to where
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
@ -92,11 +94,21 @@ where they were and are sent; the ones after it wait for the check. When it
has run, the server asks the editor to ask again
(`workspace/inlayHint/refresh`), if the editor says it can be asked.
Local names are the ones the parser's own forms bind: parameters of a
`defun`, `fun` and the other `def…` heads, `let`, `let*`, `letrec`,
`let/mono`, named `let` and `with-open` bindings, `with-return`, `match`
patterns, the clauses of `loop`, `seql` and a comprehension, and `def` or
`defun` inside a body, for the forms after it.
Local names are the ones the parser's own forms bind, with its scoping:
- parameters of a `defun`, `fun` and the other `def…` heads, a pattern
parameter `(Tuple a b)` included;
- `let`, `let*`, `letrec`, `let/mono`, named `let` and `with-open`
bindings (`with-open` one after another, as `let*`), a tuple of plain
names `((a b) pair)` included;
- `with-return`, and `match` patterns, where a `(:view step p)` binds what
`p` binds;
- the clauses of `loop`, `seql` and a comprehension, `:as` included, a
named `loop`'s name, and a `:subloop` form's `=> (name expr)`;
- `def`, `def*` and `defun` inside a body, also in a `(begin ...)`, for
the forms after it. A run of `def`s and `defun`s is one recursive group,
as the compiler makes it, so a local function sees itself and the
definitions after it in the run;
- the arms after a `def`'s `:leave`, over their bodies.
## Rename
@ -267,8 +279,9 @@ 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, and renaming an exported name, a keyword parameter, a
type, a constructor, a field or a trait method (see "Rename").
- References in other modules, 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

194
Scope.fs
View file

@ -35,10 +35,15 @@ let private binder name range shown 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)
| _ -> []
@ -60,21 +65,58 @@ let private parameters (owner: string) (args: SExpr list) : Binder list =
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) ...)`, `(defun (f ...) ...)` and their kin.
/// `(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) ->
match target with
| SAtom { Token = Symbol n; Range = r } -> [ binder n r whole "defined in this body" ]
| SList(SAtom { Token = Colon } :: SAtom { Token = Symbol n; Range = r } :: _, _) ->
[ binder n r whole "defined in this body" ]
| SList(names, _) -> names |> List.collect (patternNames "defined in this body" 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"
->
@ -89,7 +131,9 @@ let private letBindings (description: string) (bindings: SExpr list) : (Binder l
| 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) -> patternNames description whole pattern, 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,
@ -100,20 +144,47 @@ 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 k) }
| 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" ]
| SList(SAtom { Token = Keyword "subloop" } :: inner, _) -> loopNames inner
| SList([ SAtom { Token = Symbol n; Range = r }; _ ], whole) when
// A `:subloop`'s `=> (name expr)`, the only bare list among clauses.
not (Char.IsUpper n[0])
->
[ binder n r whole "a subloop's result" ]
// 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 =
@ -129,7 +200,7 @@ and private inList (line: int) (column: int) (env: Binder list) (items: SExpr li
match items with
| SAtom { Token = Symbol head } :: SList(SAtom { Token = Symbol name } :: args, _) :: _ when
head.StartsWith "def" && head <> "def" && head <> "def/mutable"
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.
@ -137,6 +208,29 @@ and private inList (line: int) (column: int) (env: Binder list) (items: SExpr li
| 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
@ -159,7 +253,8 @@ and private inList (line: int) (column: int) (env: Binder list) (items: SExpr li
let seen =
match head with
| "letrec" -> env @ all
| "let*" -> env @ named @ (bindings |> List.take i |> List.collect fst)
| "let*"
| "with-open" -> env @ named @ (bindings |> List.take i |> List.collect fst)
| _ -> env
inForm line column seen v))
@ -191,12 +286,71 @@ and private inList (line: int) (column: int) (env: Binder list) (items: SExpr li
| _ -> body env items
/// The names in scope in a body at the position: a definition scopes over
/// the forms after it.
/// 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
@ -209,7 +363,7 @@ and private inBody (line: int) (column: int) (env: Binder list) (forms: SExpr li
| Some found -> found
| None -> go (env @ defined) rest
go env forms
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

View file

@ -19,6 +19,7 @@ type Kind =
| Method = 6
| Field = 8
| EnumMember = 22
| Constant = 14
| Struct = 23
| Module = 2
@ -64,6 +65,72 @@ let private binderName (s: SExpr) : (string * Range) option =
| SList(SAtom { Token = Symbol n; Range = r } :: _, _) -> Some(n, r)
| _ -> None
/// The names a top-level `def` binder binds, as the compiler reads it:
/// - a name, or `(: name T)`;
/// - a list of plain names, `(a b)` or `(Tuple a b)`, a tuple;
/// - else a pattern: its lowercase symbols that are not a list's head. A
/// `(:view step p)` binds what `p` binds, and a comparison nothing.
let private defBinderNames (binder: SExpr) : (string * Range) list =
let rec patternNames (s: SExpr) =
match s with
| SAtom { Token = Symbol n; Range = r } when n <> "_" && not (Char.IsUpper n[0]) -> [ n, r ]
| SList([ SAtom { Token = Keyword "view" }; _; inner ], _) -> patternNames inner
| SList(SAtom { Token = Keyword("at-least" | "at-most" | "greater-than" | "less-than" | "between") } :: _, _) -> []
| SList(SAtom { Token = Symbol _ } :: args, _) -> args |> List.collect patternNames
| SList(items, _) -> items |> List.collect patternNames
| _ -> []
let plain =
function
| SAtom { Token = Symbol _ }
| SAtom { Token = Comma } -> true
| _ -> false
match binder with
| SAtom { Token = Symbol n; Range = r } -> [ n, r ]
| SList(SAtom { Token = Colon } :: SAtom { Token = Symbol n; Range = r } :: _, _) -> [ n, r ]
| SList((SAtom { Token = Symbol head } :: _) as names, _) when
(head = "Tuple" || not (Char.IsUpper head[0])) && List.forall plain names
->
names
|> List.choose (function
| SAtom { Token = Symbol n; Range = r } when n <> "Tuple" && n <> "_" -> Some(n, r)
| _ -> None)
| _ -> patternNames binder
/// The productions of a `def/grammar` after the first, which is the grammar's
/// own type, and the cases of each `(:or (: Case item) ...)`.
let private grammarMembers (grammar: string) (productions: SExpr list) : Symbol list * Symbol list =
let casesOf (production: string) (body: SExpr list) =
body
|> List.collect (function
| SList(SAtom { Token = Keyword "or" } :: alternatives, _) ->
alternatives
|> List.choose (function
| SList(SAtom { Token = Colon } :: SAtom { Token = Symbol n; Range = nr } :: _, cr) when Char.IsUpper n[0] ->
Some(symbol n production Kind.EnumMember cr nr cr [])
| _ -> None)
| _ -> [])
let production =
function
| SList(SAtom { Token = Symbol n; Range = nr } :: (_ :: _ as body), pr) when Char.IsUpper n[0] ->
Some(n, nr, body, pr)
| _ -> None
// As the compiler reads it: if the first form is a production, all are.
// Else the forms are the grammar's one production.
match productions with
| first :: _ when (production first).IsNone -> casesOf grammar productions, []
| _ ->
match List.choose production productions with
| [] -> [], []
| (_, _, firstBody, _) :: rest ->
casesOf grammar firstBody,
rest
|> List.map (fun (n, nr, body, pr) -> symbol n $"a production of `%s{grammar}`" Kind.Class pr nr pr (casesOf n body))
/// One `(: head body)` of a `type` form: the type, and its constructors or
/// fields.
let private typeDef (s: SExpr) : Symbol option =
@ -135,19 +202,37 @@ let rec private ofForm (form: SExpr) : Symbol list =
[ symbol $"impl %s{show head}" "" Kind.Module r (getRange head) (getRange head) (body |> List.collect ofForm) ]
| SList(SAtom { Token = Symbol("def" | "def/mutable" as head) } :: binder :: _, r) ->
match binder with
// `(def (a b) expr)`: every name in the destructuring list.
| SList(items, br) when (match items with
| SAtom { Token = Colon } :: _ -> false
| _ -> true) ->
items
|> List.choose (function
| SAtom { Token = Symbol n; Range = nr } -> Some(symbol n head Kind.Variable r nr br [])
| _ -> None)
| _ ->
binderName binder
|> Option.map (fun (n, nr) -> symbol n head Kind.Variable r nr (getRange binder) [])
|> Option.toList
defBinderNames binder |> List.map (fun (n, nr) -> symbol n head Kind.Variable r nr (getRange binder) [])
// `(def* (binder scrutinee ...) ...)`: each clause binds as a `def`.
| SList(SAtom { Token = Symbol "def*" } :: clauses, _) ->
clauses
|> List.collect (function
| SList(binder :: _ :: _, cr) ->
defBinderNames binder |> List.map (fun (n, nr) -> symbol n "def*" Kind.Variable cr nr (getRange binder) [])
| _ -> [])
// `(:alias new-name existing-name)`.
| SList([ SAtom { Token = Keyword "alias" }; SAtom { Token = Symbol n; Range = nr }; SAtom { Token = Symbol old } ], r) ->
[ symbol n $"an alias of `%s{old}`" Kind.Function r nr r [] ]
// `(def/grammar Name production ...)`: the grammar is a type, and so is
// each production after the first. `#:rules-only` is module metadata.
| SList(SAtom { Token = Symbol "def/grammar" } :: head :: productions, r) when
(match head with
| SAtom { Token = Keyword _ } -> false
| _ -> true)
->
match binderName head with
| Some(name, nr) ->
let cases, others = grammarMembers name productions
symbol name "grammar" Kind.Class r nr (getRange head) cases :: others
| None -> []
// `(def/dimension name ...)`, `(def/unit name value)`,
// `(def/prefix name value)`: names of units, not functions.
| SList(SAtom { Token = Symbol("def/dimension" | "def/unit" | "def/prefix" as head) } :: SAtom { Token = Symbol n; Range = nr } :: _, r) ->
[ symbol n head Kind.Constant r nr r [] ]
// `defun`, `defbjo`, `defbjouble`, `def/macro`, `def/pattern`, and any
// other `def…` form a library adds, which all put the name first.

View file

@ -552,6 +552,178 @@ def locals_(server, tmp):
server.diagnostics_after("textDocument/didClose", uri)
BINDERS = """(import (std prelude))
(: pairs (-> (List (Tuple int int)) (List int)))
(defun (pairs ps)
(list-map (fun ((Tuple a b)) (+ a b)) ps))
(: swap (-> (Tuple int int) int))
(defun (swap (Tuple p q))
(- q p))
(: unpack (-> (Tuple int int) int))
(defun (unpack pair)
(let (((lo hi) pair))
(- hi lo)))
(: countdown (-> int int))
(defun (countdown n)
(defun (down k) (if (= k 0) (up k) (down (- k 1))))
(defun (up k) k)
(down n))
(: spliced (-> int int))
(defun (spliced n)
(begin (def twice (* 2 n)))
(def* (thrice (* 3 n)) ((Some s) (first (list n)) :leave (other (+ other 1))))
(def (Some t) (first (list n)) :leave (missing (- missing 1)))
(+ twice thrice s t))
(: doubled (-> (List int) (List int)))
(defun (doubled xs)
(loop (:for x xs) (:as y (* 2 x)) (:acc acc (listing y)) => (first acc)))
(: named (-> (List int) int))
(defun (named xs)
(loop go (:for x xs) (:with total 0 total) (:do (go #:total (+ total x))) => total))
(: viewed (-> string int))
(defun (viewed s)
(match s
((:view string-length len) len)))
(: opened (-> string int))
(defun (opened p)
(with-open ((r (open p)) (w (wrap r)))
0))
(: averages (-> (List (List int)) (List int)))
(defun (averages rows)
(loop (:for row rows)
(:subloop (:for y row) (:acc s (summing y)) => (avg (* 2 s)))
(:acc out (listing avg))))
(: lengths (-> (List string) (List int)))
(defun (lengths ws)
{listing (string-length w) (:for w ws)})
"""
def binders_(server, tmp):
path = os.path.join(tmp, "binders.bjo")
uri = "file://" + path
with open(path, "w") as f:
f.write(BINDERS)
server.diagnostics_after("textDocument/didOpen", uri, BINDERS)
def definition(needle, offset, nth=0):
at = position_of(BINDERS, needle, nth, offset)
return server.send("textDocument/definition", {"textDocument": {"uri": uri}, "position": at}, request=True)["result"]
# (case, use, offset into it, binding, offset into it)
cases = [
("a fun's pattern parameter", "(+ a b)", 3, "((Tuple a b))", 8),
("a defun's pattern parameter", "(- q p)", 3, "(Tuple p q)", 9),
("a let's tuple of plain names, its first", "(- hi lo)", 6, "((lo hi)", 2),
("a local defun calls itself", "(down (- k", 1, "(defun (down k)", 8),
("a local defun calls a later one", "(up k) (down", 1, "(defun (up k)", 8),
("a def in a begin, after it", "(+ twice", 3, "(def twice", 5),
("a def* clause's name", "thrice s t", 0, "(thrice (* 3", 1),
("a def* clause's pattern", "s t))", 0, "((Some s)", 7),
("a pattern def, after it", "s t))", 2, "(def (Some t)", 11),
("a :leave arm of a def*", "(+ other", 3, "(other (+", 1),
("a :leave arm of a def", "(- missing", 3, "(missing (-", 1),
("an :as variable", "(listing y)", 9, "(:as y", 5),
("a named loop's name", "(go #:total", 1, "loop go", 5),
("a :view pattern's variable", "len)))", 0, "len) len", 0),
("with-open: a later value sees an earlier binding", "(wrap r)", 6, "((r (open", 2),
("a :subloop's => name", "(listing avg)", 9, "(avg (* 2 s))", 1),
]
for name, needle, offset, target, target_offset in cases:
d = definition(needle, offset)
ok = d and d["uri"] == uri and d["range"]["start"] == position_of(BINDERS, target, 0, target_offset)
expect("binder: " + name, ok, d)
# Not binders: a function called in a loop's =>, in a comprehension's
# head, and as a :view's step.
for name, needle, offset in [
("a function in a loop's =>", "(first acc)", 1),
("a function in a comprehension's head", "(string-length w)", 1),
("a :view's step", "string-length len", 0),
]:
d = definition(needle, offset)
expect("not a binder: " + name, d and d["uri"] != uri, d)
server.diagnostics_after("textDocument/didClose", uri)
DECLARATIONS = """(import (std prelude))
(def/grammar Proc
(Proc (List Item))
(Item (:or (: Sym symbol) (: Sub (Item ...)))))
(def (Some found) (first (list 1)))
(def (lo hi) (Tuple 1 2))
(def* (one 1) ((Tuple two three) (Tuple 2 3)))
(:alias uno one)
(def/unit ft "3048|10000 m")
(: use (-> int))
(defun (use)
(match (Sub Nil) ((Sym _) found) (_ (+ lo hi one two three uno))))
"""
def declarations(server, tmp):
path = os.path.join(tmp, "declarations.bjo")
uri = "file://" + path
with open(path, "w") as f:
f.write(DECLARATIONS)
server.diagnostics_after("textDocument/didOpen", uri, DECLARATIONS)
found = server.send("textDocument/documentSymbol", {"textDocument": {"uri": uri}}, request=True)["result"]
expect(
"outline: a grammar, pattern defs, def*, an alias and a unit",
names(found)
== [
("Proc", []),
("Item", [("Sym", []), ("Sub", [])]),
("found", []),
("lo", []),
("hi", []),
("one", []),
("two", []),
("three", []),
("uno", []),
("ft", []),
("use", []),
],
names(found),
)
def definition(needle, offset, nth=0):
at = position_of(DECLARATIONS, needle, nth, offset)
return server.send("textDocument/definition", {"textDocument": {"uri": uri}, "position": at}, request=True)["result"]
for name, needle, offset, target, target_offset in [
("a grammar's case", "(Sub Nil)", 1, "(: Sub", 3),
("a grammar's case in a pattern", "(Sym _)", 1, "(: Sym", 3),
("a pattern def's variable", "found) (_", 0, "(Some found)", 6),
("a def*'s pattern clause", "three uno", 0, "two three)", 4),
("an alias", "uno))))", 0, "(:alias uno", 8),
]:
d = definition(needle, offset)
ok = d and d["uri"] == uri and d["range"]["start"] == position_of(DECLARATIONS, target, 0, target_offset)
expect("top-level definition: " + name, ok, d)
at = position_of(DECLARATIONS, "(def/unit", 0, 4)
items = server.send("textDocument/completion", {"textDocument": {"uri": uri}, "position": at}, request=True)["result"]["items"]
labels = {i["label"] for i in items}
expect("completion: def/grammar and def/unit are special forms", {"def/grammar", "def/unit"} <= labels, sorted(labels)[:20])
server.diagnostics_after("textDocument/didClose", uri)
INFERRED = """(import (std prelude))
(: total (-> (List int) int))
@ -1306,6 +1478,8 @@ with tempfile.TemporaryDirectory() as tmp:
constrained(server, tmp)
completing(server, tmp)
locals_(server, tmp)
binders_(server, tmp)
declarations(server, tmp)
inferred(server, tmp)
fields(server, tmp)
renaming(server, tmp)