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

+36
View File
@@ -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<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 (!diagnostics_)
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/IndexNavigation.hpp>
#include <vls/features/SignatureHelp.hpp>
#include <vls/features/TextStructure.hpp>
#include <vls/index/SymbolIndex.hpp>
#include <vls/modules/ArtifactCache.hpp>
#include <vls/modules/GccArtifacts.hpp>
@@ -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<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) {
std::lock_guard lock{state_->mutex};
state_->transactional_rename = supported;