From 78d18c985459bcee6cc137a9a6f1f8c6fa7be36ff7e4b2ee5882dd70a2cc6048 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20Bj=C3=B6rnstam?= Date: Tue, 3 Nov 2026 14:45:55 +0100 Subject: [PATCH] Hover on fields, and on locals of record types A field read shows the field's type and its declaration; a local of a record, struct or union type shows the type. Structs and opaque types get their symbols, and the file's own types drop their module qualifier. --- Hover.fs | 25 ++++++++++++++++++++++++ Program.fs | 35 ++++++++++++++++++++++++++++++++- README.md | 8 ++++++-- Symbols.fs | 9 ++++++--- Types.fs | 46 ++++++++++++++++++++++++++++++++++++++----- test/smoke.py | 54 +++++++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 166 insertions(+), 11 deletions(-) diff --git a/Hover.fs b/Hover.fs index 1f3a212..7d2bfb4 100644 --- a/Hover.fs +++ b/Hover.fs @@ -313,6 +313,31 @@ let builtin (name: string) : string option = yield "*Built into the compiler.*" ] |> String.concat "\n\n") +/// The hover for a field read, `(.x r)`: the field's type at this read, the +/// field as its type declares it, with its doc, and whose field it is. +/// `declared` is the record's or struct's definition, if it is found. +let field (name: string) (t: string) (record: string) (declared: Found option) : string = + let declaredField = + declared + |> Option.bind (fun d -> + d.Symbol.Children + |> List.tryFind (fun c -> c.Name = name) + |> Option.map (fun c -> { d with Symbol = c })) + + let file = + declared + |> Option.map (fun d -> $", in %s{IO.Path.GetFileName d.Symbol.NameRange.File}") + |> Option.defaultValue "" + + [ yield fence $"(: .%s{name} %s{t})" + match declaredField with + | Some f -> + yield fence (clip (f.Module.Slice f.Symbol.Signature)) + yield! Option.toList (doc f) + | None -> () + yield $"*A field of `%s{record}`%s{file}.*" ] + |> String.concat "\n\n" + /// The hover for `found`: its signature, where it is, and its doc. let text (found: Found) (inferred: string option) : string = let where = diff --git a/Program.fs b/Program.fs index f952dbc..8e510e1 100644 --- a/Program.fs +++ b/Program.fs @@ -183,15 +183,48 @@ let private localType (uri: string) (b: Scope.Binder) (at: Bjolang.Lexer.Range) | Some u -> Some u.Type | None -> Types.boundAt path b.Name b.Range +/// The record, struct or union a type as shown names, if this file sees its +/// definition: `Leg`, `module/Leg`, `(Pair int)`. +let private typeDefinition (uri: string) (shown: string) : Symbols.Found option = + let head = + if shown.StartsWith "(" then + shown.Substring(1).Split([| ' '; ')' |], StringSplitOptions.RemoveEmptyEntries) |> Array.tryHead + else + Some shown + + head + |> Option.map (fun h -> h.Substring(h.LastIndexOf '/' + 1)) + |> Option.filter (fun h -> h <> "" && Char.IsUpper h[0]) + |> Option.bind (Symbols.definition (uriToPath uri) (textOf uri)) + |> Option.filter (fun found -> found.Symbol.Kind = Symbols.Kind.Struct || found.Symbol.Kind = Symbols.Kind.Class) + let private hoverAt (uri: string) (line: int) (character: int) : JsonNode = let answer (text: string) (at: Bjolang.Lexer.Range) = JsonObject(dict [ "contents", markdownContent text; "range", range at ]) :> JsonNode match localAt uri line character with - | Some(b, at) -> answer (Hover.local b (localType uri b at) (Symbols.sliceOf (textOf uri) b.Shown)) at + | Some(b, at) -> + let inferred = localType uri b at + + // A record's or a struct's definition beside a local of its type. + let ofType = + inferred + |> Option.bind (typeDefinition uri) + |> Option.map (fun found -> Hover.text found None) + |> Option.toList + + answer (String.concat "\n\n---\n\n" (Hover.local b inferred (Symbols.sliceOf (textOf uri) b.Shown) :: ofType)) at | None -> match Symbols.nameAt (uriToPath uri) (textOf uri) (line + 1) character with | None -> null + // `(.x r)`: the field read, with its type there. + | Some(name, at) when + name.Length > 1 + && name.StartsWith "." + && (Types.fieldAt (uriToPath uri) (name.Substring 1) at).IsSome + -> + let f = (Types.fieldAt (uriToPath uri) (name.Substring 1) at).Value + answer (Hover.field f.Field f.Type f.Record (typeDefinition uri f.Record)) at | Some(name, at) -> let here = match Types.useAt (uriToPath uri) name at with diff --git a/README.md b/README.md index 4eebc2d..6247b18 100644 --- a/README.md +++ b/README.md @@ -36,8 +36,12 @@ their own below; besides those, it does these: `field` line. A builtin, which the compiler defines rather than a module, shows its type and its doc from the prelude's docs. A local name shows its binding as written, a typed parameter with its type, and what binds - it. A hover also shows the types the compiler inferred (see "Inferred - types"). + it; when its type is a record, a struct or a union this file sees, the + type's definition and doc follow. A field read, the `.x` of `(.x r)`, + shows the field's type there, the field as its type declares it with its + doc line, and whose field it is. A hover also shows the types the + compiler inferred (see "Inferred types"), the file's own types by the + names it writes rather than module-qualified. - Completion (`textDocument/completion`): the local names in scope, then the top-level names of the file and of every module it sees, the builtins, and the special forms, each name once and the nearest first. An diff --git a/Symbols.fs b/Symbols.fs index e921032..580bbda 100644 --- a/Symbols.fs +++ b/Symbols.fs @@ -68,7 +68,10 @@ let private binderName (s: SExpr) : (string * Range) option = /// fields. let private typeDef (s: SExpr) : Symbol option = match s with - | SList([ SAtom { Token = Colon }; head; body ], r) -> + // The body is last: `#:opaque` may come before it. + | SList(SAtom { Token = Colon } :: head :: (_ :: _ as rest), r) -> + let body = List.last rest + binderName head |> Option.map (fun (name, nr) -> let members, kind, detail = @@ -80,13 +83,13 @@ let private typeDef (s: SExpr) : Symbol option = |> Option.map (fun (n, cr) -> symbol n name Kind.EnumMember (getRange c) cr (getRange c) [])), Kind.Class, "union" - | SList(SAtom { Token = Symbol "Record" } :: fields, _) -> + | SList(SAtom { Token = Symbol("Record" | "Struct" as shape) } :: fields, _) -> fields |> List.choose (fun f -> binderName f |> Option.map (fun (n, fr) -> symbol n name Kind.Field (getRange f) fr (getRange f) [])), Kind.Struct, - "record" + (if shape = "Record" then "record" else "struct") | other -> [], Kind.Class, show other symbol name detail kind r nr r members) diff --git a/Types.fs b/Types.fs index ad29ec6..ccb74a6 100644 --- a/Types.fs +++ b/Types.fs @@ -27,9 +27,20 @@ type Bound = Within: Range Type: string } -type Index = { Uses: Use list; Bounds: Bound list } +/// 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 } -let private empty = { Uses = []; Bounds = [] } +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 `_`. @@ -46,8 +57,15 @@ let private written (name: string) = 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 - DotNetInterop.showType settled + ownQualifier.Replace(DotNetInterop.showType settled, "") let bind (name: string) (within: Range) (t: HMType) = if inFile within && not (invented name) then @@ -96,6 +114,12 @@ let private read (env: Env) (file: string) (decls: TDecl list) : Index = 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 @@ -147,7 +171,9 @@ let private read (env: Env) (file: string) (decls: TDecl list) : Index = | _ -> () List.iter decl decls - { Uses = List.ofSeq uses; Bounds = List.ofSeq bounds } + { Uses = List.ofSeq uses + Bounds = List.ofSeq bounds + Fields = List.ofSeq fields } /// Each file's index, from its last check. let private byFile = Collections.Generic.Dictionary() @@ -172,7 +198,7 @@ let recording (path: string) (text: string) (check: unit -> 'a) : 'a = 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 + if index.Uses.IsEmpty && index.Bounds.IsEmpty && index.Fields.IsEmpty then index <- read env full decls) try @@ -212,3 +238,13 @@ let boundAt (path: string) (name: string) (at: Range) : string option = |> 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) diff --git a/test/smoke.py b/test/smoke.py index a476968..be28517 100755 --- a/test/smoke.py +++ b/test/smoke.py @@ -691,6 +691,59 @@ def inferred(server, tmp): server.diagnostics_after("textDocument/didClose", uri) +FIELDS = """(type (: Leg (Record (: distance double) (: name string)))) +(type (: Pos (Struct (: x int) (: y int)))) + +(:doc Leg + (summary "A part of a trip.") + (field distance "How far it goes.") + (field name "Where it ends.")) + +(: far? (-> Leg bool)) +(defun (far? leg) (> (.distance leg) 10.0)) + +(: across (-> Pos int)) +(defun (across p) (+ (.x p) (.y p))) +""" + + +def fields(server, tmp): + path = os.path.join(tmp, "fields.bjo") + uri = "file://" + path + with open(path, "w") as f: + f.write(FIELDS) + found = server.diagnostics_after("textDocument/didOpen", uri, FIELDS) + errors = [d for d in found if d["severity"] == 1] + expect("fields: the file checks", errors == [], json.dumps(errors, indent=1)) + + def hover(needle, offset=1): + at = position_of(FIELDS, needle, 0, offset) + h = server.send("textDocument/hover", {"textDocument": {"uri": uri}, "position": at}, request=True)["result"] + return h and h["contents"]["value"] + + h = hover("(.distance leg)", 2) + expect( + "fields hover: a record field's type, its declaration and its doc", + h + and "(: .distance double)" in h + and "(: distance double)" in h + and "How far it goes." in h + and "A field of `Leg`" in h, + h, + ) + h = hover("(.y p)", 2) + expect("fields hover: a struct's field", h and "(: .y int)" in h and "A field of `Pos`" in h, h) + h = hover("leg) 10.0", 0) + expect( + "fields hover: a local of a record type shows the record", + h and "(: leg Leg)" in h and "(: Leg (Record (: distance double) (: name string)))" in h and "A part of a trip." in h, + h, + ) + h = hover("p) (.y", 0) + expect("fields hover: a local of a struct type shows the struct", h and "(: Pos (Struct" in h, h) + server.diagnostics_after("textDocument/didClose", uri) + + RENAMING = """(export area) (:doc helper @@ -1254,6 +1307,7 @@ with tempfile.TemporaryDirectory() as tmp: completing(server, tmp) locals_(server, tmp) inferred(server, tmp) + fields(server, tmp) renaming(server, tmp) referencing(server, tmp) acting(server, tmp)