Files
Language-Server/src/features/TextStructure.cpp
T
faumaray 624c24d028 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.
2026-12-05 14:41:03 +03:00

327 lines
11 KiB
C++

#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