From ec86a79a1a3cb4e76ed795b3d053872a397ff314 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Sat, 5 Dec 2026 17:28:59 +0300 Subject: [PATCH] Report full function extents from the stock observer The observer emits an optional extent inside each proven definition span from the body's last statement finish (the C++ frontend does not set function_end_locus). The occurrence decoder binds it to the same snapshot through the negotiated encoding and rejects malformed extents; call hierarchy attributes nested calls to the enclosing extent. A real stdio session reported both inner calls as outgoing from outer, and the observer and occurrence corpora still pass. --- docs/agent-workflow/LSP-PARITY.md | 2 +- docs/agent-workflow/STATE.md | 2 +- docs/agent-workflow/VERIFICATION.md | 21 +++++ .../frontend/gcc-observer/Observer.cpp | 83 ++++++++++++++++++- include/vls/semantic/Occurrences.hpp | 3 + src/features/CallHierarchy.cpp | 7 +- src/semantic/EditorDiagnostics.cpp | 12 ++- src/semantic/Occurrences.cpp | 70 +++++++++++++++- .../corpus/frontend/verify-stock-observer.py | 18 +++- tests/features/CallHierarchyTests.cpp | 11 +++ tests/semantic/OccurrenceTests.cpp | 21 +++++ 11 files changed, 239 insertions(+), 11 deletions(-) diff --git a/docs/agent-workflow/LSP-PARITY.md b/docs/agent-workflow/LSP-PARITY.md index b38db63..28903b7 100644 --- a/docs/agent-workflow/LSP-PARITY.md +++ b/docs/agent-workflow/LSP-PARITY.md @@ -34,7 +34,7 @@ missing part. Updated December 5, 2026 after semantic tokens and inlay hints. | Compiler-native completion with visibility proof | index-backed completion is explicitly incomplete | | Overload-set signature help | only the selected occurrence's signature is available | | textDocument/formatting | needs a plan | -| callHierarchy / typeHierarchy | prepare, incomingCalls and outgoingCalls are implemented and served; outgoing results need full function extents from the compiler (the observed span is the declarator only). Type hierarchy is open. | +| callHierarchy / typeHierarchy | prepare, incomingCalls and outgoingCalls are implemented and served; outgoing calls are verified over stdio now that the observer reports full function extents. Type hierarchy is open. | | textDocument/codeLens, executeCommand | command surface not designed | | Client-side application of server-issued workspace edits | rename and code actions return edits the clients apply directly | | Applying multi-file renames through client buffers | plans can be ready; application is client work | diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 7df8c0d..008a7bd 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -102,7 +102,7 @@ ingests occurrence facts after each analysis and the server answers Hash.hpp definition through it. Real persistence migrations and cross-file rename coverage remain open. -Index-backed completion (roadmap 14 first slice) is implemented: `include/vls/features/Completion.hpp`, `src/features/Completion.cpp` and registered `vls_feature_tests` cover prefix extraction, filtering with replacement ranges, label+kind deduplication, deterministic ranking and bounds. `Server.cpp` advertises `completionProvider` and answers `textDocument/completion` from the symbol index through `EditorDiagnostics::completion`; a real stdio session with the stock observer returned `fnv1a64` and `fnv1a64_update` at a real call site. Every result is marked incomplete because the index does not prove visibility. Signature help is now served from the compiler-provided occurrence signature (parameter labels and ranges, active parameter, innermost call selection) and advertised by the server. Document symbols are served from the index by path and document highlights from same-binding occurrence facts; both are advertised and were exercised over stdio with the stock observer. Selection and folding ranges are served from immutable document snapshots with registered bounded cores. Code actions now offer the compiler's own suggested fixes (quickfix) from retained published diagnostics, with SARIF fix decoding bound to the owner snapshot. Semantic tokens encode the proven call occurrences with a bounded one-type legend. Inlay hints project parameter types from the occurrence signature at each argument start. Workspace file-operation notifications invalidate dependent index contexts and re-queue open documents. A will-rename request returns the include updates for open documents. Call hierarchy serves prepare and incoming calls (grouped by enclosing definition or explicitly by file) from the stock call facts. Outgoing calls are served too, but the observer's declarator-only definition span limits attribution to the core tests for now. Compiler-native completion with visibility proof and deferred detail resolution remain open. +Index-backed completion (roadmap 14 first slice) is implemented: `include/vls/features/Completion.hpp`, `src/features/Completion.cpp` and registered `vls_feature_tests` cover prefix extraction, filtering with replacement ranges, label+kind deduplication, deterministic ranking and bounds. `Server.cpp` advertises `completionProvider` and answers `textDocument/completion` from the symbol index through `EditorDiagnostics::completion`; a real stdio session with the stock observer returned `fnv1a64` and `fnv1a64_update` at a real call site. Every result is marked incomplete because the index does not prove visibility. Signature help is now served from the compiler-provided occurrence signature (parameter labels and ranges, active parameter, innermost call selection) and advertised by the server. Document symbols are served from the index by path and document highlights from same-binding occurrence facts; both are advertised and were exercised over stdio with the stock observer. Selection and folding ranges are served from immutable document snapshots with registered bounded cores. Code actions now offer the compiler's own suggested fixes (quickfix) from retained published diagnostics, with SARIF fix decoding bound to the owner snapshot. Semantic tokens encode the proven call occurrences with a bounded one-type legend. Inlay hints project parameter types from the occurrence signature at each argument start. Workspace file-operation notifications invalidate dependent index contexts and re-queue open documents. A will-rename request returns the include updates for open documents. Call hierarchy serves prepare and incoming calls (grouped by enclosing definition or explicitly by file) from the stock call facts. Outgoing calls are served and verified: the stock observer now reports full function extents, so nested calls are attributed to the enclosing definition. Compiler-native completion with visibility proof and deferred detail resolution remain open. The reflection provenance representation (roadmap 12 first slice) is implemented as a bounded library with a registered suite: innermost-first diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index 808dc8b..38a3826 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -79,6 +79,27 @@ the upgraded snapshot (keeping `snapshot.prev.json`) and rewrites a legacy about 25-30s in a Debug build (it passed VBS at ~27s); the full CMake run then passed 18/18. +## December 5 full function extents from the stock observer + +The stock occurrence observer now reports an optional `extent` inside each +proven definition span: the body's last statement finish location, because the +C++ frontend never sets `function_end_locus`. The occurrence decoder binds it to +the same snapshot through the negotiated encoding (malformed extents reject the +report), and call hierarchy attributes nested calls to the enclosing definition +extent. The corpus verifier validates the extent shape and ordering. + +Real stdio session with nested calls: +``` +prepare: [('outer', 'main.cpp', {'start': {'line': 1, 'character': 4}, 'end': {'line': 1, 'character': 9}})] +incoming: [('main.cpp', 1, 1)] +outgoing: [('inner', 2)] +``` +`outgoing` now reports both `inner()` calls from `outer`, and `inner` remains +file-level for its caller because `main` is never a call target. The stock +observer corpus passed all cases and the stock occurrence corpus still selected +the `string_view`/`byte_span` overloads. All 18 native suites and all 18 CMake +tests passed. + ## December 5 outgoing call hierarchy `callHierarchy/outgoingCalls` is wired through diff --git a/experiments/frontend/gcc-observer/Observer.cpp b/experiments/frontend/gcc-observer/Observer.cpp index d8a8c84..e957a3f 100644 --- a/experiments/frontend/gcc-observer/Observer.cpp +++ b/experiments/frontend/gcc-observer/Observer.cpp @@ -15,6 +15,7 @@ #include "diagnostic.h" #include "function.h" #include "input.h" +#include "tree-iterator.h" #include #include @@ -63,6 +64,8 @@ struct body_entry { char path[max_path + 1]{}; bool definition{}; bool conflict{}; + bool has_extent{}; + unsigned end_line{}, end_byte{}; }; struct use_entry { @@ -371,6 +374,64 @@ bool token_span(location_t token, unsigned length, const char *expected, span &o return true; } +// One physical position in an admitted primary file, in the same byte space as +// token_span (the first-line BOM is restored). Ordinary maps only. +bool point_position(location_t location, const char *&path_out, unsigned &line, unsigned &column) { + const location_t pure = get_pure_location(location); + if (RESERVED_LOCATION_P(pure) || from_macro_expansion_at(pure)) { + return false; + } + const line_map *raw_map = linemap_lookup(line_table, pure); + if (!raw_map || !MAP_ORDINARY_P(raw_map)) { + return false; + } + const line_map_ordinary *map = linemap_check_ordinary(raw_map); + if (map->sysp || !map->to_file) { + return false; + } + file_entry *file = file_for(map->to_file); + if (!file) { + return false; + } + line = SOURCE_LINE(map, pure); + column = SOURCE_COLUMN(map, pure); + if (!line || !column || column == UINT_MAX) { + return false; + } + const bool bom = line == 1 && file->size >= 3 && file->data[0] == 0xEF && + file->data[1] == 0xBB && file->data[2] == 0xBF; + if (bom) { + column += 3; + } + path_out = file->path; + return true; +} + +// End of the last statement in a saved function body. The C++ frontend does not +// set function_end_locus, so the body itself is the authority. +location_t last_body_location(tree node) { + if (!node) { + return UNKNOWN_LOCATION; + } + if (TREE_CODE(node) == BIND_EXPR) { + return last_body_location(BIND_EXPR_BODY(node)); + } + if (TREE_CODE(node) == STATEMENT_LIST) { + for (tree_stmt_iterator i = tsi_last(node); !tsi_end_p(i); tsi_prev(&i)) { + if (location_t location = last_body_location(tsi_stmt(i)); + location != UNKNOWN_LOCATION) { + return location; + } + } + return UNKNOWN_LOCATION; + } + return EXPR_LOCATION(node); +} + +bool end_line_after(unsigned line, unsigned column, const body_entry *body) { + return line > body->where.line || (line == body->where.line && column >= body->where.start); +} + bool range_bytes(location_t location, file_entry *&file, std::size_t &begin, std::size_t &end) { const location_t start = get_pure_location(get_start(location)); const location_t last = get_pure_location(get_finish(location)); @@ -618,6 +679,18 @@ void pre_genericize(void *data, void *) { } if (body_entry *body = find_body(DECL_UID(decl))) { body->definition = true; + location_t end = last_body_location(DECL_SAVED_TREE(decl)); + if (!RESERVED_LOCATION_P(end)) { + end = get_finish(end); + } + const char *path = nullptr; + unsigned line = 0, column = 0; + if (!RESERVED_LOCATION_P(end) && point_position(end, path, line, column) && + std::strcmp(path, body->path) == 0 && (end_line_after(line, column, body))) { + body->has_extent = true; + body->end_line = line; + body->end_byte = column; + } } const location_t location = DECL_SOURCE_LOCATION(decl); if (RESERVED_LOCATION_P(location)) { @@ -692,8 +765,16 @@ void finish(void *, void *) { if (known) { std::fputs("{\"path\":", out); json_string(out, body->path); - std::fprintf(out, ",\"line\":%u,\"startByte\":%u,\"endByte\":%u}", body->where.line, + std::fprintf(out, ",\"line\":%u,\"startByte\":%u,\"endByte\":%u", body->where.line, body->where.start, body->where.end); + if (body->has_extent) { + std::fprintf(out, + ",\"extent\":{\"startLine\":%u,\"startByte\":%u," + "\"endLine\":%u,\"endByte\":%u}", + body->where.line, body->where.start, body->end_line, + body->end_byte); + } + std::fputc('}', out); } else { std::fputs("null", out); } diff --git a/include/vls/semantic/Occurrences.hpp b/include/vls/semantic/Occurrences.hpp index 78219a4..e05bb8d 100644 --- a/include/vls/semantic/Occurrences.hpp +++ b/include/vls/semantic/Occurrences.hpp @@ -19,6 +19,9 @@ struct Occurrence { Documents::Range use; DiagnosticSnapshot definition_file; Documents::Range definition; + // Whole definition extent when the compiler reported one (function body + // included). Call hierarchy uses it to attribute nested calls. + std::optional extent; [[nodiscard]] bool has_definition() const noexcept { return definition_file != nullptr; } }; diff --git a/src/features/CallHierarchy.cpp b/src/features/CallHierarchy.cpp index 2777932..1a87d5e 100644 --- a/src/features/CallHierarchy.cpp +++ b/src/features/CallHierarchy.cpp @@ -16,7 +16,9 @@ std::vector incoming(std::span calls, std::span, Incoming> grouped; std::size_t total_ranges{}; for (const auto &call : calls) { - if (!call.callee_definition || *call.callee_definition != target) + if (!call.callee_definition || call.callee_definition->name != target.name || + call.callee_definition->path != target.path || + !contains(call.callee_definition->range, target.range)) continue; const Definition *enclosing{}; for (const auto &definition : known) { @@ -78,7 +80,8 @@ std::vector outgoing(std::span calls, std::span enclosing->range.start) enclosing = &definition; } - if (!enclosing || *enclosing != caller) + if (!enclosing || enclosing->name != caller.name || enclosing->path != caller.path || + !contains(enclosing->range, caller.range)) continue; auto &slot = grouped[{call.callee_definition->name, call.callee_definition->path, call.callee_definition->range}]; diff --git a/src/semantic/EditorDiagnostics.cpp b/src/semantic/EditorDiagnostics.cpp index 4631aa3..5e6a38f 100644 --- a/src/semantic/EditorDiagnostics.cpp +++ b/src/semantic/EditorDiagnostics.cpp @@ -1470,11 +1470,13 @@ Json EditorDiagnostics::call_hierarchy_incoming(const Json &item) const { call.range = {{occurrence.use.start.line, occurrence.use.start.character}, {occurrence.use.end.line, occurrence.use.end.character}}; if (occurrence.has_definition()) { + const auto &extent = + occurrence.extent ? *occurrence.extent : occurrence.definition; features::call_hierarchy::Definition definition{ occurrence.name, occurrence.definition_file->identity.canonical_path.native(), - {{occurrence.definition.start.line, occurrence.definition.start.character}, - {occurrence.definition.end.line, occurrence.definition.end.character}}}; + {{extent.start.line, extent.start.character}, + {extent.end.line, extent.end.character}}}; call.callee_definition = definition; known.push_back(std::move(definition)); } @@ -1535,11 +1537,13 @@ Json EditorDiagnostics::call_hierarchy_outgoing(const Json &item) const { call.range = {{occurrence.use.start.line, occurrence.use.start.character}, {occurrence.use.end.line, occurrence.use.end.character}}; if (occurrence.has_definition()) { + const auto &extent = + occurrence.extent ? *occurrence.extent : occurrence.definition; features::call_hierarchy::Definition definition{ occurrence.name, occurrence.definition_file->identity.canonical_path.native(), - {{occurrence.definition.start.line, occurrence.definition.start.character}, - {occurrence.definition.end.line, occurrence.definition.end.character}}}; + {{extent.start.line, extent.start.character}, + {extent.end.line, extent.end.character}}}; call.callee_definition = definition; known.push_back(std::move(definition)); } diff --git a/src/semantic/Occurrences.cpp b/src/semantic/Occurrences.cpp index 10fa271..3f9c763 100644 --- a/src/semantic/Occurrences.cpp +++ b/src/semantic/Occurrences.cpp @@ -59,7 +59,9 @@ struct RawSpan { std::optional span(const Json *value) { const auto *object = value ? P::as_object(value) : nullptr; - if (!object || object->size() != 4) + if (!object || (object->size() != 4 && object->size() != 5)) + return {}; + if (object->size() == 5 && !P::find_member(*object, "extent")) return {}; const auto *path = P::as_string(P::find_member(*object, "path")); const auto line = integer(P::find_member(*object, "line")); @@ -73,6 +75,31 @@ std::optional span(const Json *value) { static_cast(*end)}; } +struct RawExtent { + std::uint32_t start_line{}, start_byte{}, end_line{}, end_byte{}; +}; + +std::optional extent(const Json *definition) { + const auto *object = definition ? P::as_object(definition) : nullptr; + const auto *value = object ? P::find_member(*object, "extent") : nullptr; + const auto *fields = value ? P::as_object(value) : nullptr; + if (!fields || fields->size() != 4) + return {}; + const auto start_line = integer(P::find_member(*fields, "startLine")); + const auto start_byte = integer(P::find_member(*fields, "startByte")); + const auto end_line = integer(P::find_member(*fields, "endLine")); + const auto end_byte = integer(P::find_member(*fields, "endByte")); + constexpr auto maximum = std::numeric_limits::max(); + if (!start_line || !start_byte || !end_line || !end_byte || *start_line < 1 || + *start_line > maximum || *end_line < *start_line || *end_line > maximum || + *start_byte < 1 || *start_byte > maximum || *end_byte < 1 || *end_byte > maximum || + (*end_line == *start_line && *end_byte <= *start_byte)) + return {}; + return RawExtent{static_cast(*start_line), + static_cast(*start_byte), static_cast(*end_line), + static_cast(*end_byte)}; +} + bool captured(std::span capture, const std::string &path) { return std::ranges::any_of(capture, [&](const auto &entry) { return entry.snapshot && entry.logical_path.native() == path; @@ -118,6 +145,39 @@ bind_span(const RawSpan &raw, std::string_view name, std::span bind_extent(const RawExtent &raw, + const Documents::DocumentSnapshot &snapshot) { + const std::string_view text = snapshot.text; + const auto offset = [&](std::uint32_t line, std::uint32_t byte) -> std::optional { + std::size_t line_start = 0; + for (std::uint32_t current = 1; current != line; ++current) { + const auto newline = text.find('\n', line_start); + if (newline == std::string_view::npos) + return {}; + line_start = newline + 1; + } + auto line_end = text.find('\n', line_start); + if (line_end == std::string_view::npos) + line_end = text.size(); + if (byte - 1 > line_end - line_start) + return {}; + const std::size_t result = line_start + byte - 1; + if (result < text.size() && (static_cast(text[result]) & 0xC0) == 0x80) + return {}; + return result; + }; + const auto begin = offset(raw.start_line, raw.start_byte); + const auto end = offset(raw.end_line, raw.end_byte); + if (!begin || !end || *end < *begin) + return {}; + const auto start = snapshot.offset_to_position(*begin); + const auto finish = snapshot.offset_to_position(*end); + if (!start || !finish || !(*start < *finish)) + return {}; + return Documents::Range{*start, *finish}; +} + } // namespace std::expected @@ -186,6 +246,14 @@ decode_occurrences(std::string_view report, std::string_view nonce, return std::unexpected{OccurrenceError::invalid_report}; occurrence.definition_file = bound->first; occurrence.definition = bound->second; + if (P::find_member(*P::as_object(definition), "extent")) { + const auto raw_extent = extent(definition); + if (!raw_extent) + return std::unexpected{OccurrenceError::invalid_report}; + occurrence.extent = bind_extent(*raw_extent, *bound->first); + if (!occurrence.extent) + return std::unexpected{OccurrenceError::invalid_report}; + } } } result.occurrences.push_back(std::move(occurrence)); diff --git a/tests/corpus/frontend/verify-stock-observer.py b/tests/corpus/frontend/verify-stock-observer.py index 9ee767f..286320c 100755 --- a/tests/corpus/frontend/verify-stock-observer.py +++ b/tests/corpus/frontend/verify-stock-observer.py @@ -61,7 +61,9 @@ def compile(compiler, observer, work, main, flags=()): def read_span(span, name, label): - check(isinstance(span, dict) and set(span) == {"path", "line", "startByte", "endByte"}, + check(isinstance(span, dict) + and set(span) in ({"path", "line", "startByte", "endByte"}, + {"path", "line", "startByte", "endByte", "extent"}), f"invalid {label} span {span!r}") check(all(type(span[key]) is int for key in ("line", "startByte", "endByte")), f"non-integer {label} span {span!r}") @@ -76,6 +78,20 @@ def read_span(span, name, label): f"{label} {name!r} does not occupy {span}: {raw!r}") raw[:start - 1].decode("utf-8") raw[:end - 1].decode("utf-8") + if "extent" in span: + extent = span["extent"] + check(isinstance(extent, dict) + and set(extent) == {"startLine", "startByte", "endLine", "endByte"} + and all(type(value) is int for value in extent.values()), + f"invalid {label} extent {extent!r}") + check(extent["startLine"] == span["line"] and extent["startByte"] == start + and (extent["endLine"], extent["endByte"]) >= (extent["startLine"], start), + f"{label} extent does not start at its span: {extent} vs {span}") + check(1 <= extent["endLine"] <= len(lines), + f"{label} extent line outside {path}: {extent}") + last = lines[extent["endLine"] - 1] + check(1 <= extent["endByte"] <= len(last) + 1, + f"{label} extent bytes outside line: {extent}") return (path, span["line"], start, end) diff --git a/tests/features/CallHierarchyTests.cpp b/tests/features/CallHierarchyTests.cpp index 29d3643..c347e74 100644 --- a/tests/features/CallHierarchyTests.cpp +++ b/tests/features/CallHierarchyTests.cpp @@ -124,3 +124,14 @@ VOID_TEST(CallHierarchy, outgoing_skips_unresolved_callees_and_bounds_groups) { require(outgoing(calls, known, known.front()).size() == 1); expect(outgoing(calls, known, known.front(), Limits{.callers = 0}).empty()); } + +VOID_TEST(CallHierarchy, a_compiler_extent_identifies_the_same_function) { + const auto target = definition("f", "/p/a.cpp", range(1)); + const auto caller_name = definition("outer", "/p/a.cpp", range(0, 4, 5)); + const std::vector known{definition("outer", "/p/a.cpp", {{0, 4}, {9, 1}}), target}; + const std::vector calls{call("f", target, "/p/a.cpp", range(5))}; + require(incoming(calls, known, target).size() == 1); + const auto result = outgoing(calls, known, caller_name); + require(result.size() == 1); + expect(result.front().to.name == "f"); +} diff --git a/tests/semantic/OccurrenceTests.cpp b/tests/semantic/OccurrenceTests.cpp index e90e747..48646fd 100644 --- a/tests/semantic/OccurrenceTests.cpp +++ b/tests/semantic/OccurrenceTests.cpp @@ -186,3 +186,24 @@ VOID_TEST(Occurrences, rejects_a_malformed_envelope) { require(!decode(extra, entries).has_value()); require(!decode("{\"schema\":1}", entries).has_value()); } + +VOID_TEST(Occurrences, binds_a_multiline_definition_extent) { + auto entries = capture(std::string{source}); + const auto call = span(source, "f", 1), declaration = span(source, "f", 0); + const auto definition = span_json(path, declaration); + const auto with_extent = definition.substr(0, definition.size() - 1) + + R"(,"extent":{"startLine":1,"startByte":5,"endLine":1,"endByte":21}})"; + auto decoded = + decode(report(occurrence("f", "int", span_json(path, call), with_extent)), entries); + require(decoded.has_value()); + require(decoded->occurrences.size() == 1); + const auto &fact = decoded->occurrences.front(); + require(fact.extent.has_value()); + expect(fact.extent->start.line == 0 && fact.extent->start.character == 4); + expect(fact.extent->end.line == 0 && fact.extent->end.character == 20); + // A malformed extent rejects the report rather than being dropped. + const auto bad = definition.substr(0, definition.size() - 1) + + R"(,"extent":{"startLine":2,"startByte":5,"endLine":1,"endByte":21}})"; + expect( + !decode(report(occurrence("f", "int", span_json(path, call), bad)), entries).has_value()); +}