/// 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 } /// A field read, `(.x r)` or `(record-ref r x)`: the field, the form, the /// field's type there, and the record's type. type FieldUse = { Field: string Range: Range Type: string Record: string } type Index = { Uses: Use list Bounds: Bound list Fields: FieldUse list } let private empty = { Uses = []; Bounds = []; Fields = [] } /// 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() let bounds = ResizeArray() let fields = ResizeArray() let inFile (r: Range) = r.File <> "" && IO.Path.GetFullPath r.File = file // The file's own types by the names it writes: `Leg`, not `fields/Leg`. let ownQualifier = Text.RegularExpressions.Regex( @"(? t ownQualifier.Replace(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 } | TGetField(target, field) when inFile e.Range -> fields.Add { Field = field Range = e.Range Type = show e.Type Record = show target.Type } | 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 Fields = List.ofSeq fields } /// Each file's index, from its last check. let private byFile = Collections.Concurrent.ConcurrentDictionary() /// Each file's text as its last check read it: where an index's ranges are. let private checkedTexts = Collections.Concurrent.ConcurrentDictionary() /// 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.Value <- 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 && index.Fields.IsEmpty then index <- read env full decls) try check () finally Inference.observe.Value <- 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)) /// The field read written at `at`: the innermost one of `field` whose form /// holds it. let fieldAt (path: string) (field: string) (at: Range) : FieldUse option = indexOf path |> Option.bind (fun index -> index.Fields |> List.filter (fun f -> f.Field = field && holds at f.Range) |> List.sortBy (fun f -> size f.Range) |> List.tryHead)