From 624c24d02839b810b589645d87251fdbe78eb871 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Sat, 5 Dec 2026 14:41:03 +0300 Subject: [PATCH] Serve selection and folding ranges over LSP A bounded snapshot-only core (vls/features/TextStructure.hpp) builds nested selection chains (identifier, line, enclosing blocks, document) and foldable regions (brace blocks, comments, preprocessor pairs, include groups) while ignoring literals. The server advertises and serves textDocument/selectionRange with bounded positions and textDocument/foldingRange through EditorDiagnostics; registered vls_feature_tests cases cover both. --- CMakeLists.txt | 2 +- build.cpp | 4 +- docs/agent-workflow/LSP-PARITY.md | 8 +- docs/agent-workflow/STATE.md | 2 +- docs/agent-workflow/VERIFICATION.md | 19 ++ include/vls/features/TextStructure.hpp | 45 +++ include/vls/semantic/EditorDiagnostics.hpp | 6 + src/Server.cpp | 36 +++ src/features/TextStructure.cpp | 326 +++++++++++++++++++++ src/semantic/EditorDiagnostics.cpp | 39 +++ tests/CMakeLists.txt | 2 +- tests/features/TextStructureTests.cpp | 120 ++++++++ 12 files changed, 601 insertions(+), 8 deletions(-) create mode 100644 include/vls/features/TextStructure.hpp create mode 100644 src/features/TextStructure.cpp create mode 100644 tests/features/TextStructureTests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 4cb75ae..5b637f8 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/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/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 b27557f..98a7ad3 100644 --- a/build.cpp +++ b/build.cpp @@ -70,6 +70,7 @@ void build(Void::Build::Project &project) { "src/features/IndexNavigation.cpp", "src/features/SignatureHelp.cpp", "src/features/DocumentSymbols.cpp", + "src/features/TextStructure.cpp", "src/debug/live/LiveSession.cpp", "src/modules/ModuleWorkQueue.cpp", "src/modules/GccScan.cpp", @@ -148,7 +149,8 @@ void build(Void::Build::Project &project) { auto feature_tests = suite("vls_feature_tests", {"tests/features/CompletionTests.cpp", "tests/features/IndexNavigationTests.cpp", - "tests/features/SignatureHelpTests.cpp", "tests/features/DocumentSymbolsTests.cpp"}); + "tests/features/SignatureHelpTests.cpp", "tests/features/DocumentSymbolsTests.cpp", + "tests/features/TextStructureTests.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 be7d78b..1ed2b0c 100644 --- a/docs/agent-workflow/LSP-PARITY.md +++ b/docs/agent-workflow/LSP-PARITY.md @@ -17,6 +17,7 @@ missing part. | textDocument/signatureHelp | `vls_feature_tests`, real stdio session | | textDocument/documentSymbol | `vls_index_tests` path query, real stdio session | | textDocument/documentHighlight | `vls_feature_tests`, real stdio session | +| textDocument/selectionRange, foldingRange | `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` | @@ -27,7 +28,6 @@ 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/selectionRange, foldingRange | straightforward next slices | | textDocument/codeAction, formatting | compiler-backed; needs a plan | | textDocument/semanticTokens, inlayHint | larger | textDocument/codeLens, executeCommand | command surface not designed | @@ -38,6 +38,6 @@ missing part. ## Next slices -1. selectionRange and foldingRange from document snapshots. -2. codeAction quick fixes from published diagnostics. -3. Semantic tokens from stock occurrences. +1. codeAction quick fixes from published diagnostics. +2. Semantic tokens from stock occurrences. +3. Formatting and inlay hints. diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index cad8f23..1e30823 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. 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. 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 516f1b1..460fcbf 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -79,6 +79,25 @@ 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 selection and folding ranges + +`include/vls/features/TextStructure.hpp` and +`src/features/TextStructure.cpp` add two bounded, snapshot-only cores: +`selection_chain` (identifier, line, enclosing brace blocks found within a +scan window, whole document) and `folding_ranges` (multi-line brace blocks, +block comments, grouped full-line comments, `#if`/`#endif` and +`#region`/`#endregion` pairs, and include groups, ignoring literals). The server +advertises `selectionRangeProvider` and `foldingRangeProvider` and serves +`textDocument/selectionRange` (bounded positions) and `textDocument/foldingRange` +through `EditorDiagnostics`. `vls_feature_tests` grew from 36 to 45 cases. + +Real stdio session on `DocumentSnapshot.cpp` at line 10 column 9: +``` +selectionRange chain: [(10, 9, 10, 19), (10, 0, 10, 30), (9, 48, 14, 1), (8, 42, 37, 1), (0, 0, 38, 0)] +foldingRange: 9 first: [{'endLine': 6, 'kind': 'imports', 'startLine': 0}, {'endLine': 37, 'startLine': 8}, {'endLine': 14, 'startLine': 9}] +``` +All 18 native suites and all 18 CMake tests passed. + ## December 5 document symbols and document highlights `SymbolIndex::find_by_path` returns the records whose use location is in one diff --git a/include/vls/features/TextStructure.hpp b/include/vls/features/TextStructure.hpp new file mode 100644 index 0000000..ef6d3f2 --- /dev/null +++ b/include/vls/features/TextStructure.hpp @@ -0,0 +1,45 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace vls::features::structure { + +struct Position { + std::uint32_t line{}, character{}; + auto operator<=>(const Position &) const = default; +}; + +struct Range { + Position start, end; + auto operator<=>(const Range &) const = default; +}; + +struct Folding { + std::uint32_t start_line{}, end_line{}; + std::string_view kind; // "comment", "region", "imports" or empty + auto operator<=>(const Folding &) const = default; +}; + +struct Limits { + std::size_t selectionDepth{8}; + std::size_t scanBytes{1024 * 1024}; + std::size_t folds{4096}; + std::size_t positions{256}; +}; + +// Innermost first: the identifier at the position, its line, each enclosing +// brace block (only openings within the bounded window) and the whole +// document. Consecutive duplicates are removed. +[[nodiscard]] std::vector selection_chain(std::string_view text, Position, + const Limits & = Limits{}); + +// Multi-line brace blocks, block comments, grouped line comments, #if/#endif +// and #region/#endregion pairs, and include groups, in source order and +// bounded. Braces inside literals or comments never open a block. +[[nodiscard]] std::vector folding_ranges(std::string_view text, const Limits & = Limits{}); + +} // namespace vls::features::structure diff --git a/include/vls/semantic/EditorDiagnostics.hpp b/include/vls/semantic/EditorDiagnostics.hpp index 62131e7..a383814 100644 --- a/include/vls/semantic/EditorDiagnostics.hpp +++ b/include/vls/semantic/EditorDiagnostics.hpp @@ -3,6 +3,7 @@ #include #include +#include namespace vls::semantic { @@ -42,6 +43,11 @@ class EditorDiagnostics { // Same-binding uses within the document, or an empty list. [[nodiscard]] Void::LanguageServer::Protocol::Json document_highlights(std::string_view uri, Documents::Position position) const; + // Nested selection chains (token, line, blocks, document) per position. + [[nodiscard]] Void::LanguageServer::Protocol::Json + selection_ranges(std::string_view uri, std::span) const; + // Foldable brace blocks, comments, regions and include groups. + [[nodiscard]] Void::LanguageServer::Protocol::Json folding_ranges(std::string_view uri) const; struct NavigationReply { Void::LanguageServer::Protocol::Json result; diff --git a/src/Server.cpp b/src/Server.cpp index b5f9580..e05d17c 100644 --- a/src/Server.cpp +++ b/src/Server.cpp @@ -16,6 +16,7 @@ namespace vls { namespace { namespace Protocol = Void::LanguageServer::Protocol; +using Protocol::as_array; using Protocol::as_object; using Protocol::as_string; using Protocol::find_member; @@ -262,6 +263,8 @@ DispatchResult Server::handle(std::string_view body) { {"changeNotifications", Json{true}}}}}}}}}; if (diagnostics_) { capabilities.emplace("documentSymbolProvider", Json{true}); + capabilities.emplace("selectionRangeProvider", Json{true}); + capabilities.emplace("foldingRangeProvider", Json{true}); } if (diagnostics_ && diagnostics_->supports_occurrences()) { capabilities.emplace("hoverProvider", Json{true}); @@ -337,6 +340,39 @@ DispatchResult Server::handle(std::string_view body) { return error(id, -32602, "Expected a completion item"); return reply(id, "result", diagnostics_->completion_resolve(*params)); } + if (*method == "textDocument/foldingRange") { + if (!diagnostics_) + 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_->folding_ranges(*uri)); + } + if (*method == "textDocument/selectionRange") { + if (!diagnostics_) + return error(id, -32601, "Method not found"); + const auto *uri = as_string(member(member(params, "textDocument"), "uri")); + const auto *positions = as_array(member(params, "positions")); + if (!uri || !Void::LanguageServer::Documents::client_uri_key(*uri) || !positions || + positions->size() > 256) + return error(id, -32602, "Expected textDocument.uri and bounded positions"); + std::vector selected; + for (const auto &entry : *positions) { + const auto *fields = Protocol::as_object(&entry); + const auto *line = fields ? Protocol::find_member(*fields, "line") : nullptr; + const auto *character = fields ? Protocol::find_member(*fields, "character") : nullptr; + const auto *line_value = line ? std::get_if(&line->value) : nullptr; + const auto *character_value = + character ? std::get_if(&character->value) : nullptr; + if (!line_value || !character_value || *line_value < 0 || *character_value < 0 || + *line_value > Void::LanguageServer::Documents::kMaxPositionValue || + *character_value > Void::LanguageServer::Documents::kMaxPositionValue) + return error(id, -32602, "Expected bounded positions"); + selected.push_back({static_cast(*line_value), + static_cast(*character_value)}); + } + return reply(id, "result", diagnostics_->selection_ranges(*uri, selected)); + } if (*method == "textDocument/documentSymbol") { if (!diagnostics_) return error(id, -32601, "Method not found"); diff --git a/src/features/TextStructure.cpp b/src/features/TextStructure.cpp new file mode 100644 index 0000000..f18e938 --- /dev/null +++ b/src/features/TextStructure.cpp @@ -0,0 +1,326 @@ +#include + +#include +#include +#include +#include +#include + +namespace vls::features::structure { +namespace { +bool word(char ch) { + return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || + ch == '_'; +} + +struct Line { + std::uint32_t number{}; + std::size_t start{}, end{}; // end excludes the line terminator +}; + +std::vector lines_of(std::string_view text) { + std::vector lines; + std::size_t start{}; + std::uint32_t number{}; + while (start <= text.size()) { + const auto newline = text.find('\n', start); + auto end = newline == std::string_view::npos ? text.size() : newline; + if (end > start && text[end - 1] == '\r') + --end; + lines.push_back({number++, start, end}); + if (newline == std::string_view::npos) + break; + start = newline + 1; + } + return lines; +} + +std::size_t offset_of(std::string_view text, Position position) { + std::size_t offset{}; + std::uint32_t line{}; + while (line < position.line) { + const auto newline = text.find('\n', offset); + if (newline == std::string_view::npos) + return text.size(); + offset = newline + 1; + ++line; + } + const auto newline = text.find('\n', offset); + const auto end = newline == std::string_view::npos ? text.size() : newline; + return std::min(end, offset + position.character); +} + +Position position_of(std::string_view text, std::size_t offset) { + offset = std::min(offset, text.size()); + Position position; + std::size_t start{}; + while (true) { + const auto newline = text.find('\n', start); + const auto end = newline == std::string_view::npos ? text.size() : newline; + if (offset <= end) + return {position.line, static_cast(offset - start)}; + start = newline + 1; + ++position.line; + } +} + +// One-pass lexical state so braces and comment markers inside literals or +// comments are not structural. +struct Scanner { + char quote{}; + bool line_comment{}; + bool block_comment{}; + + // Returns the kind of structural character at the index, updating state. + void step(std::string_view text, std::size_t index, char &code, bool &in_comment) { + in_comment = false; + const char ch = text[index]; + const char next = index + 1 < text.size() ? text[index + 1] : '\0'; + code = ch; + if (line_comment) { + in_comment = true; + if (ch == '\n') + line_comment = false; + return; + } + if (block_comment) { + in_comment = true; + if (ch == '*' && next == '/') { + block_comment = false; + ++index; + } + return; + } + if (quote != '\0') { + in_comment = true; // treat literal contents as non-structural + if (ch == '\\') + ++index; + else if (ch == quote) + quote = '\0'; + return; + } + if (ch == '/' && next == '/') { + line_comment = true; + in_comment = true; + } else if (ch == '/' && next == '*') { + block_comment = true; + in_comment = true; + } else if (ch == '"' || ch == '\'') { + quote = ch; + in_comment = true; + } + } +}; + +std::size_t matching_close(std::string_view text, std::size_t open, std::size_t limit) { + Scanner scanner; + int depth{}; + const auto stop = std::min(text.size(), open + limit); + for (std::size_t index = open; index < stop; ++index) { + char code{}; + bool in_comment{}; + scanner.step(text, index, code, in_comment); + if (in_comment) + continue; + if (code == '{') + ++depth; + else if (code == '}' && --depth == 0) + return index; + } + return std::string_view::npos; +} + +void append_unique(std::vector &ranges, Range range, std::size_t depth) { + if (ranges.size() >= depth) + return; + if (!ranges.empty() && ranges.back() == range) + return; + ranges.push_back(range); +} +} // namespace + +std::vector selection_chain(std::string_view text, Position position, const Limits &limits) { + std::vector chain; + if (limits.selectionDepth == 0) + return chain; + const auto offset = offset_of(text, position); + std::size_t token_start = offset; + std::size_t token_end = offset; + while (token_start > 0 && word(text[token_start - 1])) + --token_start; + while (token_end < text.size() && word(text[token_end])) + ++token_end; + if (token_end > token_start) + append_unique(chain, {position_of(text, token_start), position_of(text, token_end)}, + limits.selectionDepth); + + const auto line_start = offset == 0 ? std::string_view::npos : text.rfind('\n', offset - 1); + const auto start = line_start == std::string_view::npos ? 0 : line_start + 1; + auto line_end = text.find('\n', offset); + if (line_end == std::string_view::npos) + line_end = text.size(); + if (line_end > start && text[line_end - 1] == '\r') + --line_end; + append_unique(chain, {position_of(text, start), position_of(text, line_end)}, + limits.selectionDepth); + + // Enclosing brace openings, innermost last, within the bounded window. + std::vector openings; + const std::size_t window = offset > limits.scanBytes ? offset - limits.scanBytes : 0; + { + Scanner scanner; + std::vector stack; + for (std::size_t index = window; index < offset; ++index) { + char code{}; + bool in_comment{}; + scanner.step(text, index, code, in_comment); + if (in_comment) + continue; + if (code == '{') + stack.push_back(index); + else if (code == '}' && !stack.empty()) + stack.pop_back(); + } + openings.assign(stack.rbegin(), stack.rend()); + } + for (const auto open : openings) { + const auto close = matching_close(text, open, limits.scanBytes); + if (close == std::string_view::npos || close < offset) + continue; + append_unique(chain, {position_of(text, open), position_of(text, close + 1)}, + limits.selectionDepth); + } + const auto last = lines_of(text); + append_unique( + chain, + {{0, 0}, + {last.empty() ? 0u : last.back().number, + last.empty() ? 0u : static_cast(last.back().end - last.back().start)}}, + limits.selectionDepth); + return chain; +} + +std::vector folding_ranges(std::string_view text, const Limits &limits) { + std::vector folds; + std::set> seen; + const auto add = [&](std::uint32_t start, std::uint32_t end, std::string_view kind) { + if (end > start && folds.size() < limits.folds && seen.emplace(start, end, kind).second) + folds.push_back({start, end, kind}); + }; + const auto lines = lines_of(text); + const auto line_of = [&lines](std::size_t offset) { + const auto found = std::ranges::upper_bound(lines, offset, {}, &Line::start); + return found == lines.begin() ? 0u : (found - 1)->number; + }; + + // Multi-line brace blocks and block comments, ignoring literals. + Scanner scanner; + std::vector braces; + std::optional block_start; + for (std::size_t index = 0; index < text.size(); ++index) { + const char ch = text[index]; + const char next = index + 1 < text.size() ? text[index + 1] : '\0'; + if (scanner.line_comment) { + if (ch == '\n') + scanner.line_comment = false; + continue; + } + if (scanner.block_comment) { + if (ch == '*' && next == '/') { + scanner.block_comment = false; + if (block_start) + add(line_of(*block_start), line_of(index), "comment"); + block_start.reset(); + ++index; + } + continue; + } + if (scanner.quote != '\0') { + if (ch == '\\') + ++index; + else if (ch == scanner.quote) + scanner.quote = '\0'; + continue; + } + if (ch == '/' && next == '/') { + scanner.line_comment = true; + ++index; + } else if (ch == '/' && next == '*') { + scanner.block_comment = true; + block_start = index; + ++index; + } else if (ch == '"' || ch == '\'') { + scanner.quote = ch; + } else if (ch == '{') { + braces.push_back(index); + } else if (ch == '}' && !braces.empty()) { + add(line_of(braces.back()), line_of(index), {}); + braces.pop_back(); + } + } + + // Preprocessor regions and include groups, line-based. + std::vector conditions, regions; + std::optional include_run, include_last; + for (const auto &line : lines) { + std::string_view content = text.substr(line.start, line.end - line.start); + const auto first = content.find_first_not_of(" \t"); + if (first == std::string_view::npos) + continue; + content.remove_prefix(first); + if (content.starts_with("#include")) { + if (!include_run) + include_run = line.number; + include_last = line.number; + continue; + } + if (include_run) { + add(*include_run, *include_last, "imports"); + include_run.reset(); + } + if (content.starts_with("#if")) + conditions.push_back(line.number); + else if (content.starts_with("#endif") && !conditions.empty()) { + add(conditions.back(), line.number, "region"); + conditions.pop_back(); + } else if (content.starts_with("#region")) + regions.push_back(line.number); + else if (content.starts_with("#endregion") && !regions.empty()) { + add(regions.back(), line.number, "region"); + regions.pop_back(); + } + } + if (include_run) + add(*include_run, *include_last, "imports"); + + // Consecutive full-line comments fold as one group. + std::optional run_start, run_last; + for (const auto &line : lines) { + std::string_view content = text.substr(line.start, line.end - line.start); + const auto first = content.find_first_not_of(" \t"); + const bool comment = + first != std::string_view::npos && content.substr(first).starts_with("//"); + if (comment && run_start && *run_last + 1 == line.number) { + run_last = line.number; + continue; + } + if (run_start) + add(*run_start, *run_last, "comment"); + run_start.reset(); + run_last.reset(); + if (comment) { + run_start = line.number; + run_last = line.number; + } + } + if (run_start) + add(*run_start, *run_last, "comment"); + + std::ranges::sort(folds, [](const Folding &left, const Folding &right) { + return std::tie(left.start_line, left.end_line) < + std::tie(right.start_line, right.end_line); + }); + return folds; +} + +} // namespace vls::features::structure diff --git a/src/semantic/EditorDiagnostics.cpp b/src/semantic/EditorDiagnostics.cpp index f73c17c..dc4e77d 100644 --- a/src/semantic/EditorDiagnostics.cpp +++ b/src/semantic/EditorDiagnostics.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -1053,6 +1054,44 @@ Json EditorDiagnostics::document_highlights(std::string_view uri, return Json{std::move(result)}; } +Json EditorDiagnostics::selection_ranges(std::string_view uri, + std::span positions) const { + const auto snapshot = state_->documents.snapshot(uri); + if (!snapshot) + return Json{nullptr}; + Json::Array result; + for (const auto &position : positions) { + const auto chain = features::structure::selection_chain( + snapshot->text, {position.line, position.character}); + Json nested; + for (auto entry = chain.rbegin(); entry != chain.rend(); ++entry) { + Json::Object node{ + {"range", range_json(Documents::Range{{entry->start.line, entry->start.character}, + {entry->end.line, entry->end.character}})}}; + if (!std::holds_alternative(nested.value)) + node.emplace("parent", nested); + nested = Json{std::move(node)}; + } + result.push_back(nested); + } + return Json{std::move(result)}; +} + +Json EditorDiagnostics::folding_ranges(std::string_view uri) const { + const auto snapshot = state_->documents.snapshot(uri); + if (!snapshot) + return Json{nullptr}; + Json::Array result; + for (const auto &fold : features::structure::folding_ranges(snapshot->text)) { + Json::Object entry{{"startLine", Json{static_cast(fold.start_line)}}, + {"endLine", Json{static_cast(fold.end_line)}}}; + if (!fold.kind.empty()) + entry.emplace("kind", Json{std::string{fold.kind}}); + result.push_back(Json{std::move(entry)}); + } + return Json{std::move(result)}; +} + 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 4021385..f4772dc 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) +vls_test_suite(vls_feature_tests features/CompletionTests.cpp features/IndexNavigationTests.cpp features/SignatureHelpTests.cpp features/DocumentSymbolsTests.cpp features/TextStructureTests.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/TextStructureTests.cpp b/tests/features/TextStructureTests.cpp new file mode 100644 index 0000000..548f647 --- /dev/null +++ b/tests/features/TextStructureTests.cpp @@ -0,0 +1,120 @@ +#include + +#include +#include + +#include +#include +#include +#include + +namespace { +using namespace vls::features::structure; +using Void::Testing::expect; +using Void::Testing::require; + +bool contains(const std::vector &folds, std::uint32_t start, std::uint32_t end, + std::string_view kind = {}) { + return std::ranges::any_of(folds, [&](const Folding &fold) { + return fold.start_line == start && fold.end_line == end && + (kind.empty() || fold.kind == kind); + }); +} +} // namespace + +VOID_TEST(TextStructure, selection_chain_nests_token_line_block_document) { + const std::string text = "int main() {\n int value = 17;\n}\n"; + const auto chain = selection_chain(text, {1, 9}); + require(chain.size() >= 4); + expect(chain[0] == Range{{1, 8}, {1, 13}}); // value + expect(chain[1] == Range{{1, 0}, {1, 19}}); // full line + expect(chain[2] == Range{{0, 11}, {2, 1}}); // brace block + expect(chain.back() == Range{{0, 0}, {3, 0}}); // whole document +} + +VOID_TEST(TextStructure, selection_chain_picks_innermost_blocks_first) { + const std::string text = "void f() {\n if (x) {\n g();\n }\n}\n"; + const auto chain = selection_chain(text, {2, 9}); + require(chain.size() >= 4); + expect(chain[1] == Range{{2, 0}, {2, 12}}); + const auto inner = std::ranges::find_if(chain, [](const Range &range) { + return range.start == Position{1, 11} && range.end == Position{3, 5}; + }); + expect(inner != chain.end()); + const auto outer = std::ranges::find_if(chain, [](const Range &range) { + return range.start == Position{0, 9} && range.end == Position{4, 1}; + }); + expect(outer != chain.end()); + expect(inner < outer); +} + +VOID_TEST(TextStructure, selection_chain_has_no_token_outside_a_word) { + const std::string text = "int x = 1;\n"; + const auto chain = selection_chain(text, {0, 4}); + require(chain.size() >= 2); + expect(chain.front() == Range{{0, 4}, {0, 5}}); + expect(chain[1] == Range{{0, 0}, {0, 10}}); + expect(selection_chain(text, {0, 0}, Limits{.selectionDepth = 0}).empty()); + expect(selection_chain(text, {0, 1}, Limits{.selectionDepth = 1}).size() == 1); +} + +VOID_TEST(TextStructure, selection_chain_bounds_the_block_window) { + std::string text = "void f() {\n"; + for (int line = 0; line != 40; ++line) + text += " // padding line\n"; + text += " g();\n}\n"; + Limits limits; + limits.scanBytes = 32; + const auto chain = selection_chain(text, {41, 6}, limits); + const auto block = std::ranges::find_if( + chain, [](const Range &range) { return range.start == Position{0, 10}; }); + expect(block == chain.end()); + expect(selection_chain(text, {41, 6}).size() > chain.size()); +} + +VOID_TEST(TextStructure, folds_multiline_braces_only) { + const std::string text = "void f() {\n if (x) {\n g();\n }\n h();\n}\n"; + const auto folds = folding_ranges(text); + expect(contains(folds, 1, 3)); + expect(contains(folds, 0, 5)); + expect(folding_ranges("void g() { h(); }\n").empty()); +} + +VOID_TEST(TextStructure, braces_in_literals_and_comments_do_not_fold) { + const std::string text = "const char *s = \"{\";\n// {\n/* {\n} */\nauto c = '}';\n"; + const auto folds = folding_ranges(text); + expect(folds.size() == 1); + expect(contains(folds, 2, 3, "comment")); +} + +VOID_TEST(TextStructure, folds_comments_and_preprocessor_regions) { + const std::string text = "#ifdef A\nint a;\n#endif\n// one\n// two\n// three\n/* block\n " + "comment */\n#region R\nint b;\n#endregion\n"; + const auto folds = folding_ranges(text); + expect(contains(folds, 0, 2, "region")); + expect(contains(folds, 3, 5, "comment")); + expect(contains(folds, 6, 7, "comment")); + expect(contains(folds, 8, 10, "region")); + expect(!contains(folds, 4, 5, "comment")); +} + +VOID_TEST(TextStructure, folds_include_groups) { + const std::string text = "#include \n#include \n\nint x;\n#include \n"; + const auto folds = folding_ranges(text); + expect(contains(folds, 0, 1, "imports")); + expect(!contains(folds, 4, 4, "imports")); +} + +VOID_TEST(TextStructure, folds_are_bounded_and_sorted) { + std::string text; + for (int block = 0; block != 20; ++block) + text += "void f" + std::to_string(block) + "() {\n g();\n}\n"; + Limits limits; + limits.folds = 3; + const auto folds = folding_ranges(text, limits); + expect(folds.size() == 3); + expect(std::ranges::is_sorted(folds, [](const Folding &left, const Folding &right) { + return std::tie(left.start_line, left.end_line) < + std::tie(right.start_line, right.end_line); + })); +}