From 12a71ff692f24ed695b7e22b2509c0ae6940b834 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Sat, 5 Dec 2026 15:19:42 +0300 Subject: [PATCH] Serve semantic tokens from stock occurrences A bounded core normalizes occurrence tokens (sorted, deduplicated, overlap-free, capped) and delta-encodes them. EditorDiagnostics emits one function token per proven call occurrence in the owner snapshot, and the server advertises a one-type legend and serves textDocument/semanticTokens/full. Registered tests cover normalization, encoding, overlap and bounds; a real stdio session decoded the fnv1a64 callee token. --- CMakeLists.txt | 2 +- build.cpp | 4 +- docs/agent-workflow/LSP-PARITY.md | 9 ++-- docs/agent-workflow/STATE.md | 2 +- docs/agent-workflow/VERIFICATION.md | 13 ++++++ include/vls/features/SemanticTokens.hpp | 35 +++++++++++++++ include/vls/semantic/EditorDiagnostics.hpp | 2 + src/Server.cpp | 16 +++++++ src/features/SemanticTokens.cpp | 52 ++++++++++++++++++++++ src/semantic/EditorDiagnostics.cpp | 40 +++++++++++++++++ tests/CMakeLists.txt | 2 +- tests/features/SemanticTokensTests.cpp | 51 +++++++++++++++++++++ 12 files changed, 220 insertions(+), 8 deletions(-) create mode 100644 include/vls/features/SemanticTokens.hpp create mode 100644 src/features/SemanticTokens.cpp create mode 100644 tests/features/SemanticTokensTests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 102d5b2..088216e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -30,7 +30,7 @@ add_library(vls_protocol STATIC src/Protocol/Framing.cpp src/Protocol/Json.cpp src/Build/ProviderFile.cpp src/Build/CommandImport.cpp src/Build/VbsProvider.cpp src/Build/CompdbProvider.cpp src/DocumentSync.cpp src/WorkspaceSession.cpp src/Server.cpp src/semantic/Diagnostics.cpp src/semantic/SourceCatalog.cpp src/semantic/StockCompiler.cpp src/semantic/EditorDiagnostics.cpp src/semantic/Occurrences.cpp src/scheduler/Scheduler.cpp - src/modules/ModuleGraph.cpp src/modules/ArtifactCache.cpp src/modules/GccArtifacts.cpp src/modules/ScheduledArtifacts.cpp src/index/SymbolIndex.cpp src/navigation/Navigation.cpp src/reflection/Provenance.cpp src/features/Completion.cpp src/features/IndexNavigation.cpp src/features/SignatureHelp.cpp src/features/DocumentSymbols.cpp src/features/TextStructure.cpp src/features/CodeActions.cpp src/debug/live/LiveSession.cpp src/modules/ModuleWorkQueue.cpp src/modules/GccScan.cpp src/modules/ScanCommand.cpp) + src/modules/ModuleGraph.cpp src/modules/ArtifactCache.cpp src/modules/GccArtifacts.cpp src/modules/ScheduledArtifacts.cpp src/index/SymbolIndex.cpp src/navigation/Navigation.cpp src/reflection/Provenance.cpp src/features/Completion.cpp src/features/IndexNavigation.cpp src/features/SignatureHelp.cpp src/features/DocumentSymbols.cpp src/features/TextStructure.cpp src/features/CodeActions.cpp src/features/SemanticTokens.cpp src/debug/live/LiveSession.cpp src/modules/ModuleWorkQueue.cpp src/modules/GccScan.cpp src/modules/ScanCommand.cpp) target_include_directories(vls_protocol PUBLIC "${PROJECT_SOURCE_DIR}/include") target_link_libraries(vls_protocol PUBLIC Void::Data PRIVATE Void::Unicode Void::Text Void::Crypto Void::System) target_compile_options(vls_protocol PUBLIC -freflection PRIVATE -Wall -Wextra -Wpedantic) diff --git a/build.cpp b/build.cpp index ec3565d..74904f6 100644 --- a/build.cpp +++ b/build.cpp @@ -72,6 +72,7 @@ void build(Void::Build::Project &project) { "src/features/DocumentSymbols.cpp", "src/features/TextStructure.cpp", "src/features/CodeActions.cpp", + "src/features/SemanticTokens.cpp", "src/debug/live/LiveSession.cpp", "src/modules/ModuleWorkQueue.cpp", "src/modules/GccScan.cpp", @@ -151,7 +152,8 @@ void build(Void::Build::Project &project) { suite("vls_feature_tests", {"tests/features/CompletionTests.cpp", "tests/features/IndexNavigationTests.cpp", "tests/features/SignatureHelpTests.cpp", "tests/features/DocumentSymbolsTests.cpp", - "tests/features/TextStructureTests.cpp", "tests/features/CodeActionsTests.cpp"}); + "tests/features/TextStructureTests.cpp", "tests/features/CodeActionsTests.cpp", + "tests/features/SemanticTokensTests.cpp"}); auto live_worker = project.executable("vls_live_worker_fixture"); live_worker.cxx_standard(CxxStandard::Cxx26) .sources({"tests/debug/LiveWorkerFixture.cpp"}) diff --git a/docs/agent-workflow/LSP-PARITY.md b/docs/agent-workflow/LSP-PARITY.md index ec44f5c..6203f41 100644 --- a/docs/agent-workflow/LSP-PARITY.md +++ b/docs/agent-workflow/LSP-PARITY.md @@ -19,6 +19,7 @@ missing part. | textDocument/documentHighlight | `vls_feature_tests`, real stdio session | | textDocument/selectionRange, foldingRange | `vls_feature_tests`, real stdio session | | textDocument/codeAction (quickfix) | `vls_feature_tests` + `vls_diagnostic_tests`, real stdio session | +| textDocument/semanticTokens/full | `vls_feature_tests`, real stdio session | | workspace/symbol | stock occurrence corpus | | voidLanguageServer/analysisStatus, providerStatus | stdio corpora | | Debug adapter (DAP) separately through `vls-dap` | `vls_live_tests`, `vls_dap_tests` | @@ -30,7 +31,7 @@ missing part. | 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 | -| textDocument/semanticTokens, inlayHint | larger +| textDocument/inlayHint | open | | textDocument/codeLens, executeCommand | command surface not designed | | callHierarchy / typeHierarchy | needs compiler call/type relationships | | workspace edits and file operations | client-side application is also open | @@ -39,6 +40,6 @@ missing part. ## Next slices -1. Semantic tokens from stock occurrences. -2. Formatting and inlay hints. -3. call/type hierarchy and code lens. +1. Formatting and inlay hints. +2. call/type hierarchy and code lens. +3. executeCommand and workspace edits/file operations. diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 27648c7..aa63a91 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. 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. 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 90efdbd..3db9575 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -79,6 +79,19 @@ 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 semantic tokens from stock occurrences + +`include/vls/features/SemanticTokens.hpp` normalizes occurrence tokens +(sorted by position, empty/overlong/duplicate/overlapping tokens dropped, the +earlier token wins, count bounded) and delta-encodes them for LSP. +`EditorDiagnostics::semantic_tokens` emits one `function` token per proven call +occurrence in the owner snapshot; the server advertises +`semanticTokensProvider` with a one-type legend and serves +`textDocument/semanticTokens/full`. `vls_feature_tests` grew from 50 to 54 +cases. A real stdio session with the stock observer decoded +`semanticTokens: 1 first: [(18, 33, 7, 0)]` - the `fnv1a64` callee token. All 18 +native suites and all 18 CMake tests passed. + ## December 5 code actions from compiler fixes GCC's SARIF `fixes` are now decoded: `CompilerDiagnostic::fixes` carries a diff --git a/include/vls/features/SemanticTokens.hpp b/include/vls/features/SemanticTokens.hpp new file mode 100644 index 0000000..4b32b0c --- /dev/null +++ b/include/vls/features/SemanticTokens.hpp @@ -0,0 +1,35 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace vls::features::semantic_tokens { + +// Indices into the legend the server advertises. Only tokens the stock +// observer can prove are represented; there are no keyword or guess tokens. +inline constexpr std::uint32_t function_type = 0; + +struct Token { + std::uint32_t line{}, character{}, length{}; + std::uint32_t type{function_type}; + std::uint32_t modifiers{}; + auto operator<=>(const Token &) const = default; +}; + +struct Limits { + std::size_t tokens{65536}; + std::size_t length{4096}; +}; + +// Sorts by position, drops empty or overlong tokens, duplicates and tokens +// that overlap an earlier one (the earlier token wins), and bounds the count. +[[nodiscard]] std::vector normalize(std::span, const Limits & = Limits{}); + +// LSP delta encoding: [deltaLine, deltaStartChar, length, type, modifiers] +// per token. Input must already be normalized. +[[nodiscard]] std::vector encode(std::span); + +} // namespace vls::features::semantic_tokens diff --git a/include/vls/semantic/EditorDiagnostics.hpp b/include/vls/semantic/EditorDiagnostics.hpp index 8eb5b3a..ffa9368 100644 --- a/include/vls/semantic/EditorDiagnostics.hpp +++ b/include/vls/semantic/EditorDiagnostics.hpp @@ -52,6 +52,8 @@ class EditorDiagnostics { // requested range. Only fixes proven in the owner snapshot are offered. [[nodiscard]] Void::LanguageServer::Protocol::Json code_actions(std::string_view uri, Documents::Range range) const; + // Semantic tokens for the document's proven occurrences, delta-encoded. + [[nodiscard]] Void::LanguageServer::Protocol::Json semantic_tokens(std::string_view uri) const; struct NavigationReply { Void::LanguageServer::Protocol::Json result; diff --git a/src/Server.cpp b/src/Server.cpp index 73f7304..9700184 100644 --- a/src/Server.cpp +++ b/src/Server.cpp @@ -266,6 +266,14 @@ DispatchResult Server::handle(std::string_view body) { capabilities.emplace("selectionRangeProvider", Json{true}); capabilities.emplace("foldingRangeProvider", Json{true}); } + if (diagnostics_ && diagnostics_->supports_occurrences()) + capabilities.emplace( + "semanticTokensProvider", + Json{Json::Object{ + {"legend", Json{Json::Object{ + {"tokenTypes", Json{Json::Array{Json{std::string{"function"}}}}}, + {"tokenModifiers", Json{Json::Array{}}}}}}, + {"full", Json{true}}}}); if (diagnostics_ && diagnostics_->supports_occurrences()) capabilities.emplace( "codeActionProvider", @@ -378,6 +386,14 @@ DispatchResult Server::handle(std::string_view body) { } return reply(id, "result", diagnostics_->selection_ranges(*uri, selected)); } + if (*method == "textDocument/semanticTokens/full") { + if (!diagnostics_ || !diagnostics_->supports_occurrences()) + return error(id, -32601, "Method not found"); + const auto *uri = as_string(member(member(params, "textDocument"), "uri")); + if (!uri || !Void::LanguageServer::Documents::client_uri_key(*uri)) + return error(id, -32602, "Expected textDocument.uri"); + return reply(id, "result", diagnostics_->semantic_tokens(*uri)); + } if (*method == "textDocument/codeAction") { if (!diagnostics_ || !diagnostics_->supports_occurrences()) return error(id, -32601, "Method not found"); diff --git a/src/features/SemanticTokens.cpp b/src/features/SemanticTokens.cpp new file mode 100644 index 0000000..b8db395 --- /dev/null +++ b/src/features/SemanticTokens.cpp @@ -0,0 +1,52 @@ +#include + +#include +#include + +namespace vls::features::semantic_tokens { + +std::vector normalize(std::span tokens, const Limits &limits) { + std::vector sorted; + sorted.reserve(tokens.size()); + for (const auto &token : tokens) + if (token.length != 0 && token.length <= limits.length) + sorted.push_back(token); + std::ranges::sort(sorted); + std::vector result; + for (const auto &token : sorted) { + if (result.size() >= limits.tokens) + break; + if (!result.empty()) { + const auto &last = result.back(); + if (last == token) + continue; + // Overlap on the same line: keep the earlier token. + if (last.line == token.line && last.character + last.length > token.character) + continue; + } + result.push_back(token); + } + return result; +} + +std::vector encode(std::span tokens) { + std::vector data; + data.reserve(tokens.size() * 5); + std::uint32_t previous_line{}; + std::uint32_t previous_character{}; + for (const auto &token : tokens) { + const std::uint32_t delta_line = token.line - previous_line; + const std::uint32_t delta_start = + delta_line == 0 ? token.character - previous_character : token.character; + data.push_back(delta_line); + data.push_back(delta_start); + data.push_back(token.length); + data.push_back(token.type); + data.push_back(token.modifiers); + previous_line = token.line; + previous_character = token.character; + } + return data; +} + +} // namespace vls::features::semantic_tokens diff --git a/src/semantic/EditorDiagnostics.cpp b/src/semantic/EditorDiagnostics.cpp index 379e835..732e5f4 100644 --- a/src/semantic/EditorDiagnostics.cpp +++ b/src/semantic/EditorDiagnostics.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -1159,6 +1160,45 @@ Json EditorDiagnostics::code_actions(std::string_view uri, Documents::Range rang return Json{std::move(actions)}; } +Json EditorDiagnostics::semantic_tokens(std::string_view uri) const { + auto &s = *state_; + auto key = Documents::client_uri_key(uri); + std::shared_ptr receipt; + std::shared_ptr> facts; + { + std::lock_guard lock{s.mutex}; + const auto i = key ? s.entries.find(*key) : s.entries.end(); + if (i == s.entries.end()) + return Json{Json::Object{{"data", Json{Json::Array{}}}}}; + receipt = i->second.receipt; + facts = i->second.occurrences; + } + if (!receipt || !facts || !s.valid(*receipt)) + return Json{Json::Object{{"data", Json{Json::Array{}}}}}; + const Documents::DocumentSnapshot *snapshot = nullptr; + for (const auto &entry : receipt->capture->entries()) + if (entry.snapshot && entry.snapshot->identity.canonical_uri == *key) { + snapshot = entry.snapshot.get(); + break; + } + if (!snapshot) + return Json{Json::Object{{"data", Json{Json::Array{}}}}}; + std::vector tokens; + for (const auto &occurrence : *facts) { + if (occurrence.use_file.get() != snapshot || + occurrence.use.start.line != occurrence.use.end.line || + occurrence.use.end.character <= occurrence.use.start.character) + continue; + tokens.push_back({occurrence.use.start.line, occurrence.use.start.character, + occurrence.use.end.character - occurrence.use.start.character}); + } + const auto normalized = features::semantic_tokens::normalize(tokens); + Json::Array data; + for (const auto value : features::semantic_tokens::encode(normalized)) + data.push_back(Json{static_cast(value)}); + return Json{Json::Object{{"data", Json{std::move(data)}}}}; +} + void EditorDiagnostics::set_transactional_rename(bool supported) { std::lock_guard lock{state_->mutex}; state_->transactional_rename = supported; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index d4ec557..297d1bf 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -22,7 +22,7 @@ vls_test_suite(vls_scheduler_tests scheduler/SchedulerTests.cpp) vls_test_suite(vls_index_tests index/SymbolIndexTests.cpp) vls_test_suite(vls_navigation_tests navigation/NavigationTests.cpp) vls_test_suite(vls_reflection_tests reflection/ProvenanceTests.cpp) -vls_test_suite(vls_feature_tests features/CompletionTests.cpp features/IndexNavigationTests.cpp features/SignatureHelpTests.cpp features/DocumentSymbolsTests.cpp features/TextStructureTests.cpp features/CodeActionsTests.cpp) +vls_test_suite(vls_feature_tests features/CompletionTests.cpp features/IndexNavigationTests.cpp features/SignatureHelpTests.cpp features/DocumentSymbolsTests.cpp features/TextStructureTests.cpp features/CodeActionsTests.cpp features/SemanticTokensTests.cpp) vls_test_suite(vls_live_tests debug/LiveSessionTests.cpp debug/LiveDapTests.cpp) target_link_libraries(vls_live_tests PRIVATE Void::System) add_dependencies(vls_live_tests vls_live_worker_fixture vls-dap) diff --git a/tests/features/SemanticTokensTests.cpp b/tests/features/SemanticTokensTests.cpp new file mode 100644 index 0000000..8a4b6fd --- /dev/null +++ b/tests/features/SemanticTokensTests.cpp @@ -0,0 +1,51 @@ +#include + +#include +#include + +#include + +namespace { +using namespace vls::features::semantic_tokens; +using Void::Testing::expect; +using Void::Testing::require; + +Token token(std::uint32_t line, std::uint32_t character, std::uint32_t length) { + return {line, character, length}; +} +} // namespace + +VOID_TEST(SemanticTokens, normalizes_order_and_deltas) { + const std::vector tokens{token(2, 4, 3), token(0, 8, 2), token(0, 2, 4)}; + const auto sorted = normalize(tokens); + require(sorted.size() == 3); + expect(sorted[0] == token(0, 2, 4)); + expect(sorted[1] == token(0, 8, 2)); + expect(sorted[2] == token(2, 4, 3)); + expect(encode(sorted) == + std::vector{0, 2, 4, 0, 0, 0, 6, 2, 0, 0, 2, 4, 3, 0, 0}); +} + +VOID_TEST(SemanticTokens, drops_empty_duplicate_and_overlapping_tokens) { + const std::vector tokens{token(1, 0, 0), token(1, 5, 4), token(1, 5, 4), token(1, 7, 2), + token(1, 9, 2)}; + const auto result = normalize(tokens); + require(result.size() == 2); + expect(result[0] == token(1, 5, 4)); + expect(result[1] == token(1, 9, 2)); +} + +VOID_TEST(SemanticTokens, the_same_span_on_different_lines_is_distinct) { + const std::vector tokens{token(0, 3, 2), token(1, 3, 2)}; + const auto result = normalize(tokens); + expect(result.size() == 2); + expect(encode(result) == std::vector{0, 3, 2, 0, 0, 1, 3, 2, 0, 0}); +} + +VOID_TEST(SemanticTokens, bounds_count_and_length) { + const std::vector tokens{token(0, 0, 1), token(0, 2, 1), token(0, 4, 1)}; + expect(normalize(tokens, Limits{.tokens = 2}).size() == 2); + expect(normalize(tokens, Limits{.tokens = 2, .length = 1}).size() == 2); + const std::vector long_token{token(0, 0, 64)}; + expect(normalize(long_token, Limits{.length = 8}).empty()); +}