lsp-bjolang/Types.fs
Linus Björnstam 471b49d9e4 Inferred types: in hovers, and as inlay hints
A check keeps what the compiler inferred, through Inference.observe, as
each use of a name with its type there and each binding with the type it
binds. A hover shows (: name type) for a local, and a generic function's
type at the use hovered. Inlay hints show the type after each local name
where it is bound and no type is written.

Hints before the first change since the last check are sent; the ones after
it wait for the check, which then asks the client to ask again. A hover runs
a check that is due first.

🤖 Generated with [ECA](https://eca.dev)

Co-Authored-By: eca-agent <git@eca.dev>
2026-10-22 12:58:19 +02:00

214 lines
8.1 KiB
FSharp

/// The types the compiler inferred for a file, from its last check.
///
/// The compiler hands each program it checked to `Inference.observe`, and the
/// names in it are read off with their types: each use of a name, at the type
/// it has there, and each binding, at the type it binds. A declaration that
/// failed to check has no types, so a name in it has none until it checks.
module BjolangLsp.Types
open System
open Bjolang
open Bjolang.Lexer
open Bjolang.TypedAST
/// A name as an expression, and the type it has there. `Generic` when it is
/// a generic binding, which this use instantiated.
type Use =
{ Name: string
Range: Range
Type: string
Generic: bool }
/// A name a form binds, and the type it binds it at. `Within` is the binding
/// form: where the name is written in it is the reader's business, and the
/// form holds it.
type Bound =
{ Name: string
Within: Range
Type: string }
type Index = { Uses: Use list; Bounds: Bound list }
let private empty = { Uses = []; Bounds = [] }
/// A name the compiler invented in place of one the program wrote: `x__3`,
/// a generated suspending copy `f__bjo`, and `unused__4` for `_`.
let private invented (name: string) =
name.EndsWith "__bjo" || name.StartsWith "unused__" || name.StartsWith "#"
/// What the program wrote: a renamed binder without its `__12`.
let private written (name: string) =
Text.RegularExpressions.Regex.Replace(name, @"__\d+$", "")
/// Reads `decls` into an index of the names in `file`, showing each type
/// with `env`'s registry: an associated type at a known implementor shows as
/// what it is there.
let private read (env: Env) (file: string) (decls: TDecl list) : Index =
let uses = ResizeArray<Use>()
let bounds = ResizeArray<Bound>()
let inFile (r: Range) = r.File <> "" && IO.Path.GetFullPath r.File = file
let show (t: HMType) =
let settled =
try
Unification.prune env.Registry t
with _ ->
t
DotNetInterop.showType settled
let bind (name: string) (within: Range) (t: HMType) =
if inFile within && not (invented name) then
bounds.Add
{ Name = written name
Within = within
Type = show t }
let rec pattern (p: TypedPattern) =
match p.Node with
| TPIdent n -> bind n p.Range p.Type
| TPAs(inner, n) ->
bind n p.Range p.Type
pattern inner
| TPList(ps, rest)
| TPVec(ps, rest)
| TPArray(ps, rest) ->
List.iter pattern ps
Option.iter pattern rest
| TPTuple ps
| TPConstruct(_, ps)
| TPOr ps
| TPAnd ps -> List.iter pattern ps
| TPRecord(_, fields) -> fields |> List.iter (snd >> pattern)
| TPApp(_, inner) -> pattern inner
| _ -> ()
let parameters (names: string list) (t: HMType) (within: Range) =
match Unification.prune env.Registry t with
| TFun(args, _, _) when args.Length = names.Length -> List.iter2 (fun n a -> bind n within a) names args
| _ -> ()
let node () (e: TypedExpr) =
match e.Node with
| TIdent(name, tArgs) when inFile e.Range && not (invented name) ->
uses.Add
{ Name = written name
Range = e.Range
Type = show e.Type
Generic = not tArgs.IsEmpty }
| TLet(name, _, _, value, _) -> bind name e.Range value.Type
| TLetMutable(name, value, _) -> bind name e.Range value.Type
| TLetRec(bindings, _) -> for (name, _, _, value) in bindings do bind name e.Range value.Type
| TLetTuple(names, value, _) ->
match Unification.prune env.Registry value.Type with
| TTuple items when items.Length = names.Length -> List.iter2 (fun n t -> bind n e.Range t) names items
| _ -> ()
| TLambda(names, _) -> parameters names e.Type e.Range
| TMatch(_, clauses) -> for c in clauses do pattern c.Pattern
| TDefMatch(binder, _, _, arms) ->
pattern binder
for a in arms do pattern a.Pattern
| _ -> ()
let expr (e: TypedExpr) = TypeVisitor.foldExpr node () e
let rec decl (d: TDecl) =
match d with
| TModule(_, inner, _) -> List.iter decl inner
| TImpl(_, _, _, _, _, _, methods, _) -> List.iter decl methods
| TDefun(name, _, _, _, _, _, _, _, _) when invented name -> ()
| TDefun(name, _, mandatory, keywords, rest, ret, effect, body, r) ->
let restArray = rest |> Option.map (fun (_, t) -> TCon("Array", [ t ])) |> Option.toList
let funType = TFun((mandatory |> List.map snd) @ (keywords |> List.map (fun (_, t, _) -> t)) @ restArray, ret, effect)
bind name r funType
for (n, t) in mandatory do
bind n r t
for (n, t, value) in keywords do
bind n r t
expr value
rest |> Option.iter (fun (n, t) -> bind n r (TCon("Array", [ t ])))
expr body
| TDef(name, value, t, r)
| TDefMutable(name, value, t, r) ->
bind name r t
expr value
| TDefTuple(names, value, t, r) ->
match Unification.prune env.Registry t with
| TTuple items when items.Length = names.Length -> List.iter2 (fun n t -> bind n r t) names items
| _ -> ()
expr value
| TDefPattern(p, value, _, _) ->
pattern p
expr value
| _ -> ()
List.iter decl decls
{ Uses = List.ofSeq uses; Bounds = List.ofSeq bounds }
/// Each file's index, from its last check.
let private byFile = Collections.Generic.Dictionary<string, Index>()
/// Each file's text as its last check read it: where an index's ranges are.
let private checkedTexts = Collections.Generic.Dictionary<string, string>()
/// The text of `path` its last check read, if it was checked.
let checkedText (path: string) : string option =
match checkedTexts.TryGetValue(IO.Path.GetFullPath path) with
| true, text -> Some text
| _ -> None
/// Runs `check` of `text`, the text of `path`, with the compiler handing over
/// what it checked, and keeps the index of the names in `path` as the file's.
/// A check that got no further than the reader leaves the file with none.
let recording (path: string) (text: string) (check: unit -> 'a) : 'a =
let full = IO.Path.GetFullPath path
let mutable index = empty
Inference.observe <-
Some(fun env decls ->
// The first program with names in the file is the file's: one
// checked before it is a dependency's.
if index.Uses.IsEmpty && index.Bounds.IsEmpty then
index <- read env full decls)
try
check ()
finally
Inference.observe <- None
byFile[full] <- index
checkedTexts[full] <- text
let private holds (inner: Range) (outer: Range) =
(inner.Start.Line > outer.Start.Line
|| (inner.Start.Line = outer.Start.Line && inner.Start.Column >= outer.Start.Column))
&& (inner.End.Line < outer.End.Line
|| (inner.End.Line = outer.End.Line && inner.End.Column <= outer.End.Column))
let private size (r: Range) = (r.End.Line - r.Start.Line) * 100000 + (r.End.Column - r.Start.Column)
let private indexOf (path: string) =
match byFile.TryGetValue(IO.Path.GetFullPath path) with
| true, index -> Some index
| _ -> None
/// The use of `name` written at `at`, if the last check typed it.
let useAt (path: string) (name: string) (at: Range) : Use option =
indexOf path
|> Option.bind (fun index ->
index.Uses
|> List.tryFind (fun u -> u.Name = name && u.Range.Start = at.Start))
/// The type `name`, written at `at` in its binding form, is bound at: the
/// innermost binding of that name that holds it.
let boundAt (path: string) (name: string) (at: Range) : string option =
indexOf path
|> Option.bind (fun index ->
index.Bounds
|> List.filter (fun b -> b.Name = name && holds at b.Within)
|> List.sortBy (fun b -> size b.Within)
|> List.tryHead
|> Option.map (fun b -> b.Type))