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.
This commit is contained in:
faumaray committed 2026-12-05 14:41:03 +03:00
1 parent 8ca3dcbf74
commit 624c24d028
12 files changed
+601 -8

No files matched your search

+1 -1
View File
@@ -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/ProviderFile.cpp src/Build/CommandImport.cpp src/Build/VbsProvider.cpp
src/Build/CompdbProvider.cpp src/DocumentSync.cpp src/WorkspaceSession.cpp src/Server.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/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_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_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) target_compile_options(vls_protocol PUBLIC -freflection PRIVATE -Wall -Wextra -Wpedantic)
+3 -1
View File
@@ -70,6 +70,7 @@ void build(Void::Build::Project &project) {
"src/features/IndexNavigation.cpp", "src/features/IndexNavigation.cpp",
"src/features/SignatureHelp.cpp", "src/features/SignatureHelp.cpp",
"src/features/DocumentSymbols.cpp", "src/features/DocumentSymbols.cpp",
"src/features/TextStructure.cpp",
"src/debug/live/LiveSession.cpp", "src/debug/live/LiveSession.cpp",
"src/modules/ModuleWorkQueue.cpp", "src/modules/ModuleWorkQueue.cpp",
"src/modules/GccScan.cpp", "src/modules/GccScan.cpp",
@@ -148,7 +149,8 @@ void build(Void::Build::Project &project) {
auto feature_tests = auto feature_tests =
suite("vls_feature_tests", suite("vls_feature_tests",
{"tests/features/CompletionTests.cpp", "tests/features/IndexNavigationTests.cpp", {"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"); auto live_worker = project.executable("vls_live_worker_fixture");
live_worker.cxx_standard(CxxStandard::Cxx26) live_worker.cxx_standard(CxxStandard::Cxx26)
.sources({"tests/debug/LiveWorkerFixture.cpp"}) .sources({"tests/debug/LiveWorkerFixture.cpp"})
+4 -4
View File
@@ -17,6 +17,7 @@ missing part.
| textDocument/signatureHelp | `vls_feature_tests`, real stdio session | | textDocument/signatureHelp | `vls_feature_tests`, real stdio session |
| textDocument/documentSymbol | `vls_index_tests` path query, real stdio session | | textDocument/documentSymbol | `vls_index_tests` path query, real stdio session |
| textDocument/documentHighlight | `vls_feature_tests`, 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 | | workspace/symbol | stock occurrence corpus |
| voidLanguageServer/analysisStatus, providerStatus | stdio corpora | | voidLanguageServer/analysisStatus, providerStatus | stdio corpora |
| Debug adapter (DAP) separately through `vls-dap` | `vls_live_tests`, `vls_dap_tests` | | 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 | | Compiler-native completion with visibility proof | index-backed completion is explicitly incomplete |
| Overload-set signature help | only the selected occurrence's signature is available | | 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/codeAction, formatting | compiler-backed; needs a plan |
| textDocument/semanticTokens, inlayHint | larger | textDocument/semanticTokens, inlayHint | larger
| textDocument/codeLens, executeCommand | command surface not designed | | textDocument/codeLens, executeCommand | command surface not designed |
@@ -38,6 +38,6 @@ missing part.
## Next slices ## Next slices
1. selectionRange and foldingRange from document snapshots. 1. codeAction quick fixes from published diagnostics.
2. codeAction quick fixes from published diagnostics. 2. Semantic tokens from stock occurrences.
3. Semantic tokens from stock occurrences. 3. Formatting and inlay hints.
+1 -1
View File
@@ -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 Hash.hpp definition through it. Real persistence migrations and cross-file
rename coverage remain open. 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 The reflection provenance representation (roadmap 12 first slice) is
implemented as a bounded library with a registered suite: innermost-first implemented as a bounded library with a registered suite: innermost-first
+19
View File
@@ -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 about 25-30s in a Debug build (it passed VBS at ~27s); the full CMake run then
passed 18/18. 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 ## December 5 document symbols and document highlights
`SymbolIndex::find_by_path` returns the records whose use location is in one `SymbolIndex::find_by_path` returns the records whose use location is in one
+45
View File
@@ -0,0 +1,45 @@
#pragma once
#include <compare>
#include <cstddef>
#include <cstdint>
#include <string_view>
#include <vector>
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<Range> 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> folding_ranges(std::string_view text, const Limits & = Limits{});
} // namespace vls::features::structure
@@ -3,6 +3,7 @@
#include <vls/semantic/StockCompiler.hpp> #include <vls/semantic/StockCompiler.hpp>
#include <functional> #include <functional>
#include <span>
namespace vls::semantic { namespace vls::semantic {
@@ -42,6 +43,11 @@ class EditorDiagnostics {
// Same-binding uses within the document, or an empty list. // Same-binding uses within the document, or an empty list.
[[nodiscard]] Void::LanguageServer::Protocol::Json [[nodiscard]] Void::LanguageServer::Protocol::Json
document_highlights(std::string_view uri, Documents::Position position) const; 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 Documents::Position>) const;
// Foldable brace blocks, comments, regions and include groups.
[[nodiscard]] Void::LanguageServer::Protocol::Json folding_ranges(std::string_view uri) const;
struct NavigationReply { struct NavigationReply {
Void::LanguageServer::Protocol::Json result; Void::LanguageServer::Protocol::Json result;
+36
View File
@@ -16,6 +16,7 @@ namespace vls {
namespace { namespace {
namespace Protocol = Void::LanguageServer::Protocol; namespace Protocol = Void::LanguageServer::Protocol;
using Protocol::as_array;
using Protocol::as_object; using Protocol::as_object;
using Protocol::as_string; using Protocol::as_string;
using Protocol::find_member; using Protocol::find_member;
@@ -262,6 +263,8 @@ DispatchResult Server::handle(std::string_view body) {
{"changeNotifications", Json{true}}}}}}}}}; {"changeNotifications", Json{true}}}}}}}}};
if (diagnostics_) { if (diagnostics_) {
capabilities.emplace("documentSymbolProvider", Json{true}); capabilities.emplace("documentSymbolProvider", Json{true});
capabilities.emplace("selectionRangeProvider", Json{true});
capabilities.emplace("foldingRangeProvider", Json{true});
} }
if (diagnostics_ && diagnostics_->supports_occurrences()) { if (diagnostics_ && diagnostics_->supports_occurrences()) {
capabilities.emplace("hoverProvider", Json{true}); 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 error(id, -32602, "Expected a completion item");
return reply(id, "result", diagnostics_->completion_resolve(*params)); 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<Void::LanguageServer::Documents::Position> 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<std::int64_t>(&line->value) : nullptr;
const auto *character_value =
character ? std::get_if<std::int64_t>(&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<std::uint32_t>(*line_value),
static_cast<std::uint32_t>(*character_value)});
}
return reply(id, "result", diagnostics_->selection_ranges(*uri, selected));
}
if (*method == "textDocument/documentSymbol") { if (*method == "textDocument/documentSymbol") {
if (!diagnostics_) if (!diagnostics_)
return error(id, -32601, "Method not found"); return error(id, -32601, "Method not found");
+326
View File
@@ -0,0 +1,326 @@
#include <vls/features/TextStructure.hpp>
#include <algorithm>
#include <optional>
#include <set>
#include <tuple>
#include <utility>
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<Line> lines_of(std::string_view text) {
std::vector<Line> 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<std::uint32_t>(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<Range> &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<Range> selection_chain(std::string_view text, Position position, const Limits &limits) {
std::vector<Range> 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<std::size_t> openings;
const std::size_t window = offset > limits.scanBytes ? offset - limits.scanBytes : 0;
{
Scanner scanner;
std::vector<std::size_t> 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<std::uint32_t>(last.back().end - last.back().start)}},
limits.selectionDepth);
return chain;
}
std::vector<Folding> folding_ranges(std::string_view text, const Limits &limits) {
std::vector<Folding> folds;
std::set<std::tuple<std::uint32_t, std::uint32_t, std::string_view>> 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<std::size_t> braces;
std::optional<std::size_t> 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<std::uint32_t> conditions, regions;
std::optional<std::uint32_t> 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<std::uint32_t> 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
+39
View File
@@ -4,6 +4,7 @@
#include <vls/features/DocumentSymbols.hpp> #include <vls/features/DocumentSymbols.hpp>
#include <vls/features/IndexNavigation.hpp> #include <vls/features/IndexNavigation.hpp>
#include <vls/features/SignatureHelp.hpp> #include <vls/features/SignatureHelp.hpp>
#include <vls/features/TextStructure.hpp>
#include <vls/index/SymbolIndex.hpp> #include <vls/index/SymbolIndex.hpp>
#include <vls/modules/ArtifactCache.hpp> #include <vls/modules/ArtifactCache.hpp>
#include <vls/modules/GccArtifacts.hpp> #include <vls/modules/GccArtifacts.hpp>
@@ -1053,6 +1054,44 @@ Json EditorDiagnostics::document_highlights(std::string_view uri,
return Json{std::move(result)}; return Json{std::move(result)};
} }
Json EditorDiagnostics::selection_ranges(std::string_view uri,
std::span<const Documents::Position> 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<std::nullptr_t>(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<std::int64_t>(fold.start_line)}},
{"endLine", Json{static_cast<std::int64_t>(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) { void EditorDiagnostics::set_transactional_rename(bool supported) {
std::lock_guard lock{state_->mutex}; std::lock_guard lock{state_->mutex};
state_->transactional_rename = supported; state_->transactional_rename = supported;
+1 -1
View File
@@ -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_index_tests index/SymbolIndexTests.cpp)
vls_test_suite(vls_navigation_tests navigation/NavigationTests.cpp) vls_test_suite(vls_navigation_tests navigation/NavigationTests.cpp)
vls_test_suite(vls_reflection_tests reflection/ProvenanceTests.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) vls_test_suite(vls_live_tests debug/LiveSessionTests.cpp debug/LiveDapTests.cpp)
target_link_libraries(vls_live_tests PRIVATE Void::System) target_link_libraries(vls_live_tests PRIVATE Void::System)
add_dependencies(vls_live_tests vls_live_worker_fixture vls-dap) add_dependencies(vls_live_tests vls_live_worker_fixture vls-dap)
+120
View File
@@ -0,0 +1,120 @@
#include <vls/features/TextStructure.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <algorithm>
#include <string>
#include <tuple>
#include <vector>
namespace {
using namespace vls::features::structure;
using Void::Testing::expect;
using Void::Testing::require;
bool contains(const std::vector<Folding> &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 <a>\n#include <b>\n\nint x;\n#include <c>\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);
}));
}