Implement the VLS roadmap on the native VBS build

Native VBS and CMake builds of the server and every registered suite:
protocol and document sync, VBS/compdb providers, stock GCC diagnostics
(including in-process default profile preparation), the stock occurrence
observer and hover/definition, the bounded Scheduler, C++ module graph,
scan and artifact cache with real CMI production, the context-aware
symbol index with schema-2 snapshot migration, navigation and guarded
rename, reflection provenance with splice-origin extraction, index-backed
completion and signature help, live GCC worker control with a registered
DAP suite, and the Neovim and VS Code clients.

VoidLibrary follows main. The private GCC 16.2.0 frontend is reproduced
from the versioned patches and verified stepping reflection/template code
with projected values 17/34 and 41/82.
This commit is contained in:
faumaray committed 2026-12-05 14:06:50 +03:00
1 parent ca04975d54
commit da8003f6d4
310 files changed
+47552 -480

No files matched your search

+692
View File
@@ -0,0 +1,692 @@
#include <Void/LanguageServer/Build/Providers.hpp>
#include <Void/LanguageServer/Protocol/Json.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <Void/Text/Hex.hpp>
#include <Void/Unicode/Utf.hpp>
#include <algorithm>
#include <map>
#include <ranges>
#include <span>
#include <utility>
namespace Void::LanguageServer::Build {
namespace {
namespace fs = std::filesystem;
using Protocol::Json;
using Strings = std::vector<std::string>;
template <class T> using Result = std::expected<T, std::string>;
constexpr std::size_t mib = 1024 * 1024;
constexpr std::size_t max_rows = 32 * 1024, max_row_bytes = 2 * mib, max_row_marks = 16 * 1024;
constexpr std::size_t max_row_depth = 31; // Plus the top-level array.
constexpr std::size_t max_args = 4096, max_arg_bytes = 64 * 1024, max_argv_bytes = mib;
constexpr std::size_t max_path_bytes = 4095;
bool consume(std::string_view &text, char byte) {
const auto start = text.find_first_not_of(" \t\r\n");
text.remove_prefix(std::min(start, text.size()));
if (!text.starts_with(byte))
return false;
text.remove_prefix(1);
return true;
}
// Locate one bounded object. StrictJson owns all JSON value, key and escape validation.
Result<std::string_view> take_row(std::string_view &text) {
if (!text.starts_with('{'))
return std::unexpected("expected a compilation database row object");
bool quoted = false, escaped = false;
std::size_t depth = 0, marks = 0;
for (std::size_t i = 0; i < std::min(text.size(), max_row_bytes); ++i) {
const char c = text[i];
if (quoted) {
if (escaped)
escaped = false;
else if (c == '\\')
escaped = true;
else if (c == '"')
quoted = false;
continue;
}
if (c == '"')
quoted = true;
else if (c == '[' || c == '{') {
if (++depth > max_row_depth)
return std::unexpected("row nesting limit exceeded");
} else if (c == ']' || c == '}') {
if (--depth == 0) {
const auto row = text.substr(0, i + 1);
text.remove_prefix(i + 1);
return row;
}
} else if (c != ',')
continue;
if (++marks > max_row_marks)
return std::unexpected("row structural token limit exceeded");
}
return std::unexpected("unterminated or oversized compilation database row");
}
bool path_text(std::string_view text) {
return !text.empty() && text.size() <= max_path_bytes && !text.contains('\0');
}
bool has_parent_step(const fs::path &path) {
return std::ranges::find(path, fs::path{".."}) != path.end();
}
bool in_workspace(const fs::path &path, const fs::path &root) {
return std::ranges::starts_with(path, root);
}
// Preserve parent steps for the scoped filesystem walk. Their meaning depends on
// every preceding component, including a directory symlink.
Result<fs::path> resolve_path(const fs::path &base, std::string_view text, bool directory) {
if (!path_text(text))
return std::unexpected("invalid or oversized path");
const fs::path spelling{text};
if (!directory && (!spelling.has_filename() || spelling.filename() == "." ||
spelling.filename() == ".."))
return std::unexpected("expected a file name");
auto joined = base / spelling;
if (!has_parent_step(joined))
joined = joined.lexically_normal();
if (directory && !joined.has_filename() && joined != joined.root_path())
joined = joined.parent_path();
if (!joined.is_absolute() || joined.native().size() > max_path_bytes)
return std::unexpected("invalid resolved path");
return joined;
}
struct Arguments {
Strings values;
std::size_t bytes{};
bool append(std::string_view value) {
if (values.size() == max_args || value.size() > max_arg_bytes ||
value.size() > max_argv_bytes - bytes || value.contains('\0'))
return false;
values.emplace_back(value);
bytes += value.size();
return true;
}
};
enum class Syntax { command, gcc_response, clang_response };
bool separator(char c, Syntax syntax) {
return c == ' ' || c == '\t' || (syntax != Syntax::command && (c == '\r' || c == '\n')) ||
(syntax == Syntax::gcc_response && (c == '\v' || c == '\f'));
}
bool command_expansion(char c, char quote, bool started) {
if (quote == '\'')
return false;
if (c == '$' || c == '`')
return true;
return !quote && (std::string_view("|&;<>()*?[]{}").contains(c) ||
(!started && (c == '~' || c == '#')));
}
Result<Arguments> tokenize(std::string_view text, Syntax syntax) {
if (text.contains('\0') || !Unicode::validate_utf8(text) || text.starts_with("\xef\xbb\xbf"))
return std::unexpected("unsupported command text encoding");
Arguments result;
std::string token;
char quote = 0;
bool started = false;
for (std::size_t i = 0; i < text.size(); ++i) {
char c = text[i];
if (!quote && separator(c, syntax)) {
if (started && !result.append(token))
return std::unexpected("command argument limit exceeded");
started = false;
token.clear();
continue;
}
if (syntax == Syntax::command && command_expansion(c, quote, started))
return std::unexpected("unsupported shell expansion or control operator");
if ((c == '\'' || c == '"') && (!quote || quote == c)) {
quote = quote ? 0 : c;
started = true;
continue;
}
// Clang GNU response files escape the next byte in either quote style. GCC's
// libiberty keeps single quotes literal and limits escapes inside double quotes.
if (c == '\\' && (syntax == Syntax::clang_response || quote != '\'')) {
if (i + 1 == text.size())
return std::unexpected("incomplete backslash escape");
const char next = text[i + 1];
const bool escapes = syntax == Syntax::clang_response || quote != '"' || next == '$' ||
next == '`' || next == '"' || next == '\\' || next == '\n';
if (escapes) {
c = text[++i];
if (syntax == Syntax::gcc_response && c == '\n') {
started = true;
continue;
}
}
}
if (static_cast<unsigned char>(c) < 32 || c == 127)
return std::unexpected("unsupported control character in argument");
if (token.size() == max_arg_bytes)
return std::unexpected("command argument byte limit exceeded");
token.push_back(c);
started = true;
}
if (quote)
return std::unexpected("unterminated quoted argument");
if (started && !result.append(token))
return std::unexpected("command argument limit exceeded");
return result;
}
struct Import {
const DatabaseInput &input;
ImportedCommands output;
// Compare against the first immutable row on every digest tie.
struct Occurrence {
std::string_view first;
std::size_t count{};
};
std::map<std::string, Occurrence> occurrences;
std::map<fs::path, Result<std::size_t>> responses;
std::map<std::pair<fs::path, CommandPathKind>, std::size_t> paths;
std::size_t read_attempts{}, remaining_storage{128 * mib}, remaining_expansion{64 * mib};
bool exhausted{};
bool charge(std::size_t &remaining, std::size_t cost) {
if (cost > remaining) {
exhausted = true;
return false;
}
remaining -= cost;
return true;
}
Result<std::string> record_id(std::string_view raw) {
const auto digest = Crypto::sha256(raw);
if (!digest)
return std::unexpected("row identity digest unavailable");
const auto [it, inserted] =
occurrences.try_emplace(Encoding::Hex::encode(*digest), Occurrence{raw});
if (!inserted && it->second.first != raw)
return std::unexpected("distinct compilation records have identical digests");
return it->first + "#" + std::to_string(++it->second.count);
}
};
std::size_t path_cost(const fs::path &path) {
return path.native().size() +
(sizeof(fs::path) + sizeof(void *)) * static_cast<std::size_t>(std::ranges::distance(path));
}
Result<const CommandPathLookup *> bind_command_path(Import &state, const fs::path &path,
CommandPathKind kind) {
if (!in_workspace(path, state.input.scope.workspace.root))
return std::unexpected("out-of-workspace command path");
const auto key = std::pair{path, kind};
auto &lookups = state.output.lookups.paths;
auto it = state.paths.find(key);
if (it == state.paths.end()) {
auto lookup = inspect_command_path(state.input.scope, path, kind);
// Includes the bounded link stamps and both retained copies of the logical name.
if (!state.charge(state.remaining_storage,
1024 + 2 * path_cost(path) + path_cost(lookup.physical_path)))
return std::unexpected("command path storage limit exceeded");
it = state.paths.emplace(key, lookups.size()).first;
lookups.push_back(std::move(lookup));
}
const auto &lookup = lookups[it->second];
if (lookup.physical_path.empty())
return std::unexpected("unresolved command path (" + lookup.issue + "): " + path.native());
return &lookup;
}
// Cache only by logical name. Two hard links or symlinks retain both namespace observations.
Result<std::size_t> response_index(Import &state, const fs::path &path, std::size_t byte_limit) {
if (const auto it = state.responses.find(path); it != state.responses.end())
return it->second;
if (++state.read_attempts > 1024 || state.responses.size() >= 256) {
state.exhausted = true;
return std::unexpected("generation response input limit exceeded");
}
auto file = read_provider_file(state.input.scope, path, FilePurpose::response, byte_limit);
if (!file) {
if (!state.charge(state.remaining_storage, path_cost(path) + 256))
return std::unexpected("retained response lookup limit exceeded");
state.output.lookups.failed_responses.push_back({file.error(), byte_limit});
if (file.error().code == "too_large")
return std::unexpected("aggregate response byte limit exceeded at " + path.native());
auto failure = std::unexpected("response file " + file.error().code + " at " + path.native());
// One observation per logical name for this generation. A byte limit depends on the
// current expansion and must not poison a different row with more remaining budget.
if (!state.charge(state.remaining_storage, path_cost(path) + failure.error().size() + 128))
return std::unexpected("retained response input limit exceeded");
state.responses.emplace(path, failure);
return failure;
}
const auto cost = file->bytes->size() + path_cost(path) * 2 + path_cost(file->canonical_path) + 1024;
if (!state.charge(state.remaining_storage, cost))
return std::unexpected("retained response input limit exceeded");
const auto index = state.output.dependencies.size();
state.responses.emplace(path, index);
state.output.dependencies.push_back(std::move(*file));
return index;
}
struct Expansion {
Import &state;
const fs::path &cwd;
Syntax syntax;
std::vector<std::size_t> active;
Arguments expanded;
std::size_t bytes_left, visits{};
Result<void> append(std::span<const std::string> tokens) {
const auto &scope = state.input.scope;
for (const auto &arg : tokens) {
if (!arg.starts_with('@')) {
if (!expanded.append(arg))
return std::unexpected("expanded argument limit exceeded");
continue;
}
if (active.size() >= std::min<std::size_t>(scope.limits.max_response_file_depth, 32) ||
++visits > 256)
return std::unexpected("response nesting or reference limit exceeded");
const auto name = std::string_view(arg).substr(1);
auto path = resolve_path(cwd, name, false);
if (!path || has_parent_step(fs::path{name}) || !in_workspace(*path, scope.workspace.root))
return std::unexpected("response file name outside supported workspace routes");
auto index = response_index(state, *path, bytes_left);
if (!index)
return std::unexpected(std::move(index.error()));
const auto &file = state.output.dependencies[*index];
if (std::ranges::any_of(active, [&](auto parent) {
return same_provider_object(state.output.dependencies[parent], file);
}))
return std::unexpected("recursive response file " + path->native());
if (file.bytes->size() > bytes_left)
return std::unexpected("aggregate response byte limit exceeded");
bytes_left -= file.bytes->size();
if (!state.charge(state.remaining_expansion, file.bytes->size() + 128))
return std::unexpected("generation response expansion limit exceeded");
auto nested = tokenize(*file.bytes, syntax);
if (!nested)
return std::unexpected(std::move(nested.error()));
active.push_back(*index);
auto accepted = append(nested->values);
active.pop_back();
if (!accepted)
return accepted;
}
return {};
}
};
Result<std::size_t> check_prefix(const DatabaseInput &input, std::span<const std::string> raw) {
if (!input.driver)
return std::unexpected("no checked compiler for this workspace");
const auto &driver = *input.driver;
const auto &tool = driver.tool;
if (tool.workspace_root != input.scope.workspace.root ||
tool.operation != Workspace::AuthorityLevel::compiler_use || !tool.trust_generation)
return std::unexpected("compiler check has a different workspace, purpose or generation");
// Trust checks bounds, controls, wrappers, compiler spelling and dialect before examining
// operands. Only these three post-prefix classifications can require provider normalization.
// The final classifier must accept the entire expanded command.
using enum Workspace::FlagClassification;
const auto checked = Workspace::classify_and_unwrap_command(raw, driver.wrappers, tool.identity,
driver.driver);
if (!checked.allowed && checked.classification != unresolved_response_file &&
checked.classification != unsupported_operand && checked.classification != unsupported_option)
return std::unexpected(std::string(checked.reason));
auto compiler = std::ranges::find(raw, tool.identity.selected_path.native());
if (compiler == raw.end())
return std::unexpected("argv lacks the exact selected compiler spelling");
return static_cast<std::size_t>(compiler - raw.begin()) + 1;
}
Result<const CommandPathLookup *> semantic_path(Import &state, const fs::path &cwd,
std::string_view value, bool directory) {
auto path = resolve_path(cwd, value, directory);
if (!path || has_parent_step(*path))
return std::unexpected("ambiguous or out-of-workspace compiler path");
return bind_command_path(state, *path, directory ? CommandPathKind::directory : CommandPathKind::file);
}
// Keep separate and joined operands distinct. In particular a separate -I consumes its
// following token, even when that token spells -o. Unknown flags go to Trust unchanged.
Result<void> normalize(Import &state, const DriverInput &driver, BuildContext &context,
std::span<const std::string> expanded, std::size_t prefix_size,
const std::string *row_output) {
const auto &cwd = *context.working_directory;
Arguments semantic;
bool compile = false, matches_tu = false;
std::optional<fs::path> output;
fs::path compiler_source;
std::optional<std::string> language, tu_language;
for (std::size_t i = 0; i < expanded.size(); ++i) {
const std::string_view arg = expanded[i];
std::string rewritten;
if (i < prefix_size) {
if (!semantic.append(arg))
return std::unexpected("normalized argument limit exceeded");
continue;
}
if (arg == "-o") {
if (output || ++i == expanded.size() || expanded[i].starts_with('-'))
return std::unexpected("ambiguous compile output operand");
auto resolved = semantic_path(state, cwd, expanded[i], false);
if (!resolved)
return std::unexpected(std::move(resolved.error()));
output = (*resolved)->physical_path;
continue;
}
constexpr std::string_view options[]{"-I", "-isystem", "-iquote", "-D", "-U", "-x"};
auto op = std::ranges::find_if(options, [&](auto option) { return arg.starts_with(option); });
if (op != std::end(options)) {
auto value = arg.substr(op->size());
const bool separate = value.empty();
if (separate) {
if (++i == expanded.size())
return std::unexpected("missing compiler option operand");
value = expanded[i];
if (!semantic.append(*op))
return std::unexpected("normalized argument limit exceeded");
} else {
rewritten = *op;
}
if (*op == "-I" || *op == "-isystem" || *op == "-iquote") {
if (value.empty() || value == "-" || value.starts_with('=') ||
value.starts_with("$SYSROOT") || (!separate && value.starts_with('-')))
return std::unexpected("unsupported search-path operand");
auto path = semantic_path(state, cwd, value, true);
if (!path)
return std::unexpected(std::move(path.error()));
rewritten += (*path)->logical_path.native();
} else {
rewritten += value;
if (*op == "-x")
language = value;
}
} else if (!arg.starts_with('-')) {
auto source = semantic_path(state, cwd, arg, false);
if (!source)
return std::unexpected(std::move(source.error()));
compiler_source = (*source)->logical_path;
rewritten = compiler_source.native();
matches_tu = (*source)->physical_path == context.key.owning_tu;
tu_language = language;
} else {
compile |= arg == "-c";
rewritten = arg;
}
if (!semantic.append(rewritten))
return std::unexpected("normalized argument limit exceeded");
}
if (output) {
if (!compile)
return std::unexpected("an explicit output requires a compile-only command");
if (row_output) {
auto declared = semantic_path(state, cwd, *row_output, false);
if (!declared || *output != (*declared)->physical_path)
return std::unexpected("compiler output differs from the row output");
}
}
auto report = Workspace::classify_and_unwrap_command(semantic.values, driver.wrappers,
driver.tool.identity, driver.driver);
if (!report.allowed)
return std::unexpected(std::string(report.reason));
if (!matches_tu)
return std::unexpected("the classified translation unit differs from the row file");
if (!tu_language) {
// Both admitted driver dialects select C++ from the actual operand spelling.
// A symlink to a generated file can have a different suffix from its target.
constexpr std::string_view cxx_suffixes[]{".C", ".cc", ".cp", ".cpp", ".cxx", ".c++"};
if (std::ranges::contains(cxx_suffixes, compiler_source.extension().native()))
tu_language = "c++";
}
context.semantic_arguments = std::move(report.unwrapped_argv);
context.source_language = std::move(tu_language);
context.sources.front().compiler_path = std::move(compiler_source);
return {};
}
Result<void> analyze(Import &state, BuildContext &context, const fs::path &directory,
const fs::path &filename, const std::string *output) {
const auto &input = state.input;
const auto &root = input.scope.workspace.root;
if (has_parent_step(directory) || has_parent_step(filename) ||
!in_workspace(*context.working_directory, root) || !in_workspace(context.key.owning_tu, root))
return std::unexpected("row working directory or file has an ambiguous or external route");
const auto &original = *context.original;
Arguments command;
if (!original.arguments) {
auto tokens = tokenize(*original.command, Syntax::command);
if (!tokens)
return std::unexpected(std::move(tokens.error()));
command = std::move(*tokens);
}
const auto &raw = original.arguments ? *original.arguments : command.values;
auto prefix = check_prefix(input, raw);
if (!prefix)
return std::unexpected(std::move(prefix.error()));
const auto &driver = *input.driver;
if (std::ranges::any_of(raw, [](std::string_view arg) {
return arg.starts_with("--driver-mode") || arg.starts_with("--rsp-quoting");
}))
return std::unexpected("driver mode or response syntax override");
Expansion expansion{.state = state,
.cwd = *context.working_directory,
.syntax = driver.driver == Workspace::CompilerDriver::gcc ? Syntax::gcc_response
: Syntax::clang_response,
.bytes_left = std::min(input.scope.limits.max_response_file_bytes, 16 * mib)};
auto expanded = expansion.append(raw);
if (!expanded)
return expanded;
return normalize(state, driver, context, expansion.expanded.values, *prefix, output);
}
Result<void> import_row(Import &state, std::string_view raw) {
auto json = Protocol::parse_json(raw, max_row_depth);
if (!json)
return std::unexpected(std::move(json.error()));
const auto &object = std::get<Json::Object>(json->value); // take_row requires an object.
const auto field = [&](std::string_view key) { return Protocol::find_member(object, key); };
const auto *directory = Protocol::as_string(field("directory"));
const auto *file = Protocol::as_string(field("file"));
const auto *args = Protocol::as_array(field("arguments"));
const auto *command = Protocol::as_string(field("command"));
const auto *output = Protocol::as_string(field("output"));
if (!directory || !file || (field("command") && !command) || (field("arguments") && !args) ||
(field("output") && (!output || !path_text(*output))) || (!args && !command))
return std::unexpected("invalid compilation database field type or missing required field");
if (command && (command->size() > max_argv_bytes || command->contains('\0')))
return std::unexpected("invalid command string");
const auto &input = state.input;
auto cwd = resolve_path(input.database.logical_path.parent_path(), *directory, true);
if (!cwd)
return std::unexpected(std::move(cwd.error()));
auto tu = resolve_path(*cwd, *file, false);
if (!tu)
return std::unexpected(std::move(tu.error()));
auto id = state.record_id(raw);
if (!id)
return std::unexpected(std::move(id.error()));
OriginalCommand original{.metadata_file = input.database.logical_path,
.record_id = *id,
.original_record = std::string(raw)};
std::size_t cost = 1536 + raw.size() + path_cost(original.metadata_file) + path_cost(*cwd) +
3 * path_cost(*tu) + (input.profile ? input.profile->size() : 0);
if (args) {
if (args->empty() || args->size() > max_args)
return std::unexpected("expected a nonempty argument array within the count limit");
Arguments typed;
for (const auto &arg : *args) {
const auto *value = Protocol::as_string(&arg);
if (!value || !typed.append(*value))
return std::unexpected("invalid or oversized arguments array");
}
cost += typed.values.capacity() * sizeof(std::string) + typed.bytes;
original.arguments = std::move(typed.values);
}
if (command) {
original.command = *command;
cost += command->size();
}
if (!state.charge(state.remaining_storage, cost))
return std::unexpected("generation storage limit exceeded");
BuildContext context;
context.key = {.profile = input.profile, .alternative = std::move(*id)};
context.original = std::move(original);
auto location = bind_command_path(state, *cwd, CommandPathKind::directory);
if (location)
context.working_directory = has_parent_step(*cwd) ? (*location)->physical_path : *cwd;
auto owner = bind_command_path(state, *tu, CommandPathKind::file);
if (owner) {
context.key.owning_tu = (*owner)->physical_path;
context.sources.push_back({.source_path = context.key.owning_tu});
}
Result<void> result;
if (!owner)
result = std::unexpected(std::move(owner.error()));
else if (!location)
result = std::unexpected(std::move(location.error()));
else
result = analyze(state, context, *directory, *file, output);
if (state.exhausted)
return std::unexpected("generation resource limit exceeded");
if (!result) {
if (!state.charge(state.remaining_storage, result.error().size()))
return std::unexpected("generation storage limit exceeded");
context.limitations.push_back(std::move(result.error()));
} else {
std::size_t semantic_bytes = context.semantic_arguments->capacity() * sizeof(std::string);
for (const auto &arg : *context.semantic_arguments)
semantic_bytes += arg.size();
if (!state.charge(state.remaining_storage, semantic_bytes))
return std::unexpected("generation storage limit exceeded");
}
state.output.contexts.push_back(std::move(context));
return {};
}
// Include the observed driver, row outcomes and every logical response name and content.
// Length framing makes field boundaries independent of the bytes in a POSIX path or flag.
Result<std::string> revision(const Import &state) {
auto hash = Crypto::Hasher::create(Crypto::HashAlgorithm::Sha256);
if (!hash)
return std::unexpected("compilation database revision digest unavailable");
bool complete = true;
const auto add = [&](std::string_view value) {
const auto length = std::to_string(value.size()) + "/";
complete = complete && hash->update(length).has_value() && hash->update(value).has_value();
};
const auto &input = state.input;
add(input.database.logical_path.native());
add(input.database.canonical_path.native());
add(input.database.content_id);
add(input.profile.value_or(""));
if (input.driver) {
const auto &driver = *input.driver;
add("driver");
add(std::to_string(static_cast<int>(driver.driver)));
add(driver.tool.workspace_root.native());
add(std::to_string(static_cast<int>(driver.tool.operation)));
add(std::to_string(driver.tool.trust_generation));
const auto &identity = driver.tool.identity;
add(identity.selected_path.native());
add(identity.canonical_path.native());
add(std::to_string(identity.device));
add(std::to_string(identity.inode));
add(std::to_string(identity.file_size));
add(std::to_string(identity.mode));
add(std::to_string(identity.owner));
add(std::to_string(identity.group));
add(identity.content_hash_hex);
const auto &origin = driver.tool.selection_origin;
add(std::to_string(static_cast<int>(origin.layer)));
add(origin.base.native());
add(origin.selected_file ? origin.selected_file->native() : "");
add(std::to_string(origin.revision));
add(std::to_string(driver.wrappers.size()));
for (const auto &wrapper : driver.wrappers)
add(wrapper);
} else
add("no driver");
add(std::to_string(state.output.contexts.size()));
for (const auto &row : state.output.contexts)
add(row.limitations.empty() ? std::string_view{} : row.limitations.front());
for (const auto &file : state.output.dependencies) {
add(file.logical_path.native());
add(file.canonical_path.native());
add(file.content_id);
}
for (const auto &lookup : state.output.lookups.paths) {
add(lookup.logical_path.native());
add(lookup.physical_path.native());
add(lookup.issue);
}
for (const auto &failed : state.output.lookups.failed_responses) {
add(failed.issue.path.native());
add(failed.issue.code);
add(std::to_string(failed.byte_limit));
}
auto digest = hash->finalize();
if (!complete || !digest)
return std::unexpected("compilation database revision digest unavailable");
return Encoding::Hex::encode(*digest);
}
} // namespace
std::expected<ImportedCommands, ProviderIssue> import_commands(const DatabaseInput &input) {
const auto &db = input.database;
auto fail = [&](std::string message) {
return std::unexpected(ProviderIssue{"invalid_database", std::move(message), db.logical_path});
};
if (!db.bytes || !db.stamp || db.content_id.empty() || !db.logical_path.is_absolute() ||
(db.purpose != FilePurpose::database && db.purpose != FilePurpose::native_database))
return fail("expected an acquired compilation database");
if (!provider_file_current(input.scope, db))
return std::unexpected(ProviderIssue{"changed", "Compilation database binding changed", db.logical_path});
if (input.profile && !path_text(*input.profile))
return fail("invalid compilation profile");
if (db.bytes->size() > input.scope.limits.max_compdb_bytes)
return fail("compilation database byte limit exceeded");
Import state{.input = input};
std::string_view text = *db.bytes;
if (!consume(text, '['))
return fail("expected a compilation database array");
if (!consume(text, ']')) {
for (;;) {
if (state.output.contexts.size() == max_rows)
return fail("compilation database row limit exceeded");
auto row = take_row(text);
if (!row)
return fail(std::move(row.error()));
auto accepted = import_row(state, *row);
if (!accepted)
return fail("row " + std::to_string(state.output.contexts.size() + 1) + " — " +
accepted.error());
if (consume(text, ']'))
break;
if (!consume(text, ','))
return fail("expected a comma or end of compilation database");
const auto next = text.find_first_not_of(" \r\n\t");
text.remove_prefix(std::min(next, text.size()));
}
}
if (text.find_first_not_of(" \r\n\t") != text.npos)
return fail("trailing data after compilation database");
auto identity = revision(state);
if (!identity)
return fail(std::move(identity.error()));
state.output.revision = std::move(*identity);
return std::move(state.output);
}
} // namespace Void::LanguageServer::Build
+51
View File
@@ -0,0 +1,51 @@
#include <Void/LanguageServer/Build/Providers.hpp>
#include <iterator>
namespace Void::LanguageServer::Build {
ProviderObservation observe_compdb(const ProviderScope &scope, const std::filesystem::path &path,
const std::optional<DriverInput> &driver) {
ProviderObservation result{.provider = "compdb"};
auto file =
read_provider_file(scope, path, FilePurpose::database, scope.limits.max_compdb_bytes);
if (!file) {
if (file.error().code == "missing")
result.health = ProviderHealth::missing;
else if (file.error().code == "changed")
result.health = ProviderHealth::changed;
result.issues.push_back(std::move(file.error()));
return result;
}
result.inputs.push_back(std::move(*file));
auto commands = import_commands({scope, result.inputs.front(), std::nullopt, driver});
if (commands) {
const auto &logical = result.inputs.front().logical_path.native();
auto revision = std::to_string(logical.size()) + "/" + logical + "/" +
result.inputs.front().content_id + "/" + commands->revision;
auto generation = BuildGeneration::create({scope.workspace, "compdb", std::move(revision)},
commands->contexts);
result.inputs.insert(result.inputs.end(),
std::make_move_iterator(commands->dependencies.begin()),
std::make_move_iterator(commands->dependencies.end()));
result.lookups = std::move(commands->lookups);
if (generation) {
result.generation = std::move(*generation);
result.health = ProviderHealth::ready;
} else {
result.health = ProviderHealth::invalid;
result.issues.push_back(
{"invalid_context", "Invalid compilation database context", path});
}
} else {
result.health = ProviderHealth::invalid;
result.issues.push_back(std::move(commands.error()));
}
if (auto changed = changed_provider_input(scope, result)) {
result.health = ProviderHealth::changed;
result.generation.reset();
result.issues = {{"changed", "Compilation inputs changed during observation", *changed}};
}
return result;
}
} // namespace Void::LanguageServer::Build
+600
View File
@@ -0,0 +1,600 @@
#include <Void/LanguageServer/Build/Model.hpp>
#include <algorithm>
#include <limits>
#include <set>
#include <utility>
namespace Void::LanguageServer::Build {
namespace {
namespace fs = std::filesystem;
bool identifier(const std::string &value) { return !value.empty() && !value.contains('\0'); }
bool valid_optional(const std::optional<std::string> &value) {
return !value || identifier(*value);
}
bool absolute_path(const fs::path &path) {
return path.is_absolute() && !path.native().contains(fs::path::value_type{}) &&
path == path.lexically_normal() && (path == path.root_path() || path.has_filename());
}
bool file_path(const fs::path &path) { return absolute_path(path) && path.has_filename(); }
bool under_root(const fs::path &path, const fs::path &root) {
const auto [r, p] = std::mismatch(root.begin(), root.end(), path.begin(), path.end());
return r == root.end() && p != path.end();
}
bool valid_key(const ContextKey &key, bool allow_unresolved = false) {
return identifier(key.alternative) &&
(file_path(key.owning_tu) || (allow_unresolved && key.owning_tu.empty())) && valid_optional(key.profile) &&
valid_optional(key.target) &&
(key.role == ContextRole::target || key.role == ContextRole::host_description ||
key.role == ContextRole::unknown);
}
bool valid_arguments(const std::optional<std::vector<std::string>> &arguments) {
return !arguments ||
std::ranges::none_of(*arguments, [](const auto &arg) { return arg.contains('\0'); });
}
bool valid_availability(Availability availability) {
return availability == Availability::unknown || availability == Availability::missing ||
availability == Availability::stale || availability == Availability::ready;
}
bool valid_mapping(const SourceMapping &source, const fs::path &root) {
const bool known_origin =
source.origin == SourceOrigin::unknown || source.origin == SourceOrigin::workspace ||
source.origin == SourceOrigin::snapshot || source.origin == SourceOrigin::generated ||
source.origin == SourceOrigin::external;
const bool known_editability = source.editability == Editability::unknown ||
source.editability == Editability::editable ||
source.editability == Editability::read_only;
return known_origin && known_editability && file_path(source.source_path) &&
(!source.compiler_path || file_path(*source.compiler_path)) &&
valid_optional(source.provenance) &&
(source.origin != SourceOrigin::workspace || under_root(source.source_path, root));
}
std::expected<void, ModelError> prepare_context(BuildContext &context, const fs::path &root) {
const bool unresolved = context.key.owning_tu.empty();
if (!valid_key(context.key, true) || !valid_optional(context.source_language) ||
!valid_optional(context.toolchain) || !valid_optional(context.standard_library) ||
!valid_optional(context.environment) || !valid_arguments(context.semantic_arguments) ||
(context.working_directory && !absolute_path(*context.working_directory))) {
return std::unexpected(ModelError::invalid_context);
}
if (context.original) {
const auto &raw = *context.original;
if (!file_path(raw.metadata_file) || !identifier(raw.record_id) ||
!valid_arguments(raw.arguments)) {
return std::unexpected(ModelError::invalid_context);
}
}
if (context.prerequisites && !std::ranges::all_of(*context.prerequisites, [](const auto &p) {
return identifier(p.name) && valid_optional(p.input_identity) &&
valid_availability(p.state);
})) {
return std::unexpected(ModelError::invalid_context);
}
if (context.artifacts && !std::ranges::all_of(*context.artifacts, [](const auto &a) {
return file_path(a.path) && valid_optional(a.content_identity) &&
valid_availability(a.state);
})) {
return std::unexpected(ModelError::invalid_context);
}
std::ranges::sort(context.sources, {}, &SourceMapping::source_path);
const fs::path *previous = nullptr;
for (const auto &source : context.sources) {
if (!valid_mapping(source, root) || (previous && *previous == source.source_path)) {
return std::unexpected(ModelError::invalid_mapping);
}
previous = &source.source_path;
}
if (unresolved) {
if (!context.original || !context.original->original_record || context.limitations.empty() ||
!context.sources.empty() || context.semantic_arguments)
return std::unexpected(ModelError::invalid_mapping);
} else if (!context.mapping_for(context.key.owning_tu)) {
return std::unexpected(ModelError::invalid_mapping);
}
return {};
}
bool editor_matches(const EditorSelection &editor, const ContextKey &key) {
return (!editor.profile || editor.profile == key.profile) &&
(!editor.target || editor.target == key.target) &&
(!editor.alternative || *editor.alternative == key.alternative) &&
(!editor.role || *editor.role == key.role);
}
bool same_source(const Snapshot &a, const Snapshot &b) {
return a == b || (a && b && a->same_input_as(*b));
}
bool same_dependencies(const std::optional<std::vector<DependencyInput>> &a,
const std::optional<std::vector<DependencyInput>> &b) {
if (!a || !b) {
return a.has_value() == b.has_value();
}
return std::ranges::equal(*a, *b, [](const auto &left, const auto &right) {
return left.kind == right.kind && left.name == right.name &&
left.lookup_path == right.lookup_path && same_source(left.source, right.source);
});
}
bool valid_snapshot(const Snapshot &snapshot) {
return snapshot && snapshot->revision_id != 0 && snapshot->identity.is_file_uri &&
identifier(snapshot->identity.canonical_uri) &&
file_path(snapshot->identity.canonical_path) &&
((snapshot->origin == Documents::DocumentOrigin::overlay && snapshot->version) ||
(snapshot->origin == Documents::DocumentOrigin::disk && !snapshot->version));
}
bool consistent_sources(const AnalysisInputs &inputs) {
std::map<fs::path, const Documents::DocumentSnapshot *> seen;
auto record = [&](const Snapshot &source) {
if (!valid_snapshot(source)) {
return false;
}
const auto [it, inserted] = seen.emplace(source->identity.canonical_path, source.get());
return inserted || it->second == source.get() || it->second->same_input_as(*source);
};
if ((inputs.document && !record(inputs.document)) ||
(inputs.translation_unit && !record(inputs.translation_unit))) {
return false;
}
return !inputs.dependencies || std::ranges::all_of(*inputs.dependencies, [&](const auto &dep) {
return identifier(dep.name) && file_path(dep.lookup_path) && record(dep.source);
});
}
std::expected<void, ModelError> validate_coverage(const RenameCoverage &coverage,
const ContextSelection &selection) {
const auto &workspace = selection.scope->workspace;
std::set<fs::path> roots;
for (const auto &root : coverage.workspace_roots) {
if (!absolute_path(root) || !roots.insert(root).second) {
return std::unexpected(ModelError::invalid_input);
}
}
if (!roots.contains(workspace.root)) {
return std::unexpected(ModelError::wrong_scope);
}
if (!valid_optional(coverage.editable_spelling_proof)) {
return std::unexpected(ModelError::invalid_input);
}
if (!coverage.contexts) {
return {};
}
std::map<std::pair<fs::path, std::string>, const BuildGeneration *> generations;
const auto &selected = selection.generation->identity();
generations.emplace(std::pair{workspace.root, selected.provider}, selection.generation.get());
std::set<const BuildContext *> seen;
for (const auto &proof : *coverage.contexts) {
if (!proof.generation || !valid_optional(proof.verification)) {
return std::unexpected(ModelError::invalid_input);
}
const auto &id = proof.generation->identity();
if (id.workspace.session != workspace.session || !roots.contains(id.workspace.root)) {
return std::unexpected(ModelError::wrong_scope);
}
const auto [it, inserted] =
generations.emplace(std::pair{id.workspace.root, id.provider}, proof.generation.get());
const auto *context = proof.generation->find(proof.key);
if ((!inserted && it->second != proof.generation.get()) || !context ||
!seen.insert(context).second) {
return std::unexpected(ModelError::invalid_input);
}
}
return {};
}
bool known_mapping(const SourceMapping *mapping) {
return mapping && mapping->compiler_path && mapping->origin != SourceOrigin::unknown &&
mapping->provenance;
}
struct ContextReadiness {
bool diagnostic_command{};
std::vector<InputIssue> missing;
};
ContextReadiness assess_context(const BuildGeneration &generation, const BuildContext &context,
const fs::path &file) {
ContextReadiness facts;
auto need = [&](bool available, InputIssue issue) {
if (!available) {
facts.missing.push_back(issue);
}
};
need(context.source_language.has_value(), InputIssue::language);
need(context.semantic_arguments && !context.semantic_arguments->empty() &&
!context.semantic_arguments->front().empty(),
InputIssue::command);
need(context.working_directory.has_value(), InputIssue::working_directory);
facts.diagnostic_command = facts.missing.empty();
const auto &raw = context.original;
need(raw && ((raw->arguments && !raw->arguments->empty() && !raw->arguments->front().empty()) ||
(raw->command && identifier(*raw->command)) ||
(raw->original_record && !raw->original_record->empty())),
InputIssue::command_provenance);
need(known_mapping(context.mapping_for(context.key.owning_tu)) &&
known_mapping(context.mapping_for(file)),
InputIssue::source_mapping);
need(context.toolchain.has_value(), InputIssue::toolchain);
need(context.standard_library.has_value(), InputIssue::standard_library);
need(context.environment.has_value(), InputIssue::environment);
need(context.prerequisites && std::ranges::all_of(*context.prerequisites,
[](const auto &p) {
return p.state == Availability::ready &&
p.input_identity;
}),
InputIssue::prerequisites);
need(context.artifacts && std::ranges::all_of(*context.artifacts,
[&](const auto &artifact) {
return artifact.state ==
Availability::ready &&
artifact.content_identity &&
generation.retains_artifacts();
}),
InputIssue::artifacts);
need(context.limitations.empty(), InputIssue::provider_limitation);
return facts;
}
bool covered(const ContextSelection &selection, const RenameCoverage &coverage) {
if (!selection.selected || !coverage.contexts) {
return false;
}
std::set<const BuildContext *> verified;
std::set<const BuildGeneration *> generations{selection.generation.get()};
for (const auto &proof : *coverage.contexts) {
if (!proof.verification) {
return false;
}
const auto *context = proof.generation->find(proof.key);
const auto &file = context->mapping_for(selection.scope->file) ? selection.scope->file
: proof.key.owning_tu;
if (!assess_context(*proof.generation, *context, file).missing.empty()) {
return false;
}
generations.insert(proof.generation.get());
verified.insert(context);
}
for (const auto *generation : generations) {
if (!std::ranges::all_of(generation->candidates(selection.scope->file),
[&](auto candidate) { return verified.contains(candidate); })) {
return false;
}
}
return true;
}
std::array<Readiness, 4> assess(const ContextSelection &selection, const AnalysisInputs &inputs) {
std::vector<InputIssue> issues;
auto need = [&](bool available, InputIssue issue) {
if (!available) {
issues.push_back(issue);
}
};
const auto *context = selection.selected;
need(context != nullptr, InputIssue::context);
need(inputs.document != nullptr, InputIssue::document);
need(inputs.translation_unit != nullptr, InputIssue::translation_unit);
need(inputs.backend.has_value(), InputIssue::backend);
need(inputs.configuration_generation.has_value(), InputIssue::configuration);
need(inputs.trust_generation.has_value(), InputIssue::trust);
bool diagnostic_inputs = issues.empty();
if (context) {
auto facts = assess_context(*selection.generation, *context, selection.scope->file);
diagnostic_inputs = diagnostic_inputs && facts.diagnostic_command;
issues.append_range(facts.missing);
}
need(inputs.dependencies.has_value(), InputIssue::dependencies);
need(inputs.lookup_epoch.has_value(), InputIssue::lookup_coverage);
const auto observed = issues.empty() ? ReadinessLevel::ready : ReadinessLevel::degraded;
const Readiness status{observed, issues};
const Readiness diagnostics{diagnostic_inputs ? observed : ReadinessLevel::unavailable, issues};
const Readiness semantic{issues.empty() ? ReadinessLevel::ready : ReadinessLevel::unavailable,
issues};
need(inputs.rename && covered(selection, *inputs.rename), InputIssue::affected_contexts);
const auto *document_mapping = context ? context->mapping_for(selection.scope->file) : nullptr;
need(document_mapping && document_mapping->editability == Editability::editable &&
inputs.rename && inputs.rename->editable_spelling_proof,
InputIssue::edit_provenance);
return {status, diagnostics, semantic,
Readiness{issues.empty() ? ReadinessLevel::ready : ReadinessLevel::unavailable,
std::move(issues)}};
}
bool regresses(std::optional<std::uint64_t> value, std::optional<std::uint64_t> floor) {
return value && floor && *value < *floor;
}
} // namespace
const SourceMapping *BuildContext::mapping_for(const fs::path &source) const {
const auto it = std::ranges::find(sources, source, &SourceMapping::source_path);
return it != sources.end() ? &*it : nullptr;
}
BuildGeneration::BuildGeneration(GenerationIdentity identity, std::vector<BuildContext> records,
std::shared_ptr<const ArtifactLease> lease)
: identity_(std::move(identity)), records_(std::move(records)), lease_(std::move(lease)) {
for (const auto &record : records_) {
for (const auto &source : record.sources) {
by_source_[source.source_path].push_back(&record);
}
}
}
std::expected<Generation, ModelError>
BuildGeneration::create(const GenerationIdentity &identity,
const std::vector<BuildContext> &supplied,
std::shared_ptr<const ArtifactLease> lease) {
if (!absolute_path(identity.workspace.root) || !identifier(identity.workspace.session) ||
!identifier(identity.provider) || !identifier(identity.revision)) {
return std::unexpected(ModelError::invalid_identity);
}
auto records = supplied;
std::ranges::sort(records, {}, &BuildContext::key);
const ContextKey *previous = nullptr;
for (auto &context : records) {
if (previous && *previous == context.key) {
return std::unexpected(ModelError::duplicate_context);
}
if (auto valid = prepare_context(context, identity.workspace.root); !valid) {
return std::unexpected(valid.error());
}
previous = &context.key;
}
return Generation{new BuildGeneration(identity, std::move(records), std::move(lease))};
}
std::span<const BuildContext *const> BuildGeneration::candidates(const fs::path &source) const {
const auto it = by_source_.find(source);
if (it == by_source_.end()) {
return {};
}
return it->second;
}
const BuildContext *BuildGeneration::find(const ContextKey &key) const {
if (key.owning_tu.empty())
return nullptr;
const auto it = std::ranges::lower_bound(records_, key, {}, &BuildContext::key);
return it != records_.end() && it->key == key ? &*it : nullptr;
}
ContextSelection::ContextSelection(std::shared_ptr<const SelectionScope> scope,
Generation generation, std::uint64_t revision,
std::optional<FileOverride> file_override,
std::optional<EditorSelection> editor, SelectionReason reason,
const BuildContext *selected)
: scope(std::move(scope)), generation(std::move(generation)), revision(revision),
file_override(std::move(file_override)), editor(std::move(editor)), reason(reason),
selected(selected) {}
SelectionState::SelectionState(const WorkspaceIdentity &workspace, const fs::path &file)
: scope_(std::make_shared<const SelectionScope>(workspace, file)) {}
std::expected<Selection, ModelError>
SelectionState::update(Generation generation, const std::optional<FileOverride> &file_override,
const std::optional<EditorSelection> &editor) {
if (!generation || !file_path(scope_->file)) {
return std::unexpected(ModelError::invalid_identity);
}
if (generation->identity().workspace != scope_->workspace ||
(file_override && (file_override->workspace_root != scope_->workspace.root ||
file_override->file != scope_->file)) ||
(editor && editor->workspace_root != scope_->workspace.root)) {
return std::unexpected(ModelError::wrong_scope);
}
if ((file_override &&
(!identifier(file_override->provider) || !valid_key(file_override->key))) ||
(editor && (!identifier(editor->provider) || !valid_optional(editor->profile) ||
!valid_optional(editor->target) || !valid_optional(editor->alternative) ||
!(editor->profile || editor->target || editor->alternative || editor->role)))) {
return std::unexpected(ModelError::invalid_identity);
}
if (current_ && current_->generation == generation &&
current_->file_override == file_override && current_->editor == editor) {
return current_;
}
if (current_ && current_->revision == std::numeric_limits<std::uint64_t>::max()) {
return std::unexpected(ModelError::sequence_exhausted);
}
const auto candidates = generation->candidates(scope_->file);
const BuildContext *selected = nullptr;
auto reason = SelectionReason::no_owner;
if (file_override) {
if (file_override->provider == generation->identity().provider) {
selected = generation->find(file_override->key);
}
if (selected && selected->mapping_for(scope_->file)) {
reason = SelectionReason::file_override;
} else {
reason = SelectionReason::missing_override;
selected = nullptr;
}
} else if (!candidates.empty()) {
selected = candidates.front();
reason = SelectionReason::fallback;
if (editor && editor->provider == generation->identity().provider) {
const auto match = std::ranges::find_if(candidates, [&](auto candidate) {
return editor_matches(*editor, candidate->key);
});
if (match != candidates.end()) {
reason = SelectionReason::editor;
selected = *match;
}
}
}
current_ = Selection{new ContextSelection(scope_, std::move(generation),
current_ ? current_->revision + 1 : 1, file_override,
editor, reason, selected)};
return current_;
}
AnalysisRevision::AnalysisRevision(Selection selection, AnalysisInputs inputs)
: selection(std::move(selection)), inputs(std::move(inputs)),
readiness_(assess(*this->selection, this->inputs)) {}
std::expected<Revision, ModelError> AnalysisRevision::capture(Selection selection,
const AnalysisInputs &observed) {
auto inputs = observed;
if (!selection || !consistent_sources(inputs)) {
return std::unexpected(ModelError::invalid_input);
}
if (inputs.document && inputs.document->identity.canonical_path != selection->scope->file) {
return std::unexpected(ModelError::wrong_scope);
}
if (inputs.translation_unit &&
(!selection->selected ||
inputs.translation_unit->identity.canonical_path != selection->selected->key.owning_tu)) {
return std::unexpected(ModelError::wrong_scope);
}
if (!inputs.translation_unit && selection->selected &&
selection->scope->file == selection->selected->key.owning_tu) {
inputs.translation_unit = inputs.document;
}
if (inputs.backend &&
(!identifier(inputs.backend->implementation) || !identifier(inputs.backend->version) ||
!identifier(inputs.backend->protocol))) {
return std::unexpected(ModelError::invalid_identity);
}
if (inputs.rename) {
if (auto valid = validate_coverage(*inputs.rename, *selection); !valid) {
return std::unexpected(valid.error());
}
}
return Revision{new AnalysisRevision(std::move(selection), std::move(inputs))};
}
const Readiness &AnalysisRevision::readiness(Operation operation) const {
const auto index = static_cast<std::size_t>(operation);
if (index >= readiness_.size()) {
static const Readiness unavailable{ReadinessLevel::unavailable, {}};
return unavailable;
}
return readiness_[index];
}
bool AnalysisRevision::same_input_as(const AnalysisRevision &other) const {
return this == &other ||
(selection == other.selection && inputs.lookup_epoch == other.inputs.lookup_epoch &&
inputs.configuration_generation == other.inputs.configuration_generation &&
inputs.trust_generation == other.inputs.trust_generation &&
inputs.backend == other.inputs.backend && inputs.rename == other.inputs.rename &&
same_source(inputs.document, other.inputs.document) &&
same_source(inputs.translation_unit, other.inputs.translation_unit) &&
same_dependencies(inputs.dependencies, other.inputs.dependencies));
}
PublicationSlot::PublicationSlot(const SelectionState &selection, Operation operation)
: scope_(selection.scope()), operation_(operation) {}
std::expected<void, ModelError> PublicationSlot::replace_inputs(std::uint64_t sequence,
Revision revision) {
if (revision && revision->selection->scope != scope_) {
return std::unexpected(ModelError::wrong_scope);
}
State retired;
std::lock_guard lock{mutex_};
if (sequence <= sequence_) {
return std::unexpected(ModelError::superseded);
}
sequence_ = sequence;
if (revision) {
const auto &inputs = revision->inputs;
if (revision->selection->revision < selection_floor_ ||
regresses(inputs.trust_generation, trust_floor_) ||
regresses(inputs.configuration_generation, configuration_floor_) ||
regresses(inputs.lookup_epoch, lookup_floor_)) {
std::swap(retired, state_);
return std::unexpected(ModelError::superseded);
}
selection_floor_ = revision->selection->revision;
if (inputs.trust_generation) {
trust_floor_ = inputs.trust_generation;
}
if (inputs.configuration_generation) {
configuration_floor_ = inputs.configuration_generation;
}
if (inputs.lookup_epoch) {
lookup_floor_ = inputs.lookup_epoch;
}
if (state_.revision && state_.revision->same_input_as(*revision)) {
return {};
}
}
// A lease destructor can run provider code. Release displaced owners after unlocking.
std::swap(retired, state_);
state_.revision = std::move(revision);
return {};
}
void PublicationSlot::revoke_trust(const WorkspaceIdentity &workspace,
std::uint64_t new_generation) {
if (scope_->workspace != workspace) {
return;
}
State retired;
std::lock_guard lock{mutex_};
if (trust_floor_ && new_generation <= *trust_floor_) {
return;
}
trust_floor_ = new_generation;
std::swap(retired, state_);
}
std::expected<Ticket, ModelError> PublicationSlot::issue() {
std::lock_guard lock{mutex_};
if (!state_.revision) {
return std::unexpected(ModelError::no_inputs);
}
if (state_.revision->readiness(operation_).level == ReadinessLevel::unavailable) {
return std::unexpected(ModelError::operation_unavailable);
}
if (last_request_ == std::numeric_limits<std::uint64_t>::max()) {
return std::unexpected(ModelError::sequence_exhausted);
}
state_.pending =
std::make_shared<const AnalysisRequest>(++last_request_, operation_, state_.revision);
return state_.pending;
}
bool PublicationSlot::cancel(const Ticket &ticket) {
std::lock_guard lock{mutex_};
if (!ticket || state_.pending != ticket) {
return false;
}
state_.pending.reset();
return true;
}
bool PublicationSlot::publish(const Ticket &ticket, std::string_view validated_payload) {
if (!ticket) {
return false;
}
auto result = std::make_shared<const Publication>(ticket, std::string{validated_payload});
std::lock_guard lock{mutex_};
if (state_.pending != ticket) {
return false;
}
state_.published.swap(result);
state_.pending.reset();
return true;
}
std::shared_ptr<const Publication> PublicationSlot::current() const {
std::lock_guard lock{mutex_};
return state_.published;
}
} // namespace Void::LanguageServer::Build
+522
View File
@@ -0,0 +1,522 @@
#include <Void/LanguageServer/Build/Providers.hpp>
#include <Void/LanguageServer/Support/RegularFile.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <algorithm>
#include <array>
#include <cerrno>
#include <map>
#include <string_view>
#include <tuple>
#include <linux/openat2.h>
#include <sys/syscall.h>
namespace Void::LanguageServer::Build {
namespace fs = std::filesystem;
using System::OwnedFd;
namespace {
struct Directory {
fs::path path;
OwnedFd fd;
struct stat identity;
};
using Anchor = std::shared_ptr<const Directory>;
bool same_inode(const struct stat &a, const struct stat &b) {
return a.st_dev == b.st_dev && a.st_ino == b.st_ino;
}
bool normalized(const fs::path &path) {
return Detail::valid_path(path) && path.is_absolute() && path == path.lexically_normal() &&
(path == path.root_path() || path.has_filename());
}
bool below(const fs::path &path, const fs::path &root) {
const auto [r, p] = std::mismatch(root.begin(), root.end(), path.begin(), path.end());
return r == root.end() && p != path.end();
}
OwnedFd open_direct(int parent, const fs::path &path, int flags, bool beneath) {
open_how how{};
how.flags = static_cast<unsigned>(flags | O_PATH | O_CLOEXEC);
how.resolve = RESOLVE_NO_SYMLINKS | RESOLVE_NO_MAGICLINKS;
if (beneath)
how.resolve |= RESOLVE_BENEATH;
return OwnedFd{
static_cast<int>(::syscall(SYS_openat2, parent, path.c_str(), &how, sizeof how))};
}
ProviderIssue open_error(int code, FilePurpose purpose, const fs::path &path) {
if (code == ENOENT) {
const bool required =
purpose == FilePurpose::status || purpose == FilePurpose::native_database;
return {required ? "missing_reference" : "missing", "Metadata path is absent", path};
}
if (code == ELOOP || code == EXDEV)
return {"outside_scope", "Path follows a disallowed link or leaves the selected directory",
path};
if (code == EAGAIN || code == ESTALE)
return {"changed", "Path changed during lookup", path};
return {"unavailable", "Cannot open the admitted path", path};
}
std::expected<Anchor, ProviderIssue> bind_directory(const fs::path &path) {
if (!normalized(path))
return std::unexpected(
ProviderIssue{"invalid_path", "Expected a normalized absolute directory", path});
auto fd = open_direct(AT_FDCWD, path, O_DIRECTORY, false);
struct stat state{};
if (!fd || ::fstat(fd.get(), &state) != 0)
return std::unexpected(
ProviderIssue{"unavailable", "Cannot bind the selected directory", path});
return std::make_shared<Directory>(path, std::move(fd), state);
}
bool directory_current(const Anchor &anchor) {
auto named = open_direct(AT_FDCWD, anchor->path, O_DIRECTORY, false);
struct stat state{};
return named && ::fstat(named.get(), &state) == 0 && same_inode(anchor->identity, state);
}
bool native_locator(const fs::path &path, const fs::path &anchor, bool exact_root,
FilePurpose purpose) {
auto editor = path.parent_path();
if (purpose == FilePurpose::native_database) {
const auto id = editor.filename().native();
if (path.filename() != "compile_commands.json" || id.size() != 16 ||
id.find_first_not_of("0123456789abcdef") != id.npos ||
editor.parent_path().filename() != "generations")
return false;
editor = editor.parent_path().parent_path();
} else if (path.filename() != "status.json") {
return false;
}
const auto profile = editor.parent_path();
const auto profiles = profile.parent_path();
const auto component = profile.filename().native();
if (editor.filename() != "editor" || profiles.filename() != "profiles" || component.empty() ||
component.size() > 255 ||
component.find_first_not_of(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-") != component.npos)
return false;
const auto root = profiles.parent_path();
return root == anchor || (!exact_root && below(root, anchor));
}
struct Route {
Anchor anchor;
bool permit_leaf_link{};
};
struct OpenedFile {
OwnedFd object, link;
fs::path canonical;
struct stat metadata{}, parent{};
std::optional<struct stat> link_state;
};
} // namespace
struct ProviderAnchors {
ProviderScope requested; // Captured before installing the shared anchors in the returned scope.
// A failed optional grant stays failed for its lifetime, even if the name later appears.
std::map<fs::path, std::expected<Anchor, ProviderIssue>> directories;
};
struct ProviderStamp {
std::shared_ptr<const ProviderAnchors> anchors;
FilePurpose purpose;
fs::path logical;
OpenedFile file;
};
struct CommandPathStamp {
std::shared_ptr<const ProviderAnchors> anchors;
CommandPathKind kind;
std::pair<dev_t, ino_t> object{};
std::vector<std::tuple<dev_t, ino_t, time_t, long>> links;
bool operator==(const CommandPathStamp &) const = default;
};
std::expected<ProviderScope, ProviderIssue> bind_provider_scope(ProviderScope scope) {
if (scope.anchors || scope.workspace.session.empty() || !normalized(scope.workspace.root))
return std::unexpected(
ProviderIssue{"invalid_path", "Invalid workspace binding", scope.workspace.root});
auto binding = std::make_shared<ProviderAnchors>();
binding->requested = scope;
auto add = [&](const fs::path &path) -> const std::expected<Anchor, ProviderIssue> & {
auto [it, fresh] = binding->directories.try_emplace(path);
if (fresh)
it->second = bind_directory(path);
return it->second;
};
if (auto owner = add(scope.workspace.root); !owner)
return std::unexpected(std::move(owner.error()));
if (scope.build_root)
add(*scope.build_root);
for (const auto *grant : {&scope.exact_selector, &scope.exact_database}) {
if (!*grant)
continue;
const auto &file = **grant;
// route_for validates the spelling when the locator is actually used.
// An unusable optional locator cannot invalidate the workspace binding.
if (normalized(file) && file.has_filename() && !below(file, scope.workspace.root))
add(file.parent_path());
}
scope.anchors = std::move(binding);
return scope;
}
std::expected<ProviderScope, ProviderIssue> reuse_provider_scope(const ProviderScope &bound,
std::string new_session) {
if (!bound.anchors || new_session.empty() || new_session.contains('\0'))
return std::unexpected(
ProviderIssue{"invalid_path", "Invalid workspace incarnation", bound.workspace.root});
const auto &root = bound.anchors->requested.workspace.root;
if (!directory_current(*bound.anchors->directories.at(root)))
return std::unexpected(ProviderIssue{"changed", "The workspace directory was replaced", root});
auto anchors = std::make_shared<ProviderAnchors>(*bound.anchors);
anchors->requested.workspace.session = std::move(new_session);
auto scope = anchors->requested;
scope.anchors = std::move(anchors);
return scope;
}
namespace {
std::expected<Anchor, ProviderIssue> workspace_anchor(const ProviderScope &scope, const fs::path &path) {
if (!scope.anchors)
return std::unexpected(
ProviderIssue{"invalid_path", "Unbound workspace scope", path});
const auto &bound = scope.anchors->requested;
if (scope.workspace != bound.workspace || scope.exact_database != bound.exact_database ||
scope.exact_selector != bound.exact_selector || scope.build_root != bound.build_root ||
scope.producer_cwd != bound.producer_cwd)
return std::unexpected(ProviderIssue{"outside_scope", "Metadata grant has changed", path});
const auto workspace = *scope.anchors->directories.at(bound.workspace.root);
if (!directory_current(workspace))
return std::unexpected(
ProviderIssue{"changed", "Workspace directory was replaced", path});
return workspace;
}
std::expected<Route, ProviderIssue> route_for(const ProviderScope &scope, const fs::path &path,
FilePurpose purpose) {
if (!normalized(path) || !path.has_filename())
return std::unexpected(ProviderIssue{"invalid_path", "Invalid metadata path", path});
const auto owner = workspace_anchor(scope, path);
if (!owner)
return std::unexpected(owner.error());
const auto &workspace = *owner;
const auto &bound = scope.anchors->requested;
const bool native = purpose == FilePurpose::status || purpose == FilePurpose::native_database;
const fs::path *authority = &workspace->path;
bool leaf_link = false;
if (native) {
if (bound.build_root)
authority = &*bound.build_root;
if (!native_locator(path, *authority, bound.build_root.has_value(), purpose))
return std::unexpected(
ProviderIssue{"outside_scope", "Invalid native generation locator", path});
} else if (below(path, workspace->path)) {
leaf_link = purpose == FilePurpose::database || purpose == FilePurpose::response;
} else if ((purpose == FilePurpose::database && bound.exact_database == path) ||
(purpose == FilePurpose::selection && bound.exact_selector == path)) {
const auto &anchor = scope.anchors->directories.at(path.parent_path());
if (!anchor)
return std::unexpected(ProviderIssue{anchor.error().code, anchor.error().message, path});
if (!directory_current(*anchor))
return std::unexpected(
ProviderIssue{"changed", "Selected metadata directory was replaced", path});
return Route{*anchor, false};
} else {
return std::unexpected(
ProviderIssue{"outside_scope", "Path is outside this workspace grant", path});
}
const auto &anchor = scope.anchors->directories.at(*authority);
if (!anchor)
return std::unexpected(ProviderIssue{anchor.error().code, anchor.error().message, path});
if (*anchor != workspace && !directory_current(*anchor))
return std::unexpected(
ProviderIssue{"changed", "Selected build directory was replaced", path});
return Route{*anchor, leaf_link};
}
// A link may backtrack through the already verified containing directory.
// A later '..' would need to traverse additional, unverified components.
std::optional<fs::path> link_target(int link, const fs::path &logical, const fs::path &root,
bool allow_root = false) {
std::array<char, 4096> name{};
const auto size = ::readlinkat(link, "", name.data(), name.size());
if (size <= 0 || static_cast<std::size_t>(size) == name.size())
return {};
const fs::path target{std::string{name.data(), static_cast<std::size_t>(size)}};
bool descending = target.is_absolute();
for (const auto &part : target) {
if (part == ".." && descending)
return {};
if (part != ".." && part != ".")
descending = true;
}
const auto resolved = (logical.parent_path() / target).lexically_normal();
if (!normalized(resolved) || (!below(resolved, root) && !(allow_root && resolved == root)))
return {};
return resolved;
}
std::expected<OpenedFile, ProviderIssue> open_file(const Route &route, const fs::path &path,
FilePurpose purpose) {
const auto parent_name = path.parent_path().lexically_relative(route.anchor->path);
auto parent = open_direct(route.anchor->fd.get(), parent_name, O_DIRECTORY, true);
if (!parent)
return std::unexpected(open_error(errno, purpose, path));
OpenedFile result;
if (::fstat(parent.get(), &result.parent) != 0)
return std::unexpected(
ProviderIssue{"unavailable", "Cannot identify metadata directory", path});
result.object = open_direct(parent.get(), path.filename(), O_NOFOLLOW, true);
if (!result.object)
return std::unexpected(open_error(errno, purpose, path));
if (::fstat(result.object.get(), &result.metadata) != 0)
return std::unexpected(ProviderIssue{"unavailable", "Cannot identify metadata file", path});
result.canonical = path;
if (S_ISLNK(result.metadata.st_mode)) {
if (!route.permit_leaf_link)
return std::unexpected(
ProviderIssue{"outside_scope", "This locator must be a direct file", path});
const auto target = link_target(result.object.get(), path, route.anchor->path);
if (!target)
return std::unexpected(
ProviderIssue{"outside_scope", "Link target is outside the admitted path", path});
result.link_state = result.metadata;
result.link = std::move(result.object);
result.object = open_direct(route.anchor->fd.get(),
target->lexically_relative(route.anchor->path), 0, true);
if (!result.object || ::fstat(result.object.get(), &result.metadata) != 0)
return std::unexpected(ProviderIssue{
"unavailable", "Cannot resolve metadata link to a direct file", path});
result.canonical = *target;
}
if (!S_ISREG(result.metadata.st_mode))
return std::unexpected(
ProviderIssue{"not_regular", "Metadata must be a regular file", path});
return result;
}
std::size_t allowed_bytes(const Workspace::ResourceLimitsConfig &limits, FilePurpose purpose) {
if (purpose == FilePurpose::response)
return limits.max_response_file_bytes;
if (purpose == FilePurpose::database || purpose == FilePurpose::native_database)
return limits.max_compdb_bytes;
return limits.max_manifest_bytes;
}
bool same_capture(const OpenedFile &a, const OpenedFile &b) {
return a.canonical == b.canonical && same_inode(a.parent, b.parent) &&
Detail::same_file_state(a.metadata, b.metadata) &&
a.link_state.has_value() == b.link_state.has_value() &&
(!a.link_state || Detail::same_file_state(*a.link_state, *b.link_state));
}
struct PathResult {
fs::path physical;
std::string issue;
};
bool expected_kind(const struct stat &state, CommandPathKind kind) {
return kind == CommandPathKind::directory ? S_ISDIR(state.st_mode) : S_ISREG(state.st_mode);
}
// Open every name beneath the original root descriptor. Never follow a kernel symlink
// or descend from a directory descriptor that may since have moved outside the root.
struct CommandPathWalk {
const Directory &root;
CommandPathStamp &stamp;
unsigned steps{};
PathResult resolve(const fs::path &path, CommandPathKind kind, bool require_present = false) {
const auto relative = path.lexically_relative(root.path);
// Ordinary direct paths, including prospective generated inputs, take one lookup.
if (normalized(path)) {
auto file = open_direct(root.fd.get(), relative, O_NOFOLLOW, true);
struct stat state{};
if (file) {
if (::fstat(file.get(), &state) != 0)
return {{}, "unavailable"};
if (!S_ISLNK(state.st_mode)) {
stamp.object = {state.st_dev, state.st_ino};
return expected_kind(state, kind) ? PathResult{path, {}} : PathResult{{}, "wrong_kind"};
}
} else if (errno != ELOOP) {
const int error = errno;
if (error == ENOENT && !require_present)
return {path, "missing"};
return {{}, error == ENOENT ? "unavailable" : open_error(error, FilePurpose::response, path).code};
}
}
fs::path current = root.path;
bool missing = false;
for (auto it = relative.begin(); it != relative.end(); ++it) {
if (++steps > 256)
return {{}, "path_limit"};
if (it->empty() || *it == ".")
continue;
if (*it == "..") {
if (current == root.path || missing)
return {{}, "unresolved_parent"};
current = current.parent_path();
continue;
}
current /= *it;
if (!Detail::valid_path(current))
return {{}, "path_limit"};
if (missing)
continue;
const auto required = std::next(it) == relative.end() ? kind : CommandPathKind::directory;
auto fd = open_direct(root.fd.get(), current.lexically_relative(root.path), O_NOFOLLOW, true);
if (!fd) {
const int error = errno;
if (error == ENOENT && !require_present) {
missing = true;
continue;
}
return {{}, error == ENOENT ? "unavailable" : open_error(error, FilePurpose::response, current).code};
}
struct stat state{};
if (::fstat(fd.get(), &state) != 0)
return {{}, "unavailable"};
stamp.object = {state.st_dev, state.st_ino};
if (S_ISLNK(state.st_mode)) {
if (stamp.links.size() == 16)
return {{}, "link_limit"};
stamp.links.emplace_back(state.st_dev, state.st_ino, state.st_ctim.tv_sec, state.st_ctim.tv_nsec);
auto target = link_target(fd.get(), current, root.path, required == CommandPathKind::directory);
if (!target)
return {{}, "outside_scope"};
auto resolved = resolve(*target, required, true);
if (resolved.physical.empty())
return resolved;
current = std::move(resolved.physical);
} else if (!expected_kind(state, required)) {
return {{}, "wrong_kind"};
}
}
return {std::move(current), missing ? "missing" : ""};
}
};
bool failed_response_current(const ProviderScope &scope, const FailedResponseLookup &failed) {
const auto &issue = failed.issue;
const auto purpose = FilePurpose::response;
auto route = route_for(scope, issue.path, purpose);
if (!route)
return route.error().code == issue.code;
auto fresh = open_file(*route, issue.path, purpose);
if (!fresh)
return fresh.error().code == issue.code;
const auto limit = std::min({failed.byte_limit, allowed_bytes(scope.limits, purpose),
allowed_bytes(scope.anchors->requested.limits, purpose)});
if (fresh->metadata.st_size < 0 || static_cast<std::uint64_t>(fresh->metadata.st_size) > limit)
return issue.code == "too_large";
// Permission failures can persist on a regular file. A successful namespace probe of a
// previously absent/refused name invalidates that observation without reading its contents.
return issue.code == "unavailable" &&
::faccessat(fresh->object.get(), "", R_OK, AT_EMPTY_PATH | AT_EACCESS) != 0;
}
} // namespace
CommandPathLookup inspect_command_path(const ProviderScope &scope, const fs::path &path,
CommandPathKind kind) {
auto stamp = std::make_shared<CommandPathStamp>(scope.anchors, kind);
auto owner = workspace_anchor(scope, path);
if (!owner)
return {path, {}, owner.error().code, std::move(stamp)};
const auto &root = (*owner)->path;
if (!Detail::valid_path(path) || (path != root && !below(path, root)))
return {path, {}, "outside_scope", std::move(stamp)};
auto result = CommandPathWalk{**owner, *stamp}.resolve(path, kind);
return {path, std::move(result.physical), std::move(result.issue), std::move(stamp)};
}
std::optional<fs::path> changed_provider_input(const ProviderScope &scope,
const ProviderObservation &observation) {
for (const auto &file : observation.inputs)
if (!provider_file_current(scope, file))
return file.logical_path;
for (const auto &path : observation.lookups.paths) {
if (!path.stamp || path.stamp->anchors != scope.anchors || path.issue == "changed")
return path.logical_path;
const auto fresh = inspect_command_path(scope, path.logical_path, path.stamp->kind);
if (fresh.issue != path.issue || fresh.physical_path != path.physical_path || *fresh.stamp != *path.stamp)
return path.logical_path;
}
for (const auto &failed : observation.lookups.failed_responses)
if (!failed_response_current(scope, failed))
return failed.issue.path;
return {};
}
bool provider_file_current(const ProviderScope &scope, const ProviderFile &file) {
if (!file.stamp || file.stamp->anchors != scope.anchors ||
file.stamp->purpose != file.purpose || file.stamp->logical != file.logical_path ||
file.stamp->file.canonical != file.canonical_path)
return false;
const auto route = route_for(scope, file.logical_path, file.purpose);
if (!route)
return false;
auto fresh = open_file(*route, file.logical_path, file.purpose);
return fresh && same_capture(*fresh, file.stamp->file);
}
bool same_provider_object(const ProviderFile &a, const ProviderFile &b) noexcept {
return a.stamp && b.stamp && same_inode(a.stamp->file.metadata, b.stamp->file.metadata);
}
std::expected<ProviderFile, ProviderIssue> read_provider_file(const ProviderScope &scope,
const fs::path &path,
FilePurpose purpose,
std::size_t byte_limit) {
auto route = route_for(scope, path, purpose);
if (!route)
return std::unexpected(std::move(route.error()));
auto file = open_file(*route, path, purpose);
if (!file)
return std::unexpected(std::move(file.error()));
const auto limit = std::min({byte_limit, allowed_bytes(scope.limits, purpose),
allowed_bytes(scope.anchors->requested.limits, purpose)});
if (file->metadata.st_size < 0 || static_cast<std::uint64_t>(file->metadata.st_size) > limit)
return std::unexpected(ProviderIssue{"too_large", "Metadata exceeds its byte limit", path});
auto data = std::make_shared<std::string>();
data->reserve(static_cast<std::size_t>(file->metadata.st_size));
auto hash = Crypto::Hasher::create(Crypto::HashAlgorithm::Sha256);
if (!hash)
return std::unexpected(ProviderIssue{"unavailable", "Cannot create metadata digest", path});
auto read =
Detail::stream_regular_fd(file->object, file->metadata, limit, false, [&](auto chunk) {
data->append(reinterpret_cast<const char *>(chunk.data()), chunk.size());
return hash->update(chunk).has_value();
});
if (!read)
return std::unexpected(
ProviderIssue{read.error() == Detail::FileError::changed ? "changed" : "unavailable",
"Could not capture a stable metadata file", path});
auto digest = hash->finalize();
if (!digest || digest->size() != 32)
return std::unexpected(
ProviderIssue{"unavailable", "Cannot finalize metadata digest", path});
std::string hex;
hex.reserve(64);
constexpr std::string_view digits = "0123456789abcdef";
for (auto byte : *digest) {
const auto n = std::to_integer<unsigned>(byte);
hex.push_back(digits[n >> 4]);
hex.push_back(digits[n & 15]);
}
const auto stamp =
std::make_shared<ProviderStamp>(scope.anchors, purpose, path, std::move(*file));
ProviderFile result{purpose, path, stamp->file.canonical,
std::move(data), std::move(hex), stamp};
if (!provider_file_current(scope, result))
return std::unexpected(
ProviderIssue{"changed", "Metadata binding changed during capture", path});
return result;
}
} // namespace Void::LanguageServer::Build
+272
View File
@@ -0,0 +1,272 @@
#include <Void/LanguageServer/Build/Providers.hpp>
#include <Void/LanguageServer/Protocol/Json.hpp>
#include <algorithm>
#include <iterator>
#include <utility>
namespace Void::LanguageServer::Build {
namespace {
namespace fs = std::filesystem;
using Protocol::Json;
const std::string *text_field(const Json::Object &object, std::string_view key) {
return Protocol::as_string(Protocol::find_member(object, key));
}
std::optional<std::uint64_t> unsigned_field(const Json::Object &object, std::string_view key) {
const auto *value = Protocol::find_member(object, key);
const auto *integer = value ? std::get_if<std::int64_t>(&value->value) : nullptr;
if (!integer || *integer < 0)
return {};
return static_cast<std::uint64_t>(*integer);
}
bool valid_component_text(std::string_view value) {
return !value.empty() && value.size() <= 255 && !value.contains('\0');
}
std::string profile_directory(std::string_view profile) {
std::string slug{profile};
for (auto &c : slug) {
const bool alphanumeric =
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
if (!alphanumeric && c != '.' && c != '_' && c != '-')
c = '_';
}
return slug;
}
bool generation_id(std::string_view id) {
return id.size() == 16 && id.find_first_not_of("0123456789abcdef") == id.npos;
}
enum class LocatorKind { directory, file };
std::optional<fs::path> locator(std::string_view value, LocatorKind kind) {
if (value.empty() || value.size() > 4095 || value.contains('\0'))
return {};
fs::path path{value};
if (kind == LocatorKind::file && (!path.has_filename() || path.filename() == "."))
return {};
if (std::find(path.begin(), path.end(), fs::path{".."}) != path.end())
return {};
path = path.lexically_normal();
if (path != path.root_path() && !path.has_filename())
path = path.parent_path();
return path;
}
bool has_suffix(const fs::path &absolute, const fs::path &relative) {
if (relative == ".")
return true;
auto name = absolute.end();
for (auto part = relative.end(); part != relative.begin();) {
if (name == absolute.begin() || *--name != *--part)
return false;
}
return true;
}
bool usable_producer_cwd(const fs::path &path) {
return path.is_absolute() && path == path.lexically_normal() &&
path.native().find('\0') == std::string::npos;
}
std::optional<fs::path> resolve_root(const ProviderScope &scope, const fs::path &producer_root) {
std::optional<fs::path> absolute;
if (producer_root.is_absolute())
absolute = producer_root;
else if (scope.producer_cwd) {
if (usable_producer_cwd(*scope.producer_cwd))
absolute = locator((*scope.producer_cwd / producer_root).native(), LocatorKind::directory);
}
else if (scope.build_root && has_suffix(*scope.build_root, producer_root))
absolute = scope.build_root;
if (absolute && scope.build_root && *absolute != *scope.build_root)
return {};
return absolute;
}
bool points_to_generation(const ProviderScope &scope, const fs::path &producer_root,
const fs::path &pointer, const fs::path &root, const fs::path &suffix) {
const auto expected = root / suffix;
if (pointer.is_absolute())
return pointer == expected;
if (scope.producer_cwd)
return usable_producer_cwd(*scope.producer_cwd) &&
(*scope.producer_cwd / pointer).lexically_normal() == expected;
if (!scope.build_root)
return false;
if (producer_root.is_relative())
return pointer == (producer_root / suffix).lexically_normal();
return has_suffix(pointer, suffix) && has_suffix(expected, pointer);
}
std::expected<Json::Object, ProviderIssue> read_pointer(const ProviderScope &scope,
const fs::path &path, FilePurpose purpose,
ProviderObservation &observation) {
constexpr std::size_t pointer_cap = 256 * 1024;
auto file = read_provider_file(scope, path, purpose,
std::min(scope.limits.max_manifest_bytes, pointer_cap));
if (!file)
return std::unexpected(std::move(file.error()));
observation.inputs.push_back(std::move(*file));
auto parsed = Protocol::parse_json(*observation.inputs.back().bytes, 12);
auto *object = parsed ? std::get_if<Json::Object>(&parsed->value) : nullptr;
if (!object)
return std::unexpected(
ProviderIssue{"invalid_metadata", "Expected a VBS metadata object", path});
if (unsigned_field(*object, "schema_version") != 1)
return std::unexpected(
ProviderIssue{"unsupported_schema", "Expected VBS editor schema version 1", path});
return std::move(*object);
}
ProviderHealth read_health(const ProviderIssue &issue, bool selector = false) {
if (issue.code == "changed")
return ProviderHealth::changed;
if (issue.code == "missing" && selector)
return ProviderHealth::missing;
if (issue.code == "invalid_metadata" || issue.code == "unsupported_schema")
return ProviderHealth::invalid;
return ProviderHealth::unavailable;
}
ProviderObservation read_vbs(const ProviderScope &scope, const fs::path &selector,
const std::optional<DriverInput> &driver) {
ProviderObservation result{.provider = "vbs"};
auto fail = [&](ProviderHealth health, ProviderIssue issue) {
result.health = health;
result.issues.push_back(std::move(issue));
return std::move(result);
};
const auto selection = read_pointer(scope, selector, FilePurpose::selection, result);
if (!selection)
return fail(read_health(selection.error(), true), selection.error());
const auto *profile = text_field(*selection, "selected_profile");
const auto *build = text_field(*selection, "selected_build_root");
const auto *id = text_field(*selection, "selected_generation_id");
const auto *selected_db = text_field(*selection, "selected_compdb_path");
result.selection_ticket = unsigned_field(*selection, "ticket");
if (!result.selection_ticket || !profile || !build || !id || !selected_db)
return fail(ProviderHealth::invalid,
{"invalid_selection", "Incomplete VBS selection record", selector});
if (!profile->empty() && valid_component_text(*profile))
result.profile = *profile;
if (id->empty() && selected_db->empty())
return fail(ProviderHealth::unavailable,
{"selection_pending", "VBS has not selected a generation yet", selector});
if (!result.profile || !generation_id(*id))
return fail(ProviderHealth::invalid,
{"invalid_selection", "Invalid VBS profile or generation ID", selector});
result.native_generation = *id;
const auto slug = profile_directory(*profile);
if (slug == "." || slug == "..")
return fail(ProviderHealth::invalid,
{"invalid_profile", "Invalid VBS profile directory", selector});
if (const auto *warning = text_field(*selection, "root_alias_warning");
warning && !warning->empty())
result.warnings.push_back({"alias_warning", warning->substr(0, 2048), selector});
const auto spelling = locator(*build, LocatorKind::directory);
const auto selected = locator(*selected_db, LocatorKind::file);
if (!spelling || !selected)
return fail(ProviderHealth::invalid, {"invalid_locator", "Invalid VBS locator", selector});
const auto root = resolve_root(scope, *spelling);
if (!root)
return fail(ProviderHealth::unavailable,
{"ambiguous_locator", "Cannot bind the selected VBS build root", selector});
const auto editor = fs::path{"profiles"} / slug / "editor";
const auto suffix = editor / "generations" / *id / "compile_commands.json";
if (!points_to_generation(scope, *spelling, *selected, *root, suffix))
return fail(ProviderHealth::invalid,
{"locator_mismatch", "Selected path does not identify the immutable generation",
selector});
const auto status_path = *root / editor / "status.json";
const auto status = read_pointer(scope, status_path, FilePurpose::status, result);
if (!status)
return fail(read_health(status.error()), status.error());
const auto *status_profile = text_field(*status, "profile");
const auto *state = text_field(*status, "status");
const auto *diagnostic = text_field(*status, "diagnostic");
if (!status_profile || *status_profile != *profile || !state || !diagnostic)
return fail(ProviderHealth::invalid,
{"invalid_status", "Incomplete or mismatched VBS profile status", status_path});
if (*state == "stale" || *state == "invalid")
return fail(*state == "stale" ? ProviderHealth::stale : ProviderHealth::invalid,
{"vbs_" + *state,
diagnostic->empty() ? "VBS marked the generation " + *state
: diagnostic->substr(0, 2048),
status_path});
const auto *status_id = text_field(*status, "generation_id");
const auto *db_text = text_field(*status, "compdb_path");
const auto status_db = db_text ? locator(*db_text, LocatorKind::file) : std::nullopt;
const auto count = unsigned_field(*status, "entry_count");
const auto *warnings = Protocol::as_array(Protocol::find_member(*status, "readiness_warnings"));
if (*state != "valid" || !status_id || !generation_id(*status_id) || !status_db || !count ||
!warnings)
return fail(ProviderHealth::invalid,
{"invalid_status", "Invalid VBS valid-generation record", status_path});
if (*status_id != *id || !points_to_generation(scope, *spelling, *status_db, *root, suffix))
return fail(ProviderHealth::changed,
{"generation_mismatch",
"VBS selection and profile status refer to different generations",
status_path});
if (warnings->size() > 256)
return fail(ProviderHealth::invalid,
{"too_large", "Too many VBS readiness warnings", status_path});
for (const auto &warning : *warnings) {
const auto *message = Protocol::as_string(&warning);
if (!message || message->size() > 2048)
return fail(ProviderHealth::invalid,
{"invalid_status", "Invalid VBS readiness warning", status_path});
result.warnings.push_back({"readiness_warning", *message, status_path});
}
const auto path = *root / suffix;
auto file = read_provider_file(scope, path, FilePurpose::native_database,
scope.limits.max_compdb_bytes);
if (!file)
return fail(read_health(file.error()), file.error());
result.inputs.push_back(std::move(*file));
auto imported = import_commands({scope, result.inputs.back(), result.profile, driver});
if (!imported)
return fail(ProviderHealth::invalid, std::move(imported.error()));
if (imported->contexts.size() != *count)
return fail(ProviderHealth::invalid,
{"count_mismatch", "VBS entry_count differs from its database", path});
// Length-prefix the variable locator. Native IDs describe producer state;
// the byte identities also distinguish in-place DB repairs and response edits.
auto revision = std::to_string(path.native().size()) + "/" + path.native() + "/" + *id + "/" +
result.inputs[1].content_id + "/" + result.inputs.back().content_id + "/" +
imported->revision;
auto generation =
BuildGeneration::create({scope.workspace, "vbs", std::move(revision)}, imported->contexts);
if (!generation)
return fail(ProviderHealth::invalid,
{"invalid_context", "Invalid native compilation context", path});
result.inputs.insert(result.inputs.end(),
std::make_move_iterator(imported->dependencies.begin()),
std::make_move_iterator(imported->dependencies.end()));
result.lookups = std::move(imported->lookups);
result.generation = std::move(*generation);
result.health = ProviderHealth::ready;
return result;
}
} // namespace
ProviderObservation observe_vbs(const ProviderScope &scope, const fs::path &selector,
const std::optional<DriverInput> &driver) {
auto result = read_vbs(scope, selector, driver);
if (auto changed = changed_provider_input(scope, result)) {
result.health = ProviderHealth::changed;
result.generation.reset();
result.issues = {{"changed", "VBS inputs changed during observation", *changed}};
}
return result;
}
} // namespace Void::LanguageServer::Build
+136
View File
@@ -0,0 +1,136 @@
#include <vls/DocumentSync.hpp>
#include <utility>
namespace vls {
namespace {
namespace Docs = Void::LanguageServer::Documents;
namespace Protocol = Void::LanguageServer::Protocol;
using Protocol::Json;
const Json *field(const Json *value, std::string_view key) {
const auto *object = Protocol::as_object(value);
return object ? Protocol::find_member(*object, key) : nullptr;
}
std::optional<std::int32_t> integer(const Json *value) {
const auto number = Protocol::as_int64(value);
if (!number || !std::in_range<std::int32_t>(*number))
return std::nullopt;
return static_cast<std::int32_t>(*number);
}
std::optional<std::uint32_t> uinteger(const Json *value) {
const auto number = integer(value);
if (!number || *number < 0)
return std::nullopt;
return static_cast<std::uint32_t>(*number);
}
std::optional<Docs::Position> position(const Json *value) {
const auto line = uinteger(field(value, "line"));
const auto character = uinteger(field(value, "character"));
if (!line || !character)
return std::nullopt;
return Docs::Position{*line, *character};
}
std::expected<Docs::TextEdit, std::string_view> decode_edit(const Json &change) {
const auto *text = Protocol::as_string(field(&change, "text"));
if (!text)
return std::unexpected{"change requires text"};
const auto *range = field(&change, "range");
const auto *length = field(&change, "rangeLength");
if (length && (!range || !uinteger(length)))
return std::unexpected{"invalid change rangeLength"};
if (!range)
return Docs::TextEdit{std::nullopt, *text};
const auto start = position(field(range, "start"));
const auto end = position(field(range, "end"));
if (!start || !end)
return std::unexpected{"invalid change range"};
return Docs::TextEdit{Docs::Range{*start, *end}, *text};
}
std::expected<void, std::string> apply_change(Docs::DocumentStore &store, const std::string &uri,
const Json *document, const Json *params) {
const auto version = integer(field(document, "version"));
const auto reject = [&](std::string_view why) -> std::expected<void, std::string> {
auto marked = store.mark_desynchronized(
uri, version, {Docs::DocumentError::Kind::malformed_change, std::string{why}});
return std::unexpected{marked ? std::string{why} : std::move(marked.error().message)};
};
if (!version)
return reject("invalid change version");
const auto *changes = Protocol::as_array(field(params, "contentChanges"));
if (!changes || changes->size() > Docs::DocumentLimits{}.max_changes)
return reject("invalid contentChanges array or too many changes");
std::vector<Docs::TextEdit> edits;
edits.reserve(changes->size());
for (const auto &change : *changes) {
auto edit = decode_edit(change);
if (!edit)
return reject(edit.error());
edits.push_back(std::move(*edit));
}
auto applied = store.apply_changes(uri, *version, edits);
if (!applied)
return std::unexpected{std::move(applied.error().message)};
return {};
}
} // namespace
void reject_change_envelope(Docs::DocumentStore &store, const Json *params) {
const auto *document = field(params, "textDocument");
if (const auto *uri = Protocol::as_string(field(document, "uri"))) {
static_cast<void>(store.mark_desynchronized(
*uri, integer(field(document, "version")),
{Docs::DocumentError::Kind::malformed_change, "invalid didChange envelope"}));
}
}
Docs::PositionEncoding negotiate_position_encoding(const Json &params) {
const auto *general = field(field(&params, "capabilities"), "general");
if (const auto *encodings = Protocol::as_array(field(general, "positionEncodings"))) {
for (const auto &entry : *encodings) {
const auto *name = Protocol::as_string(&entry);
if (name && *name == "utf-8")
return Docs::PositionEncoding::utf8;
if (name && *name == "utf-16")
return Docs::PositionEncoding::utf16;
}
}
return Docs::PositionEncoding::utf16;
}
std::expected<void, std::string> synchronize_document(Docs::DocumentStore &store,
std::string_view method, const Json *params) {
if (method != "textDocument/didOpen" && method != "textDocument/didChange" &&
method != "textDocument/didClose")
return {};
const auto *document = field(params, "textDocument");
const auto *uri = Protocol::as_string(field(document, "uri"));
if (!uri)
return std::unexpected{"document notification requires a URI"};
if (method == "textDocument/didChange")
return apply_change(store, *uri, document, params);
if (method == "textDocument/didClose") {
auto closed = store.close(*uri);
if (!closed)
return std::unexpected{std::move(closed.error().message)};
return {};
}
const auto *language = Protocol::as_string(field(document, "languageId"));
const auto *text = Protocol::as_string(field(document, "text"));
const auto version = integer(field(document, "version"));
if (!language || !text || !version)
return std::unexpected{"didOpen requires languageId, text and a signed 32-bit version"};
auto opened = store.open(*uri, *language, *version, *text);
if (!opened)
return std::unexpected{std::move(opened.error().message)};
return {};
}
} // namespace vls
+38
View File
@@ -0,0 +1,38 @@
#include <Void/LanguageServer/Documents/DocumentSnapshot.hpp>
#include <Void/Core/Hash.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <Void/Text/Hex.hpp>
#include <format>
namespace Void::LanguageServer::Documents {
std::string ContentHash::display_digest() const {
if (!sha256_hex.empty()) {
return "sha256:" + sha256_hex;
}
return std::format("fnv1a64:{:016x}", fnv1a64);
}
ContentHash compute_content_hash(std::string_view text) {
ContentHash result;
result.fnv1a64 = Void::Hash::fnv1a64(text);
if (auto digest = Void::Crypto::sha256(text); digest.has_value()) {
result.sha256_hex = Void::Encoding::Hex::encode(*digest);
}
return result;
}
bool DocumentSnapshot::same_input_as(const DocumentSnapshot &other) const noexcept {
if (origin != other.origin) {
return false;
}
if (origin == DocumentOrigin::overlay) {
return revision_id == other.revision_id;
}
return identity.canonical_path == other.identity.canonical_path && encoding == other.encoding &&
overlay_epoch == other.overlay_epoch &&
content_hash.fnv1a64 == other.content_hash.fnv1a64 && text == other.text;
}
} // namespace Void::LanguageServer::Documents
+659
View File
@@ -0,0 +1,659 @@
#include <Void/LanguageServer/Documents/DocumentStore.hpp>
#include <Void/Unicode/Utf.hpp>
#ifndef _WIN32
#include <Void/LanguageServer/Support/RegularFile.hpp>
#endif
#include <algorithm>
#include <iterator>
#include <mutex>
#include <system_error>
#include <utility>
namespace Void::LanguageServer::Documents {
namespace {
using Kind = DocumentError::Kind;
constexpr std::size_t kMaxLanguageIdBytes = 1024;
constexpr std::size_t kMaxProblemBytes = 256;
std::atomic<std::uint64_t> next_revision{1};
std::unexpected<DocumentError> failure(Kind kind, std::string message) {
return std::unexpected{DocumentError{kind, std::move(message)}};
}
std::expected<DocumentIdentity, DocumentError>
bound_file_identity(std::string_view file_uri, const std::filesystem::path &physical_path) {
auto key = client_uri_key(file_uri);
if (!key) {
return failure(Kind::invalid_uri, std::move(key.error()));
}
if (!key->starts_with("file://") || key->ends_with('/') || key->ends_with("/.") ||
key->ends_with("/..")) {
return failure(Kind::invalid_uri, "bound source requires a local file URI with a filename");
}
if (physical_path.native().size() > kMaxDocumentUriBytes) {
return failure(Kind::resource_limit, "bound physical path exceeds the byte limit");
}
if (!physical_path.is_absolute() || !physical_path.has_filename() ||
physical_path.native() != physical_path.lexically_normal().native()) {
return failure(Kind::invalid_uri, "bound source requires a resolved absolute file path");
}
const auto utf8 = physical_path.generic_u8string();
const std::string_view path_bytes{reinterpret_cast<const char *>(utf8.data()), utf8.size()};
if (path_bytes.contains('\0') || path_bytes.contains('\\') ||
!Void::Unicode::validate_utf8(path_bytes)) {
return failure(Kind::invalid_uri,
"bound physical path cannot be represented as a file URI");
}
return DocumentIdentity{std::move(*key), std::string{file_uri}, physical_path, true};
}
struct SnapshotCharge {
std::shared_ptr<std::atomic_size_t> total;
std::size_t bytes;
SnapshotCharge(std::shared_ptr<std::atomic_size_t> total, std::size_t bytes)
: total(std::move(total)), bytes(bytes) {
this->total->fetch_add(bytes, std::memory_order_relaxed);
}
SnapshotCharge(const SnapshotCharge &) = delete;
SnapshotCharge &operator=(const SnapshotCharge &) = delete;
~SnapshotCharge() { total->fetch_sub(bytes, std::memory_order_relaxed); }
};
struct BudgetedSnapshot {
BudgetedSnapshot(const std::shared_ptr<std::atomic_size_t> &total, std::size_t bytes,
DocumentSnapshot snapshot)
: charge(total, bytes), snapshot(std::move(snapshot)) {}
// Release the charge after destroying the snapshot's buffers.
SnapshotCharge charge;
DocumentSnapshot snapshot;
};
struct DiskImage {
std::string text;
#ifndef _WIN32
Detail::FileInfo file;
#endif
};
std::expected<DiskImage, DocumentError> read_regular_file(const std::filesystem::path &path,
std::size_t max_bytes) {
#ifndef _WIN32
std::string text;
auto file = Detail::read_regular(path, max_bytes, false, [&](std::span<const std::byte> chunk) {
text.append(reinterpret_cast<const char *>(chunk.data()), chunk.size());
return true;
});
if (file)
return DiskImage{std::move(text), std::move(*file)};
if (file.error() == Detail::FileError::too_large)
return failure(Kind::resource_limit, "disk document exceeds the byte limit");
if (file.error() == Detail::FileError::changed)
return failure(Kind::stale_read, "disk document changed while being read");
return failure(Kind::disk_read_failed, "cannot read regular disk document");
#else
return failure(Kind::disk_read_failed, "regular-file document reads are unavailable");
#endif
}
} // namespace
DocumentStore::DocumentStore(PositionEncoding encoding, DocumentLimits limits,
DiskReadObserver after_disk_read)
: limits_(limits), after_disk_read_(std::move(after_disk_read)),
snapshot_bytes_(std::make_shared<std::atomic_size_t>(0)), encoding_(encoding) {}
bool DocumentStore::set_position_encoding(PositionEncoding encoding) {
std::unique_lock lock{mutex_};
if (encoding_ == encoding) {
return true;
}
if (!by_uri_.empty() || unknown_file_open_ || unknown_virtual_open_) {
return false;
}
encoding_ = encoding;
++overlay_epoch_;
return true;
}
PositionEncoding DocumentStore::position_encoding() const noexcept {
std::shared_lock lock{mutex_};
return encoding_;
}
std::size_t DocumentStore::snapshot_overhead(const DocumentIdentity &identity,
std::string_view language_id) const noexcept {
constexpr std::size_t hash_hex_bytes = 64;
return sizeof(BudgetedSnapshot) + hash_hex_bytes + language_id.size() +
identity.canonical_uri.size() + identity.display_uri.size() +
identity.canonical_path.native().size() * sizeof(std::filesystem::path::value_type);
}
std::size_t DocumentStore::available_snapshot_bytes() const noexcept {
return limits_.max_snapshot_bytes - snapshot_bytes_->load(std::memory_order_relaxed);
}
DocumentStore::SnapshotResult DocumentStore::make_snapshot(const DocumentIdentity &identity,
std::string_view language_id,
std::optional<std::int32_t> version,
std::string text,
std::optional<LineIndex> index) const {
// All acquisitions run under the store's exclusive lock. References may release their
// charge from another thread or after the store is destroyed.
const auto overhead = snapshot_overhead(identity, language_id);
const auto available = available_snapshot_bytes();
if (overhead > available || text.capacity() > available - overhead) {
return failure(Kind::resource_limit, "document snapshot memory limit reached");
}
const auto index_budget = available - overhead - text.capacity();
if (!index) {
const auto lines = LineIndex::count_lines(text);
if (lines > index_budget / sizeof(std::size_t)) {
return failure(Kind::resource_limit, "document line index exceeds the snapshot budget");
}
index = LineIndex{text, lines};
}
if (index->storage_bytes() > index_budget) {
return failure(Kind::resource_limit, "document line index exceeds the snapshot budget");
}
const auto bytes = overhead + text.capacity() + index->storage_bytes();
auto content_hash = compute_content_hash(text);
auto owned = std::make_shared<BudgetedSnapshot>(
snapshot_bytes_, bytes,
DocumentSnapshot{
.identity = identity,
.language_id = std::string{language_id},
.version = version,
.revision_id = next_revision.fetch_add(1, std::memory_order_relaxed),
.overlay_epoch = overlay_epoch_,
.text = std::move(text),
.content_hash = std::move(content_hash),
.line_index = std::move(*index),
.encoding = encoding_,
.origin = version ? DocumentOrigin::overlay : DocumentOrigin::disk,
});
return Snapshot{owned, &owned->snapshot};
}
void DocumentStore::desynchronize(OpenDocument &document, const DocumentError &cause) {
document.current.reset();
document.problem.assign(cause.message, 0, kMaxProblemBytes);
}
DocumentStore::SnapshotResult DocumentStore::open(std::string_view raw_uri, std::string language_id,
std::int64_t version, std::string text) {
if (!std::in_range<std::int32_t>(version)) {
return failure(Kind::invalid_version, "open version exceeds the LSP integer range");
}
if (raw_uri.size() > kMaxDocumentUriBytes) {
std::unique_lock lock{mutex_};
unknown_file_open_ = true;
++overlay_epoch_;
return failure(Kind::resource_limit, "document URI exceeds the byte limit");
}
auto identity = normalize_uri(raw_uri);
if (!identity) {
std::unique_lock lock{mutex_};
unknown_file_open_ = true;
++overlay_epoch_;
return failure(Kind::invalid_uri, std::move(identity.error()));
}
std::unique_lock lock{mutex_};
if (by_uri_.contains(identity->canonical_uri)) {
return failure(Kind::already_open, "document is already open");
}
const auto client_version = static_cast<std::int32_t>(version);
const bool language_id_fits = language_id.size() <= kMaxLanguageIdBytes;
auto admit = [&]() -> SnapshotResult {
if (admitted_documents_ >= limits_.max_open_documents) {
return failure(Kind::resource_limit, "open document limit reached");
}
if (!language_id_fits || text.size() > limits_.max_document_bytes) {
return failure(Kind::resource_limit, "open document exceeds the byte limit");
}
if (!Void::Unicode::validate_utf8(text)) {
return failure(Kind::invalid_utf8, "document text is not valid UTF-8");
}
return make_snapshot(*identity, language_id, client_version, std::move(text));
};
if (identity->is_file_uri) {
++overlay_epoch_;
}
auto snapshot = admit();
if (!snapshot && by_uri_.size() - admitted_documents_ >= limits_.max_unavailable_documents) {
// The parsed scheme determines which authority an unrecorded open can affect.
if (identity->is_file_uri) {
unknown_file_open_ = true;
} else {
unknown_virtual_open_ = true;
}
return failure(Kind::resource_limit, "unavailable-open limit reached");
}
auto key = identity->canonical_uri;
auto [entry, inserted] = by_uri_.try_emplace(
std::move(key),
OpenDocument{
.identity = std::move(*identity),
.language_id =
language_id_fits ? std::optional<std::string>{language_id} : std::nullopt,
.highest_version = client_version,
.current = snapshot.value_or(nullptr),
.admitted = snapshot.has_value(),
.problem = snapshot ? std::string{} : snapshot.error().message,
});
const auto &bound = entry->second.identity;
if (bound.is_file_uri && !bound.canonical_path.empty()) {
try {
by_path_.emplace(bound.canonical_path, &entry->second);
} catch (...) {
by_uri_.erase(entry);
unknown_file_open_ = true;
throw;
}
} else if (bound.is_file_uri) {
++unbound_file_documents_;
}
admitted_documents_ += static_cast<std::size_t>(snapshot.has_value());
return snapshot;
}
DocumentStore::SnapshotResult DocumentStore::apply_changes(std::string_view raw_uri,
std::int64_t new_version,
std::span<const TextEdit> edits) {
const auto key = client_uri_key(raw_uri);
if (!key) {
return failure(Kind::invalid_uri, key.error());
}
std::unique_lock lock{mutex_};
const auto found = by_uri_.find(*key);
if (found == by_uri_.end()) {
return failure(Kind::not_open, "document is not open");
}
auto &document = found->second;
auto reject = [&](Kind kind, std::string reason) -> SnapshotResult {
DocumentError cause{kind, std::move(reason)};
desynchronize(document, cause);
return std::unexpected{std::move(cause)};
};
if (!std::in_range<std::int32_t>(new_version)) {
return reject(Kind::invalid_version, "change version exceeds the LSP integer range");
}
const auto client_version = static_cast<std::int32_t>(new_version);
if (client_version <= document.highest_version) {
return reject(Kind::nonmonotonic_version,
"change notification has nonmonotonic document version");
}
document.highest_version = client_version;
if (!document.current && (edits.empty() || edits.front().range)) {
return reject(Kind::desynchronized,
"document is desynchronized; a newer full-text replacement is required");
}
if (!document.language_id) {
return reject(Kind::resource_limit, "document language identifier exceeds the byte limit");
}
if (!document.admitted && admitted_documents_ >= limits_.max_open_documents) {
return reject(Kind::resource_limit, "open document limit reached");
}
if (edits.size() > limits_.max_changes) {
return reject(Kind::resource_limit, "change notification exceeds the edit count limit");
}
std::size_t remaining_batch_bytes = limits_.max_change_bytes;
for (const auto &edit : edits) {
if (edit.text.size() > remaining_batch_bytes ||
edit.text.size() > limits_.max_document_bytes) {
return reject(Kind::resource_limit, "change notification exceeds the text byte limit");
}
remaining_batch_bytes -= edit.text.size();
if (!Void::Unicode::validate_utf8(edit.text)) {
return reject(Kind::invalid_utf8, "change edit text is not valid UTF-8");
}
}
const auto overhead = snapshot_overhead(document.identity, *document.language_id);
const auto available = available_snapshot_bytes();
if (overhead > available) {
return reject(Kind::resource_limit, "document snapshot memory limit reached");
}
const auto body_budget = available - overhead;
std::string working_text;
std::optional<LineIndex> working_index;
const auto *current = document.current.get();
std::string_view source = current ? std::string_view{current->text} : std::string_view{};
const LineIndex *source_index = current ? &current->line_index : nullptr;
for (const auto &edit : edits) {
if (!edit.range) {
source = edit.text;
source_index = nullptr;
working_index.reset();
continue;
}
if (!working_index) {
const auto lines =
source_index ? source_index->line_count() : LineIndex::count_lines(source);
if (source.size() > body_budget ||
lines > (body_budget - source.size()) / sizeof(std::size_t)) {
return reject(Kind::resource_limit,
"edit working copy exceeds the snapshot budget");
}
working_text = std::string{source};
working_index = source_index ? *source_index : LineIndex{source, lines};
}
const auto offsets = working_index->range_to_offsets(working_text, *edit.range, encoding_);
if (!offsets) {
return reject(Kind::invalid_range,
"invalid incremental edit range: " + offsets.error());
}
const auto [start, end] = *offsets;
const auto unchanged = working_text.size() - (end - start);
if (edit.text.size() > limits_.max_document_bytes - unchanged) {
return reject(Kind::resource_limit, "edited document exceeds the byte limit");
}
const auto next_size = unchanged + edit.text.size();
const auto text_bytes = std::max(next_size, working_text.capacity());
if (text_bytes > body_budget ||
!working_index->apply_replacement(working_text, start, end, edit.text,
(body_budget - text_bytes) / sizeof(std::size_t))) {
return reject(Kind::resource_limit, "edit working copy exceeds the snapshot budget");
}
working_text.replace(start, end - start, edit.text);
}
if (!working_index) {
if (source.size() > body_budget) {
return reject(Kind::resource_limit, "document snapshot memory limit reached");
}
working_text = std::string{source};
}
auto updated = make_snapshot(document.identity, *document.language_id, client_version,
std::move(working_text), std::move(working_index));
if (!updated) {
desynchronize(document, updated.error());
return updated;
}
if (!document.admitted) {
document.admitted = true;
++admitted_documents_;
}
document.current = *updated;
document.problem.clear();
return updated;
}
std::expected<void, DocumentError> DocumentStore::mark_desynchronized(
std::string_view raw_uri, std::optional<std::int64_t> observed_version, DocumentError cause) {
const auto key = client_uri_key(raw_uri);
if (!key) {
return failure(Kind::invalid_uri, key.error());
}
std::unique_lock lock{mutex_};
const auto found = by_uri_.find(*key);
if (found == by_uri_.end()) {
return failure(Kind::not_open, "document is not open");
}
auto &document = found->second;
if (observed_version && std::in_range<std::int32_t>(*observed_version)) {
document.highest_version =
std::max(document.highest_version, static_cast<std::int32_t>(*observed_version));
}
desynchronize(document, cause);
return {};
}
std::expected<void, DocumentError> DocumentStore::close(std::string_view raw_uri) {
const auto key = client_uri_key(raw_uri);
if (!key) {
return failure(Kind::invalid_uri, key.error());
}
std::unique_lock lock{mutex_};
const auto entry = by_uri_.find(*key);
if (entry == by_uri_.end()) {
return failure(Kind::not_open, "document is not open");
}
const auto &document = entry->second;
if (document.identity.is_file_uri) {
++overlay_epoch_;
const auto &path = document.identity.canonical_path;
if (path.empty()) {
--unbound_file_documents_;
} else {
const auto [first, last] = by_path_.equal_range(path);
const auto bound = std::find_if(
first, last, [&](const auto &pair) { return pair.second == &document; });
if (bound != last) {
by_path_.erase(bound);
}
}
}
admitted_documents_ -= static_cast<std::size_t>(document.admitted);
by_uri_.erase(entry);
return {};
}
DocumentStore::Snapshot DocumentStore::snapshot(std::string_view raw_uri) const {
const auto key = client_uri_key(raw_uri);
if (!key) {
return {};
}
std::shared_lock lock{mutex_};
const auto found = by_uri_.find(*key);
return found == by_uri_.end() ? nullptr : found->second.current;
}
DocumentStore::SnapshotResult
DocumentStore::overlay_for_path(const DocumentIdentity &identity) const {
if (unknown_file_open_ || unbound_file_documents_ != 0) {
return failure(Kind::unavailable_overlay, "one or more file opens have no known binding");
}
const auto lexical = by_uri_.find(identity.canonical_uri);
if (lexical != by_uri_.end() &&
lexical->second.identity.canonical_path != identity.canonical_path) {
return failure(Kind::stale_read, "file path changed while its client URI is open");
}
const auto [first, last] = by_path_.equal_range(identity.canonical_path);
if (first == last) {
return Snapshot{};
}
if (std::next(first) != last) {
return failure(Kind::ambiguous_overlay, "multiple open client URIs refer to this file");
}
const auto &document = *first->second;
if (!document.current) {
const auto kind = document.admitted ? Kind::desynchronized : Kind::unavailable_overlay;
const auto reason = document.problem.empty() ? "waiting for full text" : document.problem;
return failure(kind, "open overlay is unavailable: " + reason);
}
return document.current;
}
DocumentStore::Snapshot DocumentStore::snapshot_by_path(const std::filesystem::path &path) const {
const auto identity = identity_from_path(path);
if (!identity) {
return {};
}
std::shared_lock lock{mutex_};
return overlay_for_path(*identity).value_or(nullptr);
}
std::vector<DocumentStore::Snapshot> DocumentStore::list_overlays() const {
std::shared_lock lock{mutex_};
std::vector<Snapshot> result;
result.reserve(admitted_documents_);
for (const auto &[uri, document] : by_uri_) {
if (document.current) {
result.push_back(document.current);
}
}
return result;
}
std::expected<FileOverlayInventory, DocumentError>
DocumentStore::file_overlay_inventory(std::size_t max_entries) const {
std::shared_lock lock{mutex_};
if (unknown_file_open_ || unbound_file_documents_ != 0) {
return failure(Kind::unavailable_overlay, "one or more file opens have no known binding");
}
if (by_path_.size() > max_entries) {
return failure(Kind::resource_limit, "file overlay inventory exceeds the entry limit");
}
FileOverlayInventory inventory;
inventory.generation_ = {snapshot_bytes_, overlay_epoch_};
inventory.entries_.reserve(by_path_.size());
for (const auto &[path, document] : by_path_) {
inventory.entries_.push_back({document->identity, overlay_for_path(document->identity)});
}
return inventory;
}
bool DocumentStore::current_generation(const FileOverlayGeneration &generation) const {
return generation.store == snapshot_bytes_ && generation.epoch == overlay_epoch_;
}
std::expected<BoundSourceObservation, DocumentError>
DocumentStore::observe_bound_source(const FileOverlayInventory &inventory,
std::string_view file_uri,
const std::filesystem::path &physical_path) const {
auto identity = bound_file_identity(file_uri, physical_path);
if (!identity) {
return std::unexpected{std::move(identity.error())};
}
std::shared_lock lock{mutex_};
if (!current_generation(inventory.generation_)) {
return failure(Kind::stale_read,
"file overlay inventory belongs to another store or generation");
}
auto overlay = overlay_for_path(*identity);
if (!overlay) {
return std::unexpected{std::move(overlay.error())};
}
BoundSourceObservation observation;
observation.generation_ = inventory.generation_;
observation.identity_ = std::move(*identity);
observation.overlay_ = std::move(*overlay);
return observation;
}
std::expected<void, DocumentError>
DocumentStore::check_observation(const BoundSourceObservation &observation) const {
if (!current_generation(observation.generation_)) {
return failure(Kind::stale_read, "bound source belongs to another store or generation");
}
auto current = overlay_for_path(observation.identity_);
if (!current) {
return std::unexpected{std::move(current.error())};
}
if (*current != observation.overlay_) {
return failure(Kind::stale_read, "selected overlay changed after observation");
}
return {};
}
DocumentStore::SnapshotResult
DocumentStore::materialize_bound_disk(const BoundSourceObservation &observation,
std::string bytes) const {
std::unique_lock lock{mutex_};
if (auto valid = check_observation(observation); !valid) {
return std::unexpected{std::move(valid.error())};
}
if (observation.overlay_) {
return failure(Kind::already_open, "an open overlay supplies the bound source");
}
if (bytes.size() > limits_.max_document_bytes) {
return failure(Kind::resource_limit, "bound disk document exceeds the byte limit");
}
if (!Void::Unicode::validate_utf8(bytes)) {
return failure(Kind::invalid_utf8, "bound disk document is not valid UTF-8");
}
return make_snapshot(observation.identity_, "cpp", std::nullopt, std::move(bytes));
}
std::expected<void, DocumentError>
DocumentStore::validate_bound_sources(const FileOverlayInventory &inventory,
std::span<const BoundSourceObservation> selected) const {
return validate_bound_sources(inventory.generation(), selected);
}
std::expected<void, DocumentError>
DocumentStore::validate_bound_sources(const FileOverlayGeneration &generation,
std::span<const BoundSourceObservation> selected) const {
std::shared_lock lock{mutex_};
if (!current_generation(generation)) {
return failure(Kind::stale_read,
"file overlay inventory belongs to another store or generation");
}
for (const auto &observation : selected) {
if (auto valid = check_observation(observation); !valid) {
return valid;
}
}
return {};
}
DocumentStore::SnapshotResult DocumentStore::resolve_content(const std::filesystem::path &path,
std::size_t max_bytes) const {
auto identity = identity_from_path(path);
if (!identity) {
return failure(Kind::invalid_uri, std::move(identity.error()));
}
std::uint64_t epoch;
{
std::shared_lock lock{mutex_};
auto overlay = overlay_for_path(*identity);
if (!overlay || *overlay) {
return overlay;
}
epoch = overlay_epoch_;
}
auto disk = identity->canonical_path.empty()
? failure(Kind::disk_read_failed, "cannot resolve physical disk path")
: read_regular_file(identity->canonical_path,
std::min(max_bytes, limits_.max_document_bytes));
if (disk && !Void::Unicode::validate_utf8(disk->text)) {
disk = failure(Kind::invalid_utf8, "disk document is not valid UTF-8");
}
if (after_disk_read_) {
after_disk_read_();
}
auto latest = identity_from_path(path);
#ifndef _WIN32
if (disk && latest) {
struct stat current{};
if (::stat(latest->canonical_path.c_str(), &current) != 0 ||
!Detail::same_file_state(disk->file.metadata, current))
disk = failure(Kind::stale_read, "disk document changed before publication");
}
#endif
std::unique_lock lock{mutex_};
if (!latest) {
return failure(Kind::stale_read, "disk path could not be revalidated");
}
auto overlay = overlay_for_path(*latest);
if (!overlay || *overlay) {
return overlay;
}
if (epoch != overlay_epoch_ || latest->canonical_path != identity->canonical_path ||
latest->canonical_uri != identity->canonical_uri) {
return failure(Kind::stale_read, "document binding or encoding changed during disk read");
}
if (!disk) {
return std::unexpected{std::move(disk.error())};
}
return make_snapshot(*latest, "cpp", std::nullopt, std::move(disk->text));
}
} // namespace Void::LanguageServer::Documents
+299
View File
@@ -0,0 +1,299 @@
#include <Void/LanguageServer/Documents/Position.hpp>
#include <Void/Unicode/Utf.hpp>
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstring>
#include <span>
#include <utility>
namespace Void::LanguageServer::Documents {
namespace {
Void::Unicode::detail::Utf8Step step_utf8(std::string_view text, std::size_t offset) noexcept {
const std::size_t avail = std::min<std::size_t>(4, text.size() - offset);
std::array<std::uint8_t, 4> bytes{};
for (std::size_t i = 0; i < avail; ++i) {
bytes[i] = static_cast<std::uint8_t>(text[offset + i]);
}
return Void::Unicode::detail::inspect_utf8(std::span<const std::uint8_t>{bytes.data(), avail});
}
std::size_t ascii_prefix_size(std::string_view text) noexcept {
constexpr std::uint64_t high_bits = 0x8080808080808080ULL;
const auto *bytes = text.data();
const auto size = text.size();
std::size_t offset = 0;
// Check full words first. memcpy supports unaligned input, and the mask works in either byte
// order.
for (; size - offset >= sizeof(high_bits); offset += sizeof(high_bits)) {
std::uint64_t word;
std::memcpy(&word, bytes + offset, sizeof(word));
if ((word & high_bits) != 0) {
break;
}
}
while (offset < size && static_cast<unsigned char>(bytes[offset]) < 0x80) {
++offset;
}
return offset;
}
struct LineCursor {
std::size_t bytes{};
std::size_t utf16_units{};
[[nodiscard]] std::size_t units(PositionEncoding encoding) const noexcept {
return encoding == PositionEncoding::utf8 ? bytes : utf16_units;
}
[[nodiscard]] std::expected<void, std::string> seek(std::string_view line, std::size_t target,
PositionEncoding encoding,
const char *split_error) {
while (bytes < line.size() && units(encoding) < target) {
const auto room = target - units(encoding);
const auto ascii =
ascii_prefix_size(line.substr(bytes, std::min(room, line.size() - bytes)));
bytes += ascii;
utf16_units += ascii;
if (ascii == room || bytes == line.size()) {
break;
}
const auto step = step_utf8(line, bytes);
if (step.status != Void::Unicode::detail::StepStatus::ok) {
return std::unexpected{"invalid UTF-8 encountered on line"};
}
const auto count = Void::Unicode::detail::utf16_length(step.scalar.code_point());
if ((encoding == PositionEncoding::utf8 ? step.consumed : count) > room - ascii) {
return std::unexpected{split_error};
}
bytes += step.consumed;
utf16_units += count;
}
return {};
}
};
std::expected<std::pair<std::size_t, std::size_t>, std::string>
offsets_on_line(const LineIndex &index, std::string_view text, Position first,
std::uint32_t last_character, PositionEncoding encoding) {
if (first.line > kMaxPositionValue || first.character > kMaxPositionValue) {
return std::unexpected{"position exceeds the LSP integer range"};
}
const auto line_start = index.line_start_offset(first.line);
if (!line_start) {
return std::unexpected{"position line out of range"};
}
const auto line_end = index.line_content_end_offset(text, first.line);
if (!line_end) {
return std::unexpected{"line index does not match text"};
}
const auto line = text.substr(*line_start, *line_end - *line_start);
const auto *split_error = encoding == PositionEncoding::utf8
? "UTF-8 character offset splits a Unicode scalar"
: "UTF-16 character offset splits a surrogate pair";
LineCursor cursor;
if (auto result = cursor.seek(line, first.character, encoding, split_error); !result) {
return std::unexpected{std::move(result.error())};
}
const auto start_offset = *line_start + cursor.bytes;
if (last_character == first.character) {
return std::pair{start_offset, start_offset};
}
if (last_character > kMaxPositionValue) {
return std::unexpected{"position exceeds the LSP integer range"};
}
if (auto result = cursor.seek(line, last_character, encoding, split_error); !result) {
return std::unexpected{std::move(result.error())};
}
return std::pair{start_offset, *line_start + cursor.bytes};
}
bool ends_line(char byte, char next) noexcept {
return byte == '\n' || (byte == '\r' && next != '\n');
}
template <class Add> void visit_line_starts(std::string_view text, char next, Add add) {
for (std::size_t i = 0; i < text.size(); ++i) {
if (ends_line(text[i], i + 1 < text.size() ? text[i + 1] : next)) {
add(i + 1);
}
}
}
} // namespace
LineIndex::LineIndex(std::string_view text) : LineIndex(text, count_lines(text)) {}
LineIndex::LineIndex(std::string_view text, std::size_t line_count) : text_size_{text.size()} {
line_starts_.reserve(line_count);
visit_line_starts(text, '\0', [&](std::size_t start) { line_starts_.push_back(start); });
}
std::size_t LineIndex::count_lines(std::string_view text) noexcept {
std::size_t count = 1;
for (std::size_t i = 0; i < text.size(); ++i) {
if (ends_line(text[i], i + 1 < text.size() ? text[i + 1] : '\0')) {
++count;
}
}
return count;
}
std::size_t LineIndex::storage_bytes() const noexcept {
return line_starts_.capacity() * sizeof(std::size_t);
}
bool LineIndex::apply_replacement(std::string_view text, std::size_t start, std::size_t end,
std::string_view replacement, std::size_t max_lines) {
// A line start at either edge can change when the splice forms or breaks a CRLF.
// Starts strictly after the right edge only need an offset adjustment.
const auto first = std::lower_bound(line_starts_.begin() + 1, line_starts_.end(), start);
const auto last = std::upper_bound(first, line_starts_.end(), end);
const auto first_index = static_cast<std::size_t>(first - line_starts_.begin());
const auto removed = static_cast<std::size_t>(last - first);
const char following = end < text.size() ? text[end] : '\0';
const char first_byte = replacement.empty() ? following : replacement.front();
const bool start_is_boundary = start > 0 && ends_line(text[start - 1], first_byte);
std::size_t inserted = start_is_boundary ? 1 : 0;
visit_line_starts(replacement, following, [&](std::size_t) { ++inserted; });
const auto new_count = line_starts_.size() - removed + inserted;
if (std::max(new_count, line_starts_.capacity()) > max_lines) {
return false;
}
if (removed > inserted) {
line_starts_.erase(first + inserted, last);
} else if (inserted > removed) {
// The insertion uses saved indices since reserve can invalidate both iterators.
line_starts_.reserve(new_count);
line_starts_.insert(line_starts_.begin() + first_index + removed, inserted - removed, 0);
}
auto output = line_starts_.begin() + first_index;
if (start_is_boundary) {
*output++ = start;
}
visit_line_starts(replacement, following,
[&](std::size_t offset) { *output++ = start + offset; });
const auto bytes_removed = end - start;
text_size_ = text.size() - bytes_removed + replacement.size();
if (bytes_removed != replacement.size()) {
for (; output != line_starts_.end(); ++output) {
*output = *output - bytes_removed + replacement.size();
}
}
return true;
}
std::optional<std::size_t> LineIndex::line_start_offset(std::uint32_t line) const noexcept {
if (line >= line_starts_.size()) {
return std::nullopt;
}
return line_starts_[line];
}
std::optional<std::size_t> LineIndex::line_content_end_offset(std::string_view text,
std::uint32_t line) const noexcept {
const auto start = line_start_offset(line);
if (!start || text.size() != text_size_) {
return std::nullopt;
}
const auto next_line = static_cast<std::size_t>(line) + 1;
const std::size_t raw_end =
next_line < line_starts_.size() ? line_starts_[next_line] : text.size();
if (*start > raw_end || raw_end > text.size()) {
return std::nullopt;
}
std::size_t end = raw_end;
if (end > *start && text[end - 1] == '\n') {
--end;
if (end > *start && text[end - 1] == '\r') {
--end;
}
} else if (end > *start && text[end - 1] == '\r') {
--end;
}
return end;
}
std::expected<std::size_t, std::string>
LineIndex::position_to_offset(std::string_view text, Position position,
PositionEncoding encoding) const {
auto offsets = offsets_on_line(*this, text, position, position.character, encoding);
if (!offsets) {
return std::unexpected{std::move(offsets.error())};
}
return offsets->first;
}
std::expected<Position, std::string>
LineIndex::offset_to_position(std::string_view text, std::size_t byte_offset,
PositionEncoding encoding) const {
if (byte_offset > text.size()) {
return std::unexpected{"byte offset out of range"};
}
// Reject landing between '\r' and '\n' of a CRLF sequence.
if (byte_offset > 0 && byte_offset < text.size() && text[byte_offset - 1] == '\r' &&
text[byte_offset] == '\n') {
return std::unexpected{"byte offset splits a CRLF line terminator"};
}
const auto it = std::upper_bound(line_starts_.begin(), line_starts_.end(), byte_offset);
if (it == line_starts_.begin()) {
return std::unexpected{"line index does not match text"};
}
const auto line_idx = static_cast<std::size_t>(it - line_starts_.begin() - 1);
if (line_idx > kMaxPositionValue) {
return std::unexpected{"position exceeds the LSP integer range"};
}
const std::size_t line_start = line_starts_[line_idx];
const auto line_end = line_content_end_offset(text, static_cast<std::uint32_t>(line_idx));
if (!line_end) {
return std::unexpected{"line index does not match text"};
}
if (byte_offset > *line_end) {
return std::unexpected{"byte offset lands inside line terminator"};
}
const auto line_view = text.substr(line_start, *line_end - line_start);
LineCursor cursor;
if (auto result = cursor.seek(line_view, byte_offset - line_start, PositionEncoding::utf8,
"byte offset splits a Unicode scalar");
!result) {
return std::unexpected{std::move(result.error())};
}
const auto units = cursor.units(encoding);
if (units > kMaxPositionValue) {
return std::unexpected{"position exceeds the LSP integer range"};
}
return Position{
.line = static_cast<std::uint32_t>(line_idx),
.character = static_cast<std::uint32_t>(units),
};
}
std::expected<std::pair<std::size_t, std::size_t>, std::string>
LineIndex::range_to_offsets(std::string_view text, Range range, PositionEncoding encoding) const {
if (range.end < range.start) {
return std::unexpected{"range end precedes range start"};
}
if (range.start.line == range.end.line) {
return offsets_on_line(*this, text, range.start, range.end.character, encoding);
}
auto start = position_to_offset(text, range.start, encoding);
if (!start) {
return std::unexpected{std::move(start.error())};
}
auto end = position_to_offset(text, range.end, encoding);
if (!end) {
return std::unexpected{std::move(end.error())};
}
return std::pair{*start, *end};
}
} // namespace Void::LanguageServer::Documents
+237
View File
@@ -0,0 +1,237 @@
#include <Void/LanguageServer/Documents/Uri.hpp>
#include <Void/Text/Url.hpp>
#include <Void/Unicode/Utf.hpp>
#include <system_error>
#include <utility>
namespace Void::LanguageServer::Documents {
namespace {
bool is_ascii_letter(char ch) noexcept {
return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z');
}
bool is_scheme_char(char ch) noexcept {
return is_ascii_letter(ch) || (ch >= '0' && ch <= '9') || ch == '+' || ch == '-' || ch == '.';
}
std::string to_lower_ascii(std::string_view text) {
std::string out{text};
for (char &ch : out) {
if (ch >= 'A' && ch <= 'Z') {
ch = static_cast<char>(ch + ('a' - 'A'));
}
}
return out;
}
std::string_view utf8_bytes(const std::u8string &text) noexcept {
return {reinterpret_cast<const char *>(text.data()), text.size()};
}
std::filesystem::path physical_path(const std::filesystem::path &absolute_path) {
namespace fs = std::filesystem;
std::error_code error;
auto resolved = fs::canonical(absolute_path, error);
if (!error)
return resolved;
if (error != std::errc::no_such_file_or_directory)
return {};
// Unsaved, newly created files may have an ordinary missing suffix.
// A missing component followed by '..' cannot be traversed on disk.
fs::path prefix = absolute_path.root_path();
bool missing = false;
for (const auto &part : absolute_path.relative_path()) {
if (!missing) {
prefix /= part;
const auto status = fs::symlink_status(prefix, error);
if (error && error != std::errc::no_such_file_or_directory)
return {};
if (status.type() != fs::file_type::not_found)
continue;
resolved = fs::canonical(prefix.parent_path(), error);
if (error || !fs::is_directory(resolved, error) || error)
return {};
missing = true;
}
if (part.empty() || part == "..")
return {};
if (part != ".")
resolved /= part;
}
return missing ? resolved : fs::path{};
}
struct ParsedUri {
std::string key;
std::filesystem::path path;
};
std::expected<ParsedUri, std::string> parse_client_uri(std::string_view uri) {
if (uri.size() > kMaxDocumentUriBytes) {
return std::unexpected{"document URI exceeds the byte limit"};
}
if (!Void::Unicode::validate_utf8(uri)) {
return std::unexpected{"document URI must be valid UTF-8"};
}
for (const unsigned char ch : uri) {
if (ch <= 0x20 || ch == 0x7f ||
std::string_view{"<>\"{}|\\^`"}.find(ch) != std::string_view::npos) {
return std::unexpected{"document URI contains a character that must be escaped"};
}
}
const auto colon = uri.find(':');
if (colon == std::string_view::npos || colon == 0) {
return std::unexpected{"document URI missing scheme"};
}
auto raw_scheme = uri.substr(0, colon);
if (!is_ascii_letter(raw_scheme.front())) {
return std::unexpected{"document URI has invalid scheme"};
}
for (char ch : raw_scheme.substr(1)) {
if (!is_scheme_char(ch)) {
return std::unexpected{"document URI has invalid scheme"};
}
}
auto scheme = to_lower_ascii(raw_scheme);
auto rest = uri.substr(colon + 1);
if (rest.empty()) {
return std::unexpected{"document URI missing scheme-specific content"};
}
const bool is_file = scheme == "file";
for (auto offset = rest.find('%'); offset != std::string_view::npos;
offset = rest.find('%', offset + 3)) {
if (rest.size() - offset < 3) {
return std::unexpected{"document URI contains malformed percent encoding"};
}
const auto decoded = Void::Encoding::Url::decode(rest.substr(offset, 3));
if (!decoded) {
return std::unexpected{"document URI contains malformed percent encoding"};
}
const char byte = decoded->front();
if (byte == '\0' || (is_file && (byte == '/' || byte == '\\'))) {
return std::unexpected{"document URI contains an encoded separator or NUL"};
}
}
if (!is_file) {
// Virtual schemes own the spelling and meaning of their scheme-specific part.
return ParsedUri{std::move(scheme) + ":" + std::string{rest}, {}};
}
if (rest.starts_with("//")) {
rest.remove_prefix(2);
const auto slash = rest.find('/');
if (slash == std::string_view::npos) {
return std::unexpected{"file URI missing absolute path"};
}
auto authority = rest.substr(0, slash);
if (!authority.empty() && to_lower_ascii(authority) != "localhost") {
return std::unexpected{"remote file URI authority is unsupported"};
}
rest.remove_prefix(slash);
}
if (!rest.starts_with('/') || rest.starts_with("//")) {
return std::unexpected{"file URI requires a local absolute path"};
}
if (rest.find_first_of("?#") != std::string_view::npos) {
return std::unexpected{"file URI must not contain a query or fragment"};
}
auto decoded = Void::Encoding::Url::decode(rest);
if (!decoded || !Void::Unicode::validate_utf8(*decoded)) {
return std::unexpected{"decoded file URI path is not valid UTF-8"};
}
#ifdef _WIN32
// Local drive paths in a file URI have a leading slash before the drive letter.
if (decoded->size() < 4 || !is_ascii_letter((*decoded)[1]) || decoded->substr(2, 2) != ":/") {
return std::unexpected{"file URI requires a local absolute drive path"};
}
decoded->erase(0, 1);
#endif
std::filesystem::path path{std::u8string{decoded->begin(), decoded->end()}};
return ParsedUri{path_to_file_uri(path), std::move(path)};
}
} // namespace
std::string path_to_file_uri(const std::filesystem::path &absolute_path) {
const auto generic_utf8 = absolute_path.generic_u8string();
auto path = utf8_bytes(generic_utf8);
std::string encoded = "file://";
if (!path.starts_with('/')) {
encoded.push_back('/');
}
#ifdef _WIN32
if (path.size() >= 3 && is_ascii_letter(path.front()) && path.substr(1, 2) == ":/") {
encoded.append(path.substr(0, 2));
path.remove_prefix(2);
}
#endif
const auto slash = '/';
while (!path.empty()) {
const auto next = path.find(slash);
encoded += Void::Encoding::Url::encode(path.substr(0, next));
if (next == std::string_view::npos) {
break;
}
encoded.push_back(slash);
path.remove_prefix(next + 1);
}
return encoded;
}
std::expected<std::string, std::string> client_uri_key(std::string_view raw_uri) {
return parse_client_uri(raw_uri).transform([](ParsedUri uri) { return std::move(uri.key); });
}
std::expected<std::filesystem::path, std::string> client_file_path(std::string_view raw_uri) {
return parse_client_uri(raw_uri).transform([](ParsedUri uri) { return std::move(uri.path); });
}
std::expected<DocumentIdentity, std::string> normalize_uri(std::string_view raw_uri) {
auto uri = parse_client_uri(raw_uri);
if (!uri) {
return std::unexpected{std::move(uri.error())};
}
const bool is_file = !uri->path.empty();
return DocumentIdentity{
.canonical_uri = std::move(uri->key),
.display_uri = std::string{raw_uri},
.canonical_path = is_file ? physical_path(uri->path) : std::filesystem::path{},
.is_file_uri = is_file,
};
}
std::expected<DocumentIdentity, std::string> identity_from_path(const std::filesystem::path &path) {
if (path.empty() || path.native().find(std::filesystem::path::value_type{}) !=
std::filesystem::path::string_type::npos) {
return std::unexpected{"filesystem path is empty or contains NUL"};
}
std::error_code error;
auto absolute_path = std::filesystem::absolute(path, error);
if (error) {
return std::unexpected{"cannot make filesystem path absolute"};
}
const auto generic_utf8 = absolute_path.generic_u8string();
const auto absolute_text = utf8_bytes(generic_utf8);
if (absolute_text.size() > kMaxDocumentUriBytes ||
absolute_text.find('\\') != std::string_view::npos ||
!Void::Unicode::validate_utf8(absolute_text)) {
return std::unexpected{"filesystem path cannot be represented as a local document URI"};
}
// Keep the spelling of segments like '..' until physical resolution, where symlinks matter.
const auto uri = path_to_file_uri(absolute_path);
return DocumentIdentity{
.canonical_uri = uri,
.display_uri = uri,
.canonical_path = physical_path(absolute_path),
.is_file_uri = true,
};
}
} // namespace Void::LanguageServer::Documents
-99
View File
@@ -1,99 +0,0 @@
#include <vls/Json.hpp>
#include <Void/Unicode/Utf.hpp>
#include <cmath>
#include <limits>
#include <type_traits>
#include <utility>
namespace vls {
std::expected<Json, std::string> parse_json(std::string_view text, std::size_t maximum_depth) {
if (!Void::Unicode::validate_utf8(text))
return std::unexpected{"invalid UTF-8"};
// Bound structural nesting before calling a recursive dependency parser.
// This scan does not parse JSON or numbers: StrictJson owns that grammar,
// including escape validation and rejection of unpaired surrogate escapes.
std::size_t depth{};
bool in_string = false;
bool escaped = false;
for (const char c : text) {
if (in_string) {
if (escaped)
escaped = false;
else if (c == '\\')
escaped = true;
else if (c == '"')
in_string = false;
} else if (c == '"') {
in_string = true;
} else if (c == '{' || c == '[') {
if (depth >= maximum_depth)
return std::unexpected{"JSON nesting exceeds depth limit"};
++depth;
} else if ((c == '}' || c == ']') && depth > 0) {
--depth;
}
}
auto parsed = Void::Json::Strict::parse(text, maximum_depth);
if (!parsed)
return std::unexpected{parsed.error().message};
return std::move(*parsed);
}
std::expected<RequestId, std::string> request_id(const Json &value) {
// LSP integer IDs are constrained by value, not by JSON number spelling.
// Preserve the value only after checking integrality and the signed range.
return std::visit(
[](const auto &item) -> std::expected<RequestId, std::string> {
using T = std::remove_cvref_t<decltype(item)>;
if constexpr (std::is_same_v<T, std::string>) {
return RequestId{item};
} else if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>) {
if (std::in_range<std::int32_t>(item))
return RequestId{static_cast<std::int32_t>(item)};
} else if constexpr (std::is_floating_point_v<T>) {
const long double wide = static_cast<long double>(item);
if (std::isfinite(item) && std::trunc(item) == item &&
wide >= std::numeric_limits<std::int32_t>::min() &&
wide <= std::numeric_limits<std::int32_t>::max())
return RequestId{static_cast<std::int32_t>(item)};
}
return std::unexpected{"request ID must be a signed 32-bit integer or string"};
},
value.value);
}
std::string quote_json(std::string_view text) {
constexpr char hex[] = "0123456789abcdef";
std::string result{"\""};
for (const unsigned char c : text) {
if (c == '"' || c == '\\') {
result.push_back('\\');
result.push_back(static_cast<char>(c));
} else if (c < 0x20) {
result += "\\u00";
result.push_back(hex[c >> 4]);
result.push_back(hex[c & 15]);
} else {
result.push_back(static_cast<char>(c));
}
}
result.push_back('"');
return result;
}
std::string encode_id(const RequestId &id) {
return std::visit(
[](const auto &item) -> std::string {
if constexpr (std::is_same_v<std::remove_cvref_t<decltype(item)>, std::string>)
return quote_json(item);
else
return std::to_string(item);
},
id);
}
} // namespace vls
+74 -38
View File
@@ -1,51 +1,60 @@
#include <vls/Framing.hpp>
#include <Void/LanguageServer/Protocol/Framing.hpp>
#include <charconv>
#include <istream>
#include <limits>
#include <ostream>
#include <utility>
namespace vls {
namespace Void::LanguageServer::Protocol {
namespace {
std::string_view trim(std::string_view text) {
const auto first = text.find_first_not_of(" \t");
if (first == std::string_view::npos)
if (first == std::string_view::npos) {
return {};
}
return text.substr(first, text.find_last_not_of(" \t") - first + 1);
}
std::string lower(std::string_view text) {
std::string to_ascii_lower(std::string_view text) {
std::string result{text};
for (char &c : result)
if (c >= 'A' && c <= 'Z')
c = static_cast<char>(c + ('a' - 'A'));
for (char &ch : result) {
if (ch >= 'A' && ch <= 'Z') {
ch = static_cast<char>(ch + ('a' - 'A'));
}
}
return result;
}
bool supported_content_type(std::string_view text) {
bool is_supported_content_type(std::string_view text) {
auto separator = text.find(';');
const auto media = lower(trim(text.substr(0, separator)));
if (media != "application/vscode-jsonrpc" && media != "application/json")
const auto media = to_ascii_lower(trim(text.substr(0, separator)));
if (media != "application/vscode-jsonrpc" && media != "application/json") {
return false;
}
bool seen_charset = false;
while (separator != std::string_view::npos) {
text.remove_prefix(separator + 1);
separator = text.find(';');
const auto parameter = trim(text.substr(0, separator));
const auto equals = parameter.find('=');
if (equals == std::string_view::npos)
if (equals == std::string_view::npos) {
return false;
if (lower(trim(parameter.substr(0, equals))) == "charset") {
if (seen_charset)
}
if (to_ascii_lower(trim(parameter.substr(0, equals))) == "charset") {
if (seen_charset) {
return false;
}
seen_charset = true;
auto encoding = trim(parameter.substr(equals + 1));
if (encoding.size() >= 2 && encoding.front() == '"' && encoding.back() == '"')
if (encoding.size() >= 2 && encoding.front() == '"' && encoding.back() == '"') {
encoding = encoding.substr(1, encoding.size() - 2);
const auto name = lower(encoding);
if (name != "utf-8" && name != "utf8")
}
const auto name = to_ascii_lower(encoding);
if (name != "utf-8" && name != "utf8") {
return false;
}
}
}
return true;
@@ -59,21 +68,26 @@ std::expected<std::optional<std::string>, std::string> read_frame(std::istream &
while (!header.ends_with("\r\n\r\n")) {
const auto next = input.get();
if (next == std::char_traits<char>::eof()) {
if (input.bad() || !input.eof())
if (input.bad() || !input.eof()) {
return std::unexpected{"input stream failure"};
if (header.empty())
}
if (header.empty()) {
return std::optional<std::string>{};
}
return std::unexpected{"truncated frame header"};
}
if (header.size() >= limits.header_bytes)
if (header.size() >= limits.header_bytes) {
return std::unexpected{"frame header exceeds byte limit"};
const char c = static_cast<char>(next);
if ((c == '\n' && (header.empty() || header.back() != '\r')) ||
(!header.empty() && header.back() == '\r' && c != '\n'))
}
const char ch = static_cast<char>(next);
if ((ch == '\n' && (header.empty() || header.back() != '\r')) ||
(!header.empty() && header.back() == '\r' && ch != '\n')) {
return std::unexpected{"frame headers require CRLF"};
if (c != '\r' && c != '\n' && c != '\t' && (c < 0x20 || c > 0x7e))
}
if (ch != '\r' && ch != '\n' && ch != '\t' && (ch < 0x20 || ch > 0x7e)) {
return std::unexpected{"non-ASCII frame header"};
header.push_back(c);
}
header.push_back(ch);
}
std::optional<std::size_t> length;
@@ -83,49 +97,71 @@ std::expected<std::optional<std::string>, std::string> read_frame(std::istream &
const auto end = remaining.find("\r\n");
const auto line = remaining.substr(0, end);
const auto colon = line.find(':');
if (colon == std::string_view::npos || colon == 0)
if (colon == std::string_view::npos || colon == 0) {
return std::unexpected{"invalid frame header field"};
}
const auto name = line.substr(0, colon);
if (name.find_first_of(" \t") != std::string_view::npos)
if (name.find_first_of(" \t") != std::string_view::npos) {
return std::unexpected{"invalid frame header name"};
}
const auto value = trim(line.substr(colon + 1));
if (lower(name) == "content-length") {
if (length)
const auto lower_name = to_ascii_lower(name);
if (lower_name == "content-length") {
if (length) {
return std::unexpected{"duplicate Content-Length"};
if (value.empty() || value.find_first_not_of("0123456789") != std::string_view::npos)
}
if (value.empty() || value.find_first_not_of("0123456789") != std::string_view::npos) {
return std::unexpected{"invalid Content-Length"};
}
std::size_t parsed{};
const auto result = std::from_chars(value.data(), value.data() + value.size(), parsed);
if (result.ec != std::errc{} || result.ptr != value.data() + value.size())
if (result.ec != std::errc{} || result.ptr != value.data() + value.size()) {
return std::unexpected{"Content-Length overflow"};
if (parsed > limits.body_bytes || parsed > std::numeric_limits<std::streamsize>::max())
}
if (parsed > limits.body_bytes ||
parsed > static_cast<std::size_t>(std::numeric_limits<std::streamsize>::max())) {
return std::unexpected{"frame body exceeds byte limit"};
}
length = parsed;
} else if (lower(name) == "content-type") {
if (seen_type || !supported_content_type(value))
} else if (lower_name == "content-type") {
if (seen_type || !is_supported_content_type(value)) {
return std::unexpected{"duplicate or unsupported Content-Type/charset"};
}
seen_type = true;
}
remaining.remove_prefix(end + 2);
}
if (!length)
if (!length) {
return std::unexpected{"missing Content-Length"};
}
std::string body(*length, '\0');
input.read(body.data(), static_cast<std::streamsize>(*length));
if (!input)
if (!input) {
return std::unexpected{"truncated frame body or input failure"};
}
return std::optional{std::move(body)};
}
std::expected<void, std::string> write_frame(std::ostream &output, std::string_view body) {
if (body.size() > static_cast<std::size_t>(std::numeric_limits<std::streamsize>::max()))
if (body.size() > static_cast<std::size_t>(std::numeric_limits<std::streamsize>::max())) {
return std::unexpected{"output frame exceeds stream limit"};
}
output << "Content-Length: " << body.size() << "\r\n\r\n";
output.write(body.data(), static_cast<std::streamsize>(body.size()));
output.flush();
if (!output)
if (!output) {
return std::unexpected{"output stream failure"};
}
return {};
}
} // namespace vls
std::expected<void, std::string> write_json_frame(std::ostream &output, const Json &body,
std::size_t maximum_depth) {
auto encoded = serialize_json(body, maximum_depth);
if (!encoded) {
return std::unexpected{std::move(encoded.error())};
}
return write_frame(output, *encoded);
}
} // namespace Void::LanguageServer::Protocol
+160
View File
@@ -0,0 +1,160 @@
#include <Void/LanguageServer/Protocol/Json.hpp>
#include <Void/Unicode/Utf.hpp>
#include <algorithm>
#include <cmath>
#include <limits>
#include <ranges>
#include <utility>
namespace Void::LanguageServer::Protocol {
namespace {
constexpr auto depth_error = "JSON nesting exceeds depth limit";
bool fits_container_depth(const Json &value, std::size_t remaining_depth) {
const auto *array = as_array(&value);
const auto *object = as_object(&value);
if (!array && !object) {
return true;
}
if (remaining_depth == 0) {
return false;
}
const auto fits_child = [remaining_depth](const Json &child) {
return fits_container_depth(child, remaining_depth - 1);
};
if (array) {
return std::ranges::all_of(*array, fits_child);
}
return std::ranges::all_of(*object | std::views::values, fits_child);
}
} // namespace
std::expected<Json, std::string> parse_json(std::string_view text, std::size_t maximum_depth) {
if (!Void::Unicode::validate_utf8(text)) {
return std::unexpected{"invalid UTF-8"};
}
maximum_depth = std::min(maximum_depth, kDefaultMaxJsonDepth);
// Count container openings before handing grammar and escape validation to StrictJson.
std::size_t depth{};
bool in_string = false;
bool escaped = false;
for (const char ch : text) {
if (in_string) {
if (escaped) {
escaped = false;
} else if (ch == '\\') {
escaped = true;
} else if (ch == '"') {
in_string = false;
}
} else if (ch == '"') {
in_string = true;
} else if (ch == '{' || ch == '[') {
if (depth >= maximum_depth) {
return std::unexpected{depth_error};
}
++depth;
} else if ((ch == '}' || ch == ']') && depth > 0) {
--depth;
}
}
auto parsed = Void::Json::Strict::parse(text, maximum_depth);
if (!parsed) {
return std::unexpected{std::move(parsed.error().message)};
}
return std::move(*parsed);
}
std::expected<std::string, std::string> serialize_json(const Json &value,
std::size_t maximum_depth) {
maximum_depth = std::min(maximum_depth, kDefaultMaxJsonDepth);
// StrictJson starts at depth zero, so an empty over-depth container can have no
// children to trigger its limit. Count each container before encoding.
if (!fits_container_depth(value, maximum_depth)) {
return std::unexpected{depth_error};
}
auto encoded = Void::Json::Strict::serialize(value, maximum_depth);
if (!encoded) {
return std::unexpected{std::move(encoded.error().message)};
}
return std::move(*encoded);
}
std::expected<RequestId, std::string> request_id(const Json &value) {
if (const auto *text = as_string(&value)) {
return RequestId{*text};
}
// StrictJson currently exposes decoded numbers. Exact wire-token validation
// requires upstream numeric metadata.
if (const auto number = as_int64(&value); number && std::in_range<std::int32_t>(*number)) {
return RequestId{static_cast<std::int32_t>(*number)};
}
return std::unexpected{"request ID must be a signed 32-bit integer or string"};
}
Json request_id_json(RequestId id) {
if (const auto *number = std::get_if<std::int32_t>(&id)) {
return Json{static_cast<std::int64_t>(*number)};
}
return Json{std::get<std::string>(std::move(id))};
}
const Json *find_member(const Json::Object &object, std::string_view key) noexcept {
const auto found = object.find(key);
return found == object.end() ? nullptr : &found->second;
}
const Json::Object *as_object(const Json *value) noexcept {
return value ? std::get_if<Json::Object>(&value->value) : nullptr;
}
const Json::Array *as_array(const Json *value) noexcept {
return value ? std::get_if<Json::Array>(&value->value) : nullptr;
}
const std::string *as_string(const Json *value) noexcept {
return value ? std::get_if<std::string>(&value->value) : nullptr;
}
std::optional<bool> as_bool(const Json *value) noexcept {
if (!value) {
return std::nullopt;
}
if (const auto *flag = std::get_if<bool>(&value->value)) {
return *flag;
}
return std::nullopt;
}
std::optional<std::int64_t> as_int64(const Json *value) noexcept {
if (!value) {
return std::nullopt;
}
if (const auto *number = std::get_if<std::int64_t>(&value->value)) {
return *number;
}
// A double rounds INT64_MAX up to 2^63. Use an exclusive upper bound.
constexpr auto lower_bound = static_cast<double>(std::numeric_limits<std::int64_t>::min());
if (const auto *number = std::get_if<double>(&value->value); number && *number >= lower_bound &&
*number < -lower_bound &&
std::trunc(*number) == *number) {
return static_cast<std::int64_t>(*number);
}
return std::nullopt;
}
std::optional<std::uint32_t> as_uint32(const Json *value) noexcept {
const auto parsed = as_int64(value);
if (!parsed || !std::in_range<std::uint32_t>(*parsed)) {
return std::nullopt;
}
return static_cast<std::uint32_t>(*parsed);
}
} // namespace Void::LanguageServer::Protocol
+335 -40
View File
@@ -1,51 +1,148 @@
#include <vls/Server.hpp>
#include <vls/DocumentSync.hpp>
#include <vls/Json.hpp>
#include <vls/semantic/EditorDiagnostics.hpp>
#include <condition_variable>
#include <deque>
#include <exception>
#include <mutex>
#include <ostream>
#include <thread>
#include <utility>
namespace vls {
namespace {
const Json *member(const Json::Object &object, std::string_view key) {
const auto found = object.find(key);
return found == object.end() ? nullptr : &found->second;
namespace Protocol = Void::LanguageServer::Protocol;
using Protocol::as_object;
using Protocol::as_string;
using Protocol::find_member;
const Json *member(const Json *value, std::string_view key) {
const auto *object = as_object(value);
return object ? find_member(*object, key) : nullptr;
}
const std::string *string(const Json *value) {
return value ? std::get_if<std::string>(&value->value) : nullptr;
// One writer serves both compiler notifications and request responses. Enqueueing a
// publication never holds the input owner's lock across a potentially blocking stream write.
class Output {
public:
Output(std::ostream &stream, bool asynchronous) : stream_(stream), asynchronous_(asynchronous) {
if (asynchronous_)
writer_ = std::jthread([this] { drain(); });
}
~Output() { finish(); }
bool send(std::string body) {
if (!asynchronous_)
return bool(write_frame(stream_, body));
std::lock_guard lock{mutex_};
constexpr std::size_t limit = 32 * 1024 * 1024;
if (finished_ || failed_ || queue_.size() >= 512 || body.size() > limit - bytes_) {
failed_ = true;
wake_.notify_one();
return false;
}
bytes_ += body.size();
queue_.push_back(std::move(body));
wake_.notify_one();
return true;
}
bool finish() {
{
std::lock_guard lock{mutex_};
finished_ = true;
wake_.notify_one();
}
if (writer_.joinable())
writer_.join();
return !failed_;
}
private:
std::ostream &stream_;
bool asynchronous_, finished_{}, failed_{};
std::mutex mutex_;
std::condition_variable wake_;
std::deque<std::string> queue_;
std::size_t bytes_{};
std::jthread writer_;
void drain() {
std::unique_lock lock{mutex_};
for (;;) {
wake_.wait(lock, [&] { return !queue_.empty() || finished_ || failed_; });
if (failed_ || queue_.empty())
return;
auto body = std::move(queue_.front());
queue_.pop_front();
lock.unlock();
bool ok{};
try {
ok = bool(write_frame(stream_, body));
} catch (const std::exception &) {
}
lock.lock();
bytes_ -= body.size();
if (!ok) {
failed_ = true;
return;
}
}
}
};
Json error_payload(std::int64_t code, std::string_view message) {
return Json{Json::Object{{"code", Json{code}}, {"message", Json{std::string{message}}}}};
}
DispatchResult error(std::string_view id, int code, std::string_view message) {
return {.response = "{\"jsonrpc\":\"2.0\",\"id\":" + std::string{id} + ",\"error\":{\"code\":" +
std::to_string(code) + ",\"message\":" + quote_json(message) + "}}",
.exit_code = std::nullopt};
DispatchResult reply(const Json &id, std::string key, Json payload) {
Json::Object envelope{{"jsonrpc", Json{std::string{"2.0"}}}, {"id", id}};
envelope.emplace(std::move(key), std::move(payload));
auto body = Protocol::serialize_json(Json{std::move(envelope)});
if (body)
return {.response = std::move(*body), .exit_code = std::nullopt};
auto fallback = Protocol::serialize_json(
Json{Json::Object{{"jsonrpc", Json{std::string{"2.0"}}},
{"id", id},
{"error", error_payload(-32603, "Internal error")}}});
if (fallback)
return {.response = std::move(*fallback),
.exit_code = std::nullopt,
.diagnostic = "failed to encode response"};
return {.response = std::nullopt, .exit_code = 1, .diagnostic = "failed to encode response ID"};
}
DispatchResult result(std::string_view id, std::string_view value) {
return {.response = "{\"jsonrpc\":\"2.0\",\"id\":" + std::string{id} +
",\"result\":" + std::string{value} + "}",
.exit_code = std::nullopt};
DispatchResult error(const Json &id, std::int64_t code, std::string_view message) {
return reply(id, "error", error_payload(code, message));
}
} // namespace
Server::Server(WorkspaceLaunch launch, std::function<bool(std::string)> send) : workspace_(launch) {
if (launch.root && launch.diagnostics_profile && send)
diagnostics_ = std::make_unique<semantic::EditorDiagnostics>(
*launch.root, std::move(launch.diagnostics_profile), workspace_, documents_,
std::move(send));
}
Server::~Server() = default;
DispatchResult Server::handle(std::string_view body) {
auto parsed = parse_json(body);
if (!parsed)
return error("null", -32700, "Parse error");
return error(Json{nullptr}, -32700, "Parse error");
const auto *object = std::get_if<Json::Object>(&parsed->value);
if (!object)
return error("null", -32600, "Invalid Request");
return error(Json{nullptr}, -32600, "Invalid Request");
const auto *id_value = member(*object, "id");
const auto *method_value = member(*object, "method");
const auto *method = string(method_value);
const auto *version = string(member(*object, "jsonrpc"));
const auto *params = member(*object, "params");
const auto *result_value = member(*object, "result");
const auto *error_value = member(*object, "error");
const auto *id_value = find_member(*object, "id");
const auto *method_value = find_member(*object, "method");
const auto *method = as_string(method_value);
const auto *version = as_string(find_member(*object, "jsonrpc"));
const auto *params = find_member(*object, "params");
const auto *result_value = find_member(*object, "result");
const auto *error_value = find_member(*object, "error");
// This shell issues no requests. Valid peer responses are unmatched and
// must be ignored, including errors whose correlation ID is null.
@@ -55,9 +152,9 @@ DispatchResult Server::handle(std::string_view body) {
request_id(*id_value).has_value();
bool valid_payload = result_value != nullptr;
if (error_value) {
if (const auto *details = std::get_if<Json::Object>(&error_value->value)) {
if (const auto *code = member(*details, "code");
code && string(member(*details, "message"))) {
if (const auto *details = as_object(error_value)) {
if (const auto *code = find_member(*details, "code");
code && as_string(find_member(*details, "message"))) {
const auto checked = request_id(*code);
valid_payload = checked && std::holds_alternative<std::int32_t>(*checked);
}
@@ -68,23 +165,66 @@ DispatchResult Server::handle(std::string_view body) {
}
const bool notification = !id_value;
std::string id{"null"};
Json id{nullptr};
if (id_value) {
auto checked = request_id(*id_value);
if (!checked)
return error("null", -32600, "Invalid Request");
id = encode_id(*checked);
return error(Json{nullptr}, -32600, "Invalid Request");
id = Protocol::request_id_json(std::move(*checked));
}
if (!version || *version != "2.0" || !method || result_value || error_value) {
// Method-bearing objects without IDs are notifications, even when
// malformed. They must never elicit a response.
if (notification && method && *method == "textDocument/didChange" &&
state_ == State::running) {
if (diagnostics_)
diagnostics_->begin_update();
reject_change_envelope(documents_, params);
if (diagnostics_)
diagnostics_->finish_update();
return {.response = std::nullopt,
.exit_code = std::nullopt,
.diagnostic = "invalid didChange envelope"};
}
if (notification && method_value)
return {};
return error(id, -32600, "Invalid Request");
}
if (notification) {
if (*method == "exit")
if (*method == "exit") {
if (diagnostics_)
diagnostics_->stop();
return {.response = std::nullopt, .exit_code = state_ == State::shutdown ? 0 : 1};
}
if (state_ == State::running) {
if (*method == "workspace/didChangeWorkspaceFolders" ||
*method == "workspace/didChangeConfiguration") {
if (diagnostics_)
diagnostics_->begin_update();
auto updated = *method == "workspace/didChangeWorkspaceFolders"
? workspace_.update_folders(params)
: workspace_.configure(params);
if (diagnostics_)
diagnostics_->finish_update(true);
if (!updated)
return {.response = std::nullopt,
.exit_code = std::nullopt,
.diagnostic = updated.error().substr(0, 256)};
return {};
}
const bool change = *method == "textDocument/didOpen" ||
*method == "textDocument/didChange" ||
*method == "textDocument/didClose";
if (diagnostics_ && change)
diagnostics_->begin_update();
auto synced = synchronize_document(documents_, *method, params);
if (diagnostics_ && change)
diagnostics_->finish_update();
if (!synced)
return {.response = std::nullopt,
.exit_code = std::nullopt,
.diagnostic = synced.error().substr(0, 256)};
}
return {};
}
if (state_ == State::shutdown)
@@ -96,27 +236,181 @@ DispatchResult Server::handle(std::string_view body) {
return error(id, -32600, "Invalid Request");
if (!params || !std::holds_alternative<Json::Object>(params->value))
return error(id, -32602, "initialize params must be an object");
state_ = State::running;
return result(id, "{\"capabilities\":{},\"serverInfo\":{\"name\":\"VoidLanguageServer\","
"\"version\":\"0.1.0\"}}");
if (auto configured = workspace_.initialize(*params); !configured)
return error(id, -32602, configured.error().substr(0, 256));
const auto encoding = negotiate_position_encoding(*params);
if (!documents_.set_position_encoding(encoding))
return error(id, -32603, "Could not set document position encoding");
if (diagnostics_) {
const auto *cap = member(member(member(params, "capabilities"), "textDocument"),
"publishDiagnostics");
diagnostics_->set_version_support(
Protocol::as_bool(member(cap, "versionSupport")).value_or(false));
const auto *edit =
member(member(member(params, "capabilities"), "workspace"), "workspaceEdit");
diagnostics_->set_transactional_rename(
Protocol::as_bool(member(edit, "documentChanges")).value_or(false));
}
Json::Object sync{{"openClose", Json{true}}, {"change", Json{std::int64_t{2}}}};
Json::Object capabilities{
{"positionEncoding",
Json{std::string{Void::LanguageServer::Documents::encoding_name(encoding)}}},
{"textDocumentSync", Json{std::move(sync)}},
{"workspace",
Json{Json::Object{
{"workspaceFolders", Json{Json::Object{{"supported", Json{true}},
{"changeNotifications", Json{true}}}}}}}}};
if (diagnostics_ && diagnostics_->supports_occurrences()) {
capabilities.emplace("hoverProvider", Json{true});
capabilities.emplace("definitionProvider", Json{true});
}
if (diagnostics_)
capabilities.emplace("completionProvider",
Json{Json::Object{{"triggerCharacters", Json{Json::Array{}}},
{"resolveProvider", Json{true}}}});
if (diagnostics_ && diagnostics_->supports_occurrences())
capabilities.emplace("signatureHelpProvider",
Json{Json::Object{{"triggerCharacters",
Json{Json::Array{Json{std::string{"("}},
Json{std::string{","}}}}}}});
Json::Object info{{"name", Json{std::string{"VoidLanguageServer"}}},
{"version", Json{std::string{server_version}}}};
auto initialized = reply(id, "result",
Json{Json::Object{{"capabilities", Json{std::move(capabilities)}},
{"serverInfo", Json{std::move(info)}}}});
if (initialized.diagnostic.empty())
state_ = State::running;
return initialized;
}
if (params && !std::holds_alternative<Json::Object>(params->value) &&
!std::holds_alternative<Json::Array>(params->value) &&
!std::holds_alternative<std::nullptr_t>(params->value))
return error(id, -32600, "Invalid Request");
if (*method == "voidLanguageServer/providerStatus") {
auto status = workspace_.provider_status(params);
if (!status)
return error(id, -32602, status.error().substr(0, 256));
return reply(id, "result", std::move(*status));
}
if (*method == "voidLanguageServer/analysisStatus") {
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_ ? diagnostics_->status(*uri)
: Json{Json::Object{{"state", Json{std::string{"disabled"}}}}});
}
if (*method == "textDocument/hover" || *method == "textDocument/definition" ||
*method == "textDocument/signatureHelp") {
if (!diagnostics_ || !diagnostics_->supports_occurrences())
return error(id, -32601, "Method not found");
const auto *uri = as_string(member(member(params, "textDocument"), "uri"));
const auto *position = member(params, "position");
const auto *line = position ? member(position, "line") : nullptr;
const auto *character = position ? member(position, "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 (!uri || !Void::LanguageServer::Documents::client_uri_key(*uri) || !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 textDocument.uri and a bounded position");
const Void::LanguageServer::Documents::Position selected{
static_cast<std::uint32_t>(*line_value), static_cast<std::uint32_t>(*character_value)};
auto result = *method == "textDocument/hover" ? diagnostics_->hover(*uri, selected)
: *method == "textDocument/definition"
? diagnostics_->definition(*uri, selected)
: diagnostics_->signature_help(*uri, selected);
return reply(id, "result", std::move(result));
}
if (*method == "completionItem/resolve") {
if (!diagnostics_)
return error(id, -32601, "Method not found");
if (!params)
return error(id, -32602, "Expected a completion item");
return reply(id, "result", diagnostics_->completion_resolve(*params));
}
if (*method == "textDocument/completion") {
if (!diagnostics_)
return error(id, -32601, "Method not found");
const auto *uri = as_string(member(member(params, "textDocument"), "uri"));
const auto *position = member(params, "position");
const auto *line = position ? member(position, "line") : nullptr;
const auto *character = position ? member(position, "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 (!uri || !Void::LanguageServer::Documents::client_uri_key(*uri) || !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 textDocument.uri and a bounded position");
return reply(
id, "result",
diagnostics_->completion(*uri, {static_cast<std::uint32_t>(*line_value),
static_cast<std::uint32_t>(*character_value)}));
}
if (*method == "textDocument/references" || *method == "textDocument/prepareRename" ||
*method == "textDocument/rename") {
if (!diagnostics_ || !diagnostics_->supports_occurrences())
return error(id, -32601, "Method not found");
const auto *uri = as_string(member(member(params, "textDocument"), "uri"));
const auto *position = member(params, "position");
const auto *line = position ? member(position, "line") : nullptr;
const auto *character = position ? member(position, "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 (!uri || !Void::LanguageServer::Documents::client_uri_key(*uri) || !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 textDocument.uri and a bounded position");
const Void::LanguageServer::Documents::Position selected{
static_cast<std::uint32_t>(*line_value), static_cast<std::uint32_t>(*character_value)};
semantic::EditorDiagnostics::NavigationReply navigation;
if (*method == "textDocument/references")
navigation = diagnostics_->references(*uri, selected);
else if (*method == "textDocument/prepareRename")
navigation = diagnostics_->prepare_rename(*uri, selected);
else {
const auto *name = as_string(member(params, "newName"));
if (!name || name->size() > 256)
return error(id, -32602, "Expected a bounded newName");
navigation = diagnostics_->rename(*uri, selected, *name);
}
if (navigation.refusal)
return error(id, -32803, navigation.refusal->substr(0, 256));
return reply(id, "result", std::move(navigation.result));
}
if (*method == "workspace/symbol") {
if (!diagnostics_ || !diagnostics_->supports_occurrences())
return error(id, -32601, "Method not found");
const auto *query = as_string(member(params, "query"));
if (!query || query->size() > 256)
return error(id, -32602, "Expected a bounded workspace symbol query");
return reply(id, "result", diagnostics_->workspace_symbols(*query));
}
if (*method == "shutdown") {
if (params && !std::holds_alternative<std::nullptr_t>(params->value))
return error(id, -32602, "shutdown takes no params");
state_ = State::shutdown;
return result(id, "null");
auto stopped = reply(id, "result", Json{nullptr});
if (diagnostics_)
diagnostics_->stop();
if (stopped.diagnostic.empty())
state_ = State::shutdown;
return stopped;
}
return error(id, -32601, "Method not found");
}
int run_stdio(std::istream &input, std::ostream &output, std::ostream &diagnostics,
FrameLimits limits) {
FrameLimits limits, WorkspaceLaunch launch) {
try {
Server server;
Output egress{output, bool(launch.diagnostics_profile)};
Server server{std::move(launch),
[&](std::string body) { return egress.send(std::move(body)); }};
for (;;) {
auto frame = read_frame(input, limits);
if (!frame) {
@@ -128,15 +422,16 @@ int run_stdio(std::istream &input, std::ostream &output, std::ostream &diagnosti
return 1;
}
auto dispatched = server.handle(**frame);
if (!dispatched.diagnostic.empty())
diagnostics << "vls: " << dispatched.diagnostic << '\n';
if (dispatched.response) {
const auto written = write_frame(output, *dispatched.response);
if (!written) {
diagnostics << "vls: " << written.error() << '\n';
if (!egress.send(std::move(*dispatched.response))) {
diagnostics << "vls: failed to write protocol frame\n";
return 1;
}
}
if (dispatched.exit_code)
return *dispatched.exit_code;
return egress.finish() ? *dispatched.exit_code : 1;
}
} catch (const std::exception &) {
diagnostics << "vls: failed to process protocol stream\n";
+467
View File
@@ -0,0 +1,467 @@
#include <Void/LanguageServer/Workspace/Configuration.hpp>
#include <Void/LanguageServer/Support/RegularFile.hpp>
#include <algorithm>
#include <atomic>
#include <ranges>
#include <utility>
namespace Void::LanguageServer::Workspace {
namespace {
namespace fs = std::filesystem;
using Protocol::Json;
constexpr std::size_t max_entries = 256;
constexpr std::size_t max_configuration_bytes = 1024 * 1024;
std::atomic<std::uint64_t> trusted_input_revision{};
struct Limit {
std::string_view key;
std::optional<std::uint32_t> SettingsOverrides::*member;
std::uint32_t minimum, maximum, workspace_ceiling;
};
constexpr ResourceLimitsConfig defaults;
constexpr Limit limits[] = {
{"maxSemanticWorkers", &SettingsOverrides::max_semantic_workers, 1, 64,
defaults.max_semantic_workers},
{"workerMemoryLimitMib", &SettingsOverrides::worker_memory_limit_mib, 128, 65536,
defaults.worker_memory_limit_mib},
{"maxResponseFileDepth", &SettingsOverrides::max_response_file_depth, 1, 32,
defaults.max_response_file_depth},
{"maxResponseFileBytes", &SettingsOverrides::max_response_file_bytes, 1, 16 * 1024 * 1024,
defaults.max_response_file_bytes},
{"maxCompdbBytes", &SettingsOverrides::max_compdb_bytes, 1, 1024 * 1024 * 1024,
defaults.max_compdb_bytes},
{"maxManifestBytes", &SettingsOverrides::max_manifest_bytes, 1, 1024 * 1024 * 1024,
defaults.max_manifest_bytes},
};
bool security_key(std::string_view key) {
constexpr std::string_view names[]{"toolApprovals", "trustedRoots",
"approvedCompilers", "approvedWrappers",
"allowMetadataRefresh", "allowExplicitBuildActions",
"allowCompilerPlugins"};
return std::ranges::contains(names, key);
}
bool valid_text(std::string_view text) {
return !text.empty() && text.size() <= 4095 && text.find('\0') == text.npos;
}
std::optional<fs::path> resolve(const fs::path &base, const fs::path &raw) {
if (!Detail::valid_path(raw)) {
return std::nullopt;
}
auto path = base / raw;
// Keep symlink components, including those followed by "..", as the user selected them.
return Detail::valid_path(path) ? std::optional{std::move(path)} : std::nullopt;
}
std::optional<fs::path> directory(const fs::path &path) {
std::error_code ec;
auto result = fs::canonical(path, ec);
if (ec || !fs::is_directory(result, ec)) {
return std::nullopt;
}
return result;
}
std::optional<AuthorityLevel> operation(std::string_view name) {
if (name == "metadataRefresh")
return AuthorityLevel::trusted_metadata_refresh;
if (name == "compilerUse")
return AuthorityLevel::compiler_use;
if (name == "explicitBuildAction")
return AuthorityLevel::explicit_build_action;
return std::nullopt;
}
std::optional<std::vector<ToolSelection>> read_approvals(const Json &node) {
const auto *rows = Protocol::as_array(&node);
if (!rows || rows->size() > max_entries)
return std::nullopt;
std::vector<ToolSelection> result;
for (const auto &row : *rows) {
const auto *obj = Protocol::as_object(&row);
if (!obj || obj->size() != 3)
return std::nullopt;
const auto *root = Protocol::as_string(Protocol::find_member(*obj, "root"));
const auto *op = Protocol::as_string(Protocol::find_member(*obj, "operation"));
const auto *exe = Protocol::as_string(Protocol::find_member(*obj, "executable"));
if (!root || !op || !exe || !valid_text(*root) || !valid_text(*exe))
return std::nullopt;
const auto kind = operation(*op);
if (!kind)
return std::nullopt;
result.push_back({*root, *kind, *exe});
}
return result;
}
template <typename T> std::optional<std::vector<T>> read_strings(const Json &node) {
const auto *array = Protocol::as_array(&node);
if (!array || array->size() > max_entries)
return std::nullopt;
std::vector<T> result;
for (const auto &value : *array) {
const auto *str = Protocol::as_string(&value);
if (!str || !valid_text(*str))
return std::nullopt;
result.emplace_back(*str);
}
return result;
}
SettingsOverrides read_fields(const Json &json, ConfigLayer source,
std::vector<ConfigDiagnostic> &diagnostics) {
SettingsOverrides out;
auto report = [&](std::string_view key, std::string message,
ConfigIssue issue = ConfigIssue::invalid_value) {
diagnostics.push_back({source, std::string(key.substr(0, 96)), std::move(message), issue});
};
const auto *obj = Protocol::as_object(&json);
if (obj) {
if (const auto *nested = Protocol::find_member(*obj, "voidLanguageServer")) {
obj = Protocol::as_object(nested);
}
}
if (!obj || obj->size() > 64) {
report("", "settings must be an object of at most 64 fields");
out.tool_approvals.emplace();
return out;
}
for (const auto &[key, value] : *obj) {
if (source == ConfigLayer::workspace_local && security_key(key)) {
report(key, "only the launcher can select execution settings",
ConfigIssue::untrusted_setting);
continue;
}
const auto limit = std::ranges::find(limits, key, &Limit::key);
if (limit != std::end(limits)) {
// Resource allocation requires an integer token; a rounded JSON double is ambiguous.
const auto *integer = std::get_if<std::int64_t>(&value.value);
if (integer && std::in_range<std::uint32_t>(*integer)) {
out.*(limit->member) = static_cast<std::uint32_t>(*integer);
} else {
report(key, "expected an unsigned integer");
}
continue;
}
if (key == "provider") {
const auto *name = Protocol::as_string(&value);
for (auto pref : {ProviderPreference::auto_detect, ProviderPreference::vbs,
ProviderPreference::compdb, ProviderPreference::none}) {
if (name && provider_preference_name(pref) == *name)
out.provider = pref;
}
if (!out.provider)
report(key, "expected auto, vbs, compdb or none");
} else if (key == "vbsManifestPath" || key == "compdbPath" || key == "selectedProfile") {
const auto *text = Protocol::as_string(&value);
if (!text || !valid_text(*text))
report(key, "expected a bounded non-empty string");
else if (key == "vbsManifestPath")
out.vbs_manifest_path = *text;
else if (key == "compdbPath")
out.compdb_path = *text;
else
out.selected_profile = *text;
} else if (key == "enableBackgroundIndexing" || key == "allowMetadataRefresh" ||
key == "allowExplicitBuildActions" || key == "allowCompilerPlugins") {
const auto flag = Protocol::as_bool(&value);
if (!flag)
report(key, "expected a boolean");
else if (key == "enableBackgroundIndexing")
out.enable_background_indexing = flag;
else if (key == "allowMetadataRefresh")
out.allow_metadata_refresh = flag;
else if (key == "allowExplicitBuildActions")
out.allow_explicit_build_actions = flag;
else
out.allow_compiler_plugins = flag;
} else if (key == "trustedRoots" || key == "approvedCompilers") {
auto &field = key == "trustedRoots" ? out.trusted_roots : out.approved_compilers;
field = read_strings<fs::path>(value);
if (!field)
report(key, "expected an array of at most 256 non-empty paths");
} else if (key == "approvedWrappers") {
out.approved_wrappers = read_strings<std::string>(value);
if (!out.approved_wrappers)
report(key, "expected an array of supported wrapper names");
} else if (key == "toolApprovals") {
out.tool_approvals = read_approvals(value);
if (!out.tool_approvals)
report(key, "expected at most 256 exact root, operation and executable triples");
} else {
report(key, "unknown workspace setting", ConfigIssue::unsupported);
}
}
return out;
}
} // namespace
std::uint64_t PartialWorkspaceSettings::latest_trusted_revision() noexcept {
return trusted_input_revision.load();
}
PartialWorkspaceSettings::PartialWorkspaceSettings(ConfigOrigin origin, SettingsOverrides values,
std::vector<ConfigDiagnostic> diagnostics)
: origin_(std::move(origin)), values_(std::move(values)), diagnostics_(std::move(diagnostics)) {
const auto source = origin_.layer;
auto report = [&](std::string_view key, std::string message,
ConfigIssue issue = ConfigIssue::invalid_value) {
diagnostics_.push_back({source, std::string(key), std::move(message), issue});
};
if (!Detail::valid_path(origin_.base) || !origin_.base.is_absolute()) {
report("", "an explicit absolute configuration base is required",
ConfigIssue::invalid_origin);
origin_.base.clear();
values_ = {};
values_.tool_approvals.emplace();
return;
}
if (source == ConfigLayer::workspace_local) {
// Resolve the root once so that a later symlink retarget cannot move this configuration.
const auto canonical = directory(origin_.base);
if (!canonical) {
report("", "workspace root must be an existing directory", ConfigIssue::invalid_origin);
origin_.base.clear();
values_ = {};
return;
}
origin_.base = *canonical;
}
if (values_.provider && provider_preference_name(*values_.provider).empty()) {
values_.provider.reset();
report("provider", "unsupported provider preference");
}
for (const auto &limit : limits) {
auto &field = values_.*(limit.member);
if (!field)
continue;
if (*field < limit.minimum || *field > limit.maximum) {
report(limit.key, "value must be between " + std::to_string(limit.minimum) + " and " +
std::to_string(limit.maximum));
field.reset();
} else if (source == ConfigLayer::workspace_local && *field > limit.workspace_ceiling) {
field = limit.workspace_ceiling;
report(limit.key,
"workspace value exceeds the runtime ceiling of " +
std::to_string(limit.workspace_ceiling),
ConfigIssue::resource_limit);
}
}
auto bind_path = [&](std::optional<fs::path> &field, std::string_view key) {
if (!field)
return;
field = resolve(origin_.base, *field);
if (!field)
report(key, "invalid configured path");
};
bind_path(values_.vbs_manifest_path, "vbsManifestPath");
bind_path(values_.compdb_path, "compdbPath");
if (values_.selected_profile && !valid_text(*values_.selected_profile)) {
values_.selected_profile.reset();
report("selectedProfile", "expected a bounded non-empty profile");
}
auto bind_paths = [&](std::optional<std::vector<fs::path>> &list, std::string_view key) {
if (!list)
return;
if (list->size() <= max_entries) {
for (auto &path : *list) {
auto resolved = resolve(origin_.base, path);
if (!resolved) {
list.reset();
report(key, "invalid configured path");
return;
}
path = std::move(*resolved);
}
} else {
list.reset();
report(key, "too many configured paths");
}
};
bind_paths(values_.trusted_roots, "trustedRoots");
bind_paths(values_.approved_compilers, "approvedCompilers");
if (values_.approved_wrappers &&
(values_.approved_wrappers->size() > max_entries ||
!std::ranges::all_of(*values_.approved_wrappers, is_transparent_wrapper))) {
values_.approved_wrappers.emplace();
report("approvedWrappers", "only ccache, sccache and distcc data prefixes are supported");
}
if (values_.allow_compiler_plugins.value_or(false)) {
values_.allow_compiler_plugins = false;
report("allowCompilerPlugins", "compiler plugins are unsupported",
ConfigIssue::unsupported);
}
if (values_.tool_approvals) {
auto bind = [&](ToolSelection &entry) {
if (entry.operation != AuthorityLevel::compiler_use &&
entry.operation != AuthorityLevel::trusted_metadata_refresh &&
entry.operation != AuthorityLevel::explicit_build_action)
return false;
auto root = resolve(origin_.base, entry.root);
auto executable = resolve(origin_.base, entry.executable);
if (!root || !executable)
return false;
auto canonical = directory(*root);
if (!canonical)
return false;
entry.root = std::move(*canonical);
entry.executable = std::move(*executable);
return true;
};
if (values_.tool_approvals->size() > max_entries ||
!std::ranges::all_of(*values_.tool_approvals, bind)) {
report("toolApprovals", "each approval requires an existing workspace directory, a "
"supported operation and a tool path");
}
}
if (source != ConfigLayer::workspace_local &&
std::ranges::any_of(diagnostics_, [](const auto &d) {
return d.issue == ConfigIssue::invalid_value && security_key(d.key);
})) {
// A malformed trusted replacement must not retain either its valid prefix or lower-layer
// grants.
values_.tool_approvals.emplace();
}
}
PartialWorkspaceSettings parse_workspace_settings(const Json &payload,
const fs::path &workspace_root) {
std::vector<ConfigDiagnostic> diagnostics;
auto values = read_fields(payload, ConfigLayer::workspace_local, diagnostics);
return {{ConfigLayer::workspace_local, workspace_root, std::nullopt, 0},
std::move(values),
std::move(diagnostics)};
}
std::expected<PartialWorkspaceSettings, ConfigDiagnostic>
read_user_settings(const fs::path &selected_file) {
const auto revision = ++trusted_input_revision;
std::string bytes;
const auto file =
Detail::read_regular(selected_file, max_configuration_bytes, false, [&](auto chunk) {
bytes.append(reinterpret_cast<const char *>(chunk.data()), chunk.size());
return true;
});
if (!file) {
return std::unexpected(ConfigDiagnostic{
ConfigLayer::user_runtime, "",
"select an absolute, readable regular user configuration file of at most 1 MiB",
ConfigIssue::file_error});
}
auto json = Protocol::parse_json(bytes);
if (!json)
return std::unexpected(ConfigDiagnostic{ConfigLayer::user_runtime, "", json.error(),
ConfigIssue::invalid_value});
std::vector<ConfigDiagnostic> diagnostics;
auto values = read_fields(*json, ConfigLayer::user_runtime, diagnostics);
return PartialWorkspaceSettings{
{ConfigLayer::user_runtime, selected_file.parent_path(), selected_file, revision},
std::move(values),
std::move(diagnostics)};
}
PartialWorkspaceSettings settings_from_cli(SettingsOverrides options, const fs::path &base) {
return {
{ConfigLayer::cli, base, std::nullopt, ++trusted_input_revision}, std::move(options), {}};
}
void MergedConfiguration::apply(const PartialWorkspaceSettings &layer, ConfigLayer expected) {
if (layer.origin_.layer != expected) {
diagnostics_.push_back({layer.origin_.layer, "",
"settings source does not match its merge position",
ConfigIssue::invalid_origin});
return;
}
diagnostics_.insert(diagnostics_.end(), layer.diagnostics_.begin(), layer.diagnostics_.end());
if (expected == ConfigLayer::workspace_local)
effective_.workspace_root = layer.origin_.base;
const auto &v = layer.values_;
auto set = [](auto &dst, const auto &src) {
if (src)
dst = *src;
};
set(effective_.provider, v.provider);
if (v.vbs_manifest_path) {
effective_.vbs_manifest_path = v.vbs_manifest_path;
effective_.vbs_manifest_origin = layer.origin_;
}
if (v.compdb_path) {
effective_.compdb_path = v.compdb_path;
effective_.compdb_origin = layer.origin_;
}
set(effective_.selected_profile, v.selected_profile);
set(effective_.enable_background_indexing, v.enable_background_indexing);
set(effective_.limits.max_semantic_workers, v.max_semantic_workers);
set(effective_.limits.worker_memory_limit_mib, v.worker_memory_limit_mib);
set(effective_.limits.max_response_file_depth, v.max_response_file_depth);
set(effective_.limits.max_response_file_bytes, v.max_response_file_bytes);
set(effective_.limits.max_compdb_bytes, v.max_compdb_bytes);
set(effective_.limits.max_manifest_bytes, v.max_manifest_bytes);
if (expected == ConfigLayer::workspace_local)
return;
set(effective_.trusted_roots, v.trusted_roots);
set(effective_.approved_compilers, v.approved_compilers);
set(effective_.approved_wrappers, v.approved_wrappers);
set(metadata_refresh_, v.allow_metadata_refresh);
set(build_actions_, v.allow_explicit_build_actions);
if (v.tool_approvals) {
effective_.tool_approvals_origin = layer.origin_;
effective_.tool_approvals.clear();
for (const auto &entry : *v.tool_approvals) {
if (entry.root == effective_.workspace_root)
effective_.tool_approvals.push_back(entry);
}
}
}
MergedConfiguration merge_configuration(const PartialWorkspaceSettings &workspace,
const PartialWorkspaceSettings *user,
const PartialWorkspaceSettings *cli) {
MergedConfiguration merged;
merged.apply(workspace, ConfigLayer::workspace_local);
if (user)
merged.apply(*user, ConfigLayer::user_runtime);
if (cli)
merged.apply(*cli, ConfigLayer::cli);
auto &settings = merged.effective_;
auto selected = [&](AuthorityLevel op) {
return std::ranges::contains(settings.tool_approvals, op, &ToolSelection::operation);
};
settings.allow_metadata_refresh =
merged.metadata_refresh_.value_or(selected(AuthorityLevel::trusted_metadata_refresh));
settings.allow_explicit_build_actions =
merged.build_actions_.value_or(selected(AuthorityLevel::explicit_build_action));
std::erase_if(settings.tool_approvals, [&](const auto &entry) {
return (entry.operation == AuthorityLevel::trusted_metadata_refresh &&
!settings.allow_metadata_refresh) ||
(entry.operation == AuthorityLevel::explicit_build_action &&
!settings.allow_explicit_build_actions);
});
return merged;
}
std::string_view provider_preference_name(ProviderPreference pref) noexcept {
switch (pref) {
case ProviderPreference::auto_detect:
return "auto";
case ProviderPreference::vbs:
return "vbs";
case ProviderPreference::compdb:
return "compdb";
case ProviderPreference::none:
return "none";
}
return {};
}
bool is_transparent_wrapper(std::string_view name) noexcept {
return name == "ccache" || name == "sccache" || name == "distcc";
}
} // namespace Void::LanguageServer::Workspace
+615
View File
@@ -0,0 +1,615 @@
#include <Void/LanguageServer/Workspace/Trust.hpp>
#include <Void/LanguageServer/Support/RegularFile.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <algorithm>
#include <ranges>
namespace Void::LanguageServer::Workspace {
namespace {
namespace fs = std::filesystem;
using DirectoryId = std::pair<std::uint64_t, std::uint64_t>;
bool valid_digest(std::string_view hex) {
return hex.size() == 64 && std::ranges::all_of(hex, [](char c) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
});
}
TrustError file_error(Detail::FileError error) {
using enum Detail::FileError;
switch (error) {
case invalid_path:
return TrustError::invalid_path;
case unavailable:
return TrustError::unavailable_file;
case not_regular:
return TrustError::not_regular;
case not_executable:
return TrustError::not_executable;
case too_large:
return TrustError::too_large;
case changed:
return TrustError::identity_changed;
case sink_failed:
return TrustError::digest_unavailable;
}
return TrustError::unavailable_file;
}
std::optional<DirectoryId> directory_id(const fs::path &path) {
if (!Detail::valid_path(path) || !path.is_absolute())
return std::nullopt;
std::error_code ec;
struct stat info{};
if (fs::canonical(path, ec).native() != path.native() || ec ||
::stat(path.c_str(), &info) != 0 || !S_ISDIR(info.st_mode))
return std::nullopt;
return DirectoryId{info.st_dev, info.st_ino};
}
bool bounded_arguments(std::span<const std::string> argv) {
if (argv.size() > 4096)
return false;
std::size_t remaining = 1024 * 1024;
for (const auto &arg : argv) {
if (arg.size() > 64 * 1024 || arg.size() > remaining || arg.find('\0') != arg.npos)
return false;
remaining -= arg.size();
}
return true;
}
bool normalized_operand(std::string_view value) {
if (value.empty() || value.front() != '/' || value.size() > 4095)
return false;
const fs::path path{value};
return path.lexically_normal().native() == value;
}
bool macro_operand(std::string_view value, bool definition) {
const auto equals = value.find('=');
if (!definition && equals != value.npos)
return false;
const auto name = value.substr(0, equals);
auto first = [](char c) {
return c == '_' || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
};
return !name.empty() && first(name.front()) &&
std::ranges::all_of(name, [&](char c) { return first(c) || (c >= '0' && c <= '9'); });
}
bool supported_driver(const fs::path &selected, CompilerDriver driver) {
const auto name = selected.filename().string();
const auto dash = name.find('-');
const auto stem = std::string_view{name}.substr(0, dash);
if (dash != name.npos) {
auto version = std::string_view{name}.substr(dash + 1);
if (version.empty() || version.front() == '.' || version.back() == '.' ||
version.contains("..") || !std::ranges::all_of(version, [](char c) {
return c == '.' || (c >= '0' && c <= '9');
}))
return false;
}
if (driver == CompilerDriver::gcc)
return stem == "gcc" || stem == "g++" || stem == "cc" || stem == "c++";
if (driver == CompilerDriver::clang)
return stem == "clang" || stem == "clang++" || stem == "cc" || stem == "c++";
return false;
}
bool simple_compiler_option(std::string_view arg, CompilerDriver driver) {
if (arg == "-freflection")
return driver == CompilerDriver::gcc;
constexpr std::string_view flags[]{"-c",
"-fsyntax-only",
"-pthread",
"-g",
"-g0",
"-g1",
"-g2",
"-g3",
"-O0",
"-O1",
"-O2",
"-O3",
"-Os",
"-Og",
"-Wall",
"-Wextra",
"-Wpedantic",
"-Werror",
"-fPIC",
"-fpic",
"-fPIE",
"-fpie",
"-fno-exceptions",
"-fno-rtti",
"-fmodules",
"-fmodules-ts",
"-fmodule-header"};
if (std::ranges::contains(flags, arg))
return true;
if (!arg.starts_with("-std="))
return false;
constexpr std::string_view standards[]{
"c89", "c99", "c11", "c17", "c23", "gnu89", "gnu99",
"gnu11", "gnu17", "gnu23", "c++98", "c++03", "c++11", "c++14",
"c++17", "c++20", "c++23", "c++26", "c++2c", "gnu++98", "gnu++03",
"gnu++11", "gnu++14", "gnu++17", "gnu++20", "gnu++23", "gnu++26", "gnu++2c"};
return std::ranges::contains(standards, arg.substr(5));
}
std::optional<DirectoryId> invocation_directory(const BuildInvocation &invocation) {
auto has_identity = [](std::string_view id) {
return !id.empty() && id.size() <= 4095 && id.find('\0') == id.npos;
};
if (!has_identity(invocation.input_identity) ||
!has_identity(invocation.environment_identity) ||
!bounded_arguments(invocation.arguments) || !Detail::valid_path(invocation.root) ||
!Detail::valid_path(invocation.executable) || !invocation.executable.is_absolute() ||
!Detail::valid_path(invocation.working_directory) ||
!std::ranges::starts_with(invocation.working_directory, invocation.root))
return std::nullopt;
return directory_id(invocation.working_directory);
}
} // namespace
std::string_view trust_error_message(TrustError error) noexcept {
using enum TrustError;
switch (error) {
case invalid_path:
return "select an absolute path without embedded NUL";
case unavailable_file:
return "selected file is missing or unreadable";
case not_regular:
return "select a regular executable file";
case not_executable:
return "selected file lacks executable permission";
case too_large:
return "selected executable exceeds the inspection limit";
case digest_unavailable:
return "a complete SHA-256 identity is required";
case identity_changed:
return "selected file changed; refresh its trusted selection";
case untrusted_root:
return "workspace has no current trusted tool selections";
case operation_not_approved:
return "select a tool for this operation in trusted settings";
case tool_not_approved:
return "executable spelling is outside this operation's selections";
case tool_not_pinned:
return "the launcher must pin the selected executable first";
case stale_generation:
return "workspace authority changed; discard the old request";
case explicit_action_required:
return "this operation requires an explicit build action";
case invalid_invocation:
return "provide the complete bounded invocation with a canonical cwd inside its workspace";
case action_pending:
return "finish or cancel the pending build action";
case action_not_current:
return "the build approval is cancelled, spent or from another policy";
case invocation_mismatch:
return "the invocation differs from the user's approved build";
case capacity_exceeded:
return "too many workspaces have active tool selections";
}
return "unknown trust failure";
}
std::expected<ToolIdentity, TrustError> inspect_tool_identity(const fs::path &executable) {
auto hasher = Crypto::Hasher::create(Crypto::HashAlgorithm::Sha256);
if (!hasher)
return std::unexpected(TrustError::digest_unavailable);
const auto file = Detail::read_regular(executable, max_tool_bytes, true, [&](auto chunk) {
return hasher->update(chunk).has_value();
});
if (!file)
return std::unexpected(file_error(file.error()));
auto digest = hasher->finalize();
if (!digest || digest->size() != 32)
return std::unexpected(TrustError::digest_unavailable);
constexpr std::string_view alphabet = "0123456789abcdef";
std::string hex;
hex.reserve(64);
for (const auto byte : *digest) {
const auto n = std::to_integer<unsigned>(byte);
hex += alphabet[n >> 4];
hex += alphabet[n & 15];
}
const auto &info = file->metadata;
return ToolIdentity{executable,
file->canonical_path,
info.st_dev,
info.st_ino,
static_cast<std::uint64_t>(info.st_size),
info.st_mode,
info.st_uid,
info.st_gid,
std::move(hex)};
}
std::expected<ToolIdentity, TrustError> revalidate_tool_identity(const ToolIdentity &pinned) {
if (!valid_digest(pinned.content_hash_hex))
return std::unexpected(TrustError::digest_unavailable);
auto current = inspect_tool_identity(pinned.selected_path);
if (!current)
return std::unexpected(current.error());
if (*current != pinned)
return std::unexpected(TrustError::identity_changed);
return current;
}
CommandSecurityReport classify_and_unwrap_command(std::span<const std::string> argv,
std::span<const std::string> recognized_wrappers,
const ToolIdentity &selected_compiler,
CompilerDriver driver) {
using enum FlagClassification;
auto refuse = [](FlagClassification issue, std::size_t index, std::string_view reason) {
return CommandSecurityReport{
.classification = issue, .argument_index = index, .reason = reason};
};
if (argv.empty() || !bounded_arguments(argv) || recognized_wrappers.size() > 256)
return refuse(invalid_command, 0, "provide an argv within the count and byte limits");
for (std::size_t i = 0; i < argv.size(); ++i) {
if (std::ranges::any_of(argv[i], [](unsigned char c) { return c < 32 || c == 127; }))
return refuse(invalid_command, i,
"control characters are unsupported in compiler arguments");
}
if (!Detail::valid_path(selected_compiler.selected_path) ||
!selected_compiler.selected_path.is_absolute() ||
!valid_digest(selected_compiler.content_hash_hex))
return refuse(unapproved_compiler_path, 0,
"select an absolute compiler with a complete SHA-256 identity");
std::size_t compiler = 0;
while (compiler < argv.size() && argv[compiler] != selected_compiler.selected_path.native()) {
const fs::path wrapper{argv[compiler]};
const auto name = wrapper.filename().string();
if (!is_transparent_wrapper(name) || (!wrapper.is_absolute() && wrapper != name) ||
!std::ranges::contains(recognized_wrappers, name)) {
if (is_transparent_wrapper(name) ||
std::ranges::contains(argv.subspan(compiler + 1),
selected_compiler.selected_path.native()))
return refuse(execution_bearing_wrapper, compiler, "unsupported wrapper prefix");
return refuse(unapproved_compiler_path, compiler,
"argv requires the exact selected compiler spelling");
}
++compiler;
}
if (compiler == argv.size())
return refuse(unapproved_compiler_path, compiler,
"missing selected compiler after wrapper");
if (!supported_driver(selected_compiler.selected_path, driver))
return refuse(unsupported_driver, compiler,
"select a supported GCC or Clang C/C++ driver dialect and spelling");
bool compile_only = false;
std::size_t sources = 0;
for (std::size_t i = compiler + 1; i < argv.size(); ++i) {
const std::string_view arg = argv[i];
if (arg.starts_with('@'))
return refuse(unresolved_response_file, i,
"expand and identify the response file before classification");
if (arg.starts_with("-fplugin") || arg.starts_with("-fpass-plugin") || arg == "-load" ||
arg == "-plugin" || arg == "-add-plugin")
return refuse(execution_bearing_plugin, i, "compiler and pass plugins are unsupported");
if (arg.starts_with("-wrapper"))
return refuse(execution_bearing_wrapper, i,
"compiler wrapper execution is unsupported");
if (arg.starts_with("-specs") || arg.starts_with("--specs") || arg.starts_with("-B") ||
arg.starts_with("-X") || arg.starts_with("-Wl,") || arg.starts_with("-Wa,") ||
arg.starts_with("-Wp,") || arg.starts_with("--config") ||
arg.starts_with("--driver-mode"))
return refuse(
suspicious_toolchain_override, i,
"driver overrides and forwarded options require a supported interpretation");
if (simple_compiler_option(arg, driver)) {
compile_only |= arg == "-c" || arg == "-fsyntax-only";
continue;
}
constexpr std::string_view operands[]{"-I", "-isystem", "-iquote", "-D", "-U", "-x"};
const auto option =
std::ranges::find_if(operands, [&](auto name) { return arg.starts_with(name); });
if (option != std::end(operands)) {
auto value = arg.substr(option->size());
if (value.empty()) {
if (i + 1 == argv.size())
return refuse(unsupported_operand, i, "missing compiler option operand");
value = argv[++i];
}
if (value.starts_with('@'))
return refuse(unresolved_response_file, i, "unexpanded response-file operand");
bool valid;
if (*option == "-D" || *option == "-U")
valid = macro_operand(value, *option == "-D");
else if (*option == "-x")
valid = value == "c" || value == "c++";
else
valid = normalized_operand(value);
if (!valid)
return refuse(unsupported_operand, i,
"unsupported or unresolved compiler option operand");
continue;
}
if (arg.starts_with('-'))
return refuse(unsupported_option, i,
"compiler option is outside the supported semantic grammar");
constexpr std::string_view suffixes[]{".c", ".C", ".cc", ".cp", ".cpp", ".cxx", ".c++",
".cppm", ".ixx", ".h", ".hh", ".hpp", ".hxx"};
if (!normalized_operand(arg) ||
!std::ranges::contains(suffixes, fs::path(arg).extension().string()))
return refuse(unsupported_operand, i,
"expected a normalized absolute C/C++ input path");
++sources;
}
if (!compile_only || sources != 1)
return refuse(invalid_command, compiler,
"expected one C/C++ input with -c or -fsyntax-only");
CommandSecurityReport result{.allowed = true,
.classification = compiler ? transparent_wrapper : safe};
result.unwrapped_wrappers.assign(argv.begin(), argv.begin() + compiler);
result.unwrapped_argv.assign(argv.begin() + compiler, argv.end());
return result;
}
TrustPolicy::TrustPolicy(RevocationCallback on_revocation)
: on_revocation_(std::move(on_revocation)) {}
void TrustPolicy::notify(const fs::path &root, std::uint64_t generation) const {
if (on_revocation_)
on_revocation_(root, generation);
}
std::expected<std::uint64_t, TrustError>
TrustPolicy::replace_configuration(const MergedConfiguration &configuration) {
const auto &settings = configuration.effective();
const auto &root = settings.workspace_root;
const auto id = directory_id(root);
if (!id) {
revoke_root_authority(root);
return std::unexpected(TrustError::invalid_path);
}
RootState next{.directory = *id,
.origin = settings.tool_approvals_origin,
.approval_floor = settings.tool_approvals_origin.revision};
if (settings.tool_approvals_origin.layer == ConfigLayer::user_runtime ||
settings.tool_approvals_origin.layer == ConfigLayer::cli) {
for (const auto &approval : settings.tool_approvals) {
if (approval.root == root)
next.tools.try_emplace({approval.operation, approval.executable.native()});
}
}
std::unique_lock lock(mutex_);
auto slot = roots_.find(root);
const bool replacing = slot != roots_.end();
if (!replacing) {
if (next.tools.empty())
return 0; // Passive workspace traffic creates no authority state.
// Retain each trusted root's revocation floor for the lifetime of this policy.
if (roots_.size() >= 256)
return std::unexpected(TrustError::capacity_exceeded);
slot = roots_.try_emplace(root).first;
} else {
auto &state = slot->second;
if (next.origin.revision != 0 && next.origin.revision < state.origin.revision)
return std::unexpected(TrustError::stale_generation);
if (next.tools.empty()) {
next.approval_floor = PartialWorkspaceSettings::latest_trusted_revision();
if (state.tools.empty()) {
state.approval_floor = next.approval_floor;
return state.generation;
}
} else if (next.origin.revision <= state.approval_floor) {
if (next.origin.revision != state.origin.revision)
return std::unexpected(TrustError::stale_generation);
// Re-merging the same launcher input (for example after a didChangeConfiguration)
// can tighten a scope. Only a fresh trusted selection can reinstate a missing pin.
const auto removed = std::erase_if(state.tools, [&](const auto &entry) {
return state.directory != *id || !next.tools.contains(entry.first);
});
const bool missing = state.tools.size() != next.tools.size();
if (removed) {
state.pending.reset();
state.approval_floor = PartialWorkspaceSettings::latest_trusted_revision();
state.generation = ++last_generation_;
}
const auto generation = state.generation;
lock.unlock();
if (removed)
notify(root, generation);
if (missing)
return std::unexpected(TrustError::stale_generation);
return generation;
}
}
const auto generation = ++last_generation_;
next.generation = generation;
slot->second = std::move(next);
lock.unlock();
if (replacing)
notify(root, generation);
return generation;
}
std::uint64_t TrustPolicy::generation(const fs::path &root) const {
std::lock_guard lock(mutex_);
auto slot = roots_.find(root);
return slot == roots_.end() ? 0 : slot->second.generation;
}
void TrustPolicy::revoke_root_authority(const fs::path &root) {
std::unique_lock lock(mutex_);
auto slot = roots_.find(root);
if (slot == roots_.end())
return;
slot->second.approval_floor = PartialWorkspaceSettings::latest_trusted_revision();
if (slot->second.tools.empty())
return;
slot->second.tools.clear();
slot->second.pending.reset();
const auto generation = slot->second.generation = ++last_generation_;
lock.unlock();
notify(root, generation);
}
std::expected<ToolCheck, TrustError>
TrustPolicy::inspect_selected(const fs::path &root, AuthorityLevel purpose,
const fs::path &executable,
std::optional<std::uint64_t> required_generation) {
if (!Detail::valid_path(root) || !root.is_absolute() || !Detail::valid_path(executable) ||
!executable.is_absolute())
return std::unexpected(TrustError::invalid_path);
std::unique_lock lock(mutex_);
auto slot = roots_.find(root);
if (slot == roots_.end() || slot->first.native() != root.native() || slot->second.tools.empty())
return std::unexpected(TrustError::untrusted_root);
const auto generation = slot->second.generation;
if (required_generation && generation != *required_generation)
return std::unexpected(TrustError::stale_generation);
const Key key{purpose, executable.native()};
auto selection = slot->second.tools.find(key);
if (selection == slot->second.tools.end()) {
auto other = slot->second.tools.lower_bound({key.first, {}});
return std::unexpected(other != slot->second.tools.end() && other->first.first == key.first
? TrustError::tool_not_approved
: TrustError::operation_not_approved);
}
const auto pinned = selection->second;
if (!pinned && required_generation)
return std::unexpected(TrustError::tool_not_pinned);
const auto expected_directory = slot->second.directory;
lock.unlock();
auto observed = pinned ? revalidate_tool_identity(*pinned) : inspect_tool_identity(executable);
const bool same_root = directory_id(root) == expected_directory;
lock.lock();
slot = roots_.find(root);
if (slot == roots_.end() || slot->second.generation != generation)
return std::unexpected(TrustError::stale_generation);
auto &state = slot->second;
auto &current_pin = state.tools.at(key);
// Concurrent first pins can finish in either order; a later observation must agree with the
// already committed identity. A transient failed first inspection cannot mint a pin.
if (observed && current_pin && *current_pin != *observed)
observed = std::unexpected(TrustError::identity_changed);
if (!same_root || !observed) {
const auto error = same_root ? observed.error() : TrustError::untrusted_root;
if (same_root && !current_pin)
return std::unexpected(error);
if (!same_root)
state.tools.clear();
else
state.tools.erase(key);
state.pending.reset();
state.approval_floor = PartialWorkspaceSettings::latest_trusted_revision();
const auto revoked = state.generation = ++last_generation_;
lock.unlock();
notify(root, revoked);
return std::unexpected(error);
}
if (!current_pin)
current_pin = *observed;
return ToolCheck{std::move(*observed), root, key.first, generation, state.origin};
}
std::expected<ToolCheck, TrustError>
TrustPolicy::pin_approved_tool(const fs::path &root, AuthorityLevel purpose, const fs::path &exe) {
return inspect_selected(root, purpose, exe, std::nullopt);
}
std::expected<ToolCheck, TrustError> TrustPolicy::check_tool(const fs::path &root,
AuthorityLevel purpose,
const fs::path &exe,
std::uint64_t expected_generation) {
if (purpose == AuthorityLevel::explicit_build_action)
return std::unexpected(TrustError::explicit_action_required);
return inspect_selected(root, purpose, exe, expected_generation);
}
bool BuildInvocation::operator==(const BuildInvocation &other) const {
return root.native() == other.root.native() &&
executable.native() == other.executable.native() &&
working_directory.native() == other.working_directory.native() &&
arguments == other.arguments && input_identity == other.input_identity &&
environment_identity == other.environment_identity &&
trust_generation == other.trust_generation;
}
std::expected<BuildApproval, TrustError>
TrustPolicy::approve_build_action(const BuildInvocation &invocation) {
{
std::lock_guard lock(mutex_);
auto slot = roots_.find(invocation.root);
if (slot != roots_.end() && slot->second.generation == invocation.trust_generation &&
slot->second.pending)
return std::unexpected(TrustError::action_pending);
}
const auto cwd = invocation_directory(invocation);
if (!cwd)
return std::unexpected(TrustError::invalid_invocation);
auto checked = inspect_selected(invocation.root, AuthorityLevel::explicit_build_action,
invocation.executable, invocation.trust_generation);
if (!checked)
return std::unexpected(checked.error());
std::lock_guard lock(mutex_);
auto slot = roots_.find(invocation.root);
if (slot == roots_.end() || slot->second.generation != invocation.trust_generation)
return std::unexpected(TrustError::stale_generation);
if (slot->second.pending)
return std::unexpected(TrustError::action_pending);
slot->second.pending = std::make_shared<const BuildInvocation>(invocation);
return BuildApproval{slot->second.pending, *cwd};
}
std::expected<ToolCheck, TrustError>
TrustPolicy::consume_build_action(const BuildApproval &approval,
const BuildInvocation &invocation) {
if (!approval.invocation_)
return std::unexpected(TrustError::action_not_current);
if (*approval.invocation_ != invocation)
return std::unexpected(TrustError::invocation_mismatch);
{
std::lock_guard lock(mutex_);
auto slot = roots_.find(invocation.root);
if (slot == roots_.end() || slot->second.pending != approval.invocation_)
return std::unexpected(TrustError::action_not_current);
}
if (invocation_directory(invocation) != approval.directory_) {
(void)cancel_build_action(approval);
return std::unexpected(TrustError::invalid_invocation);
}
auto checked = inspect_selected(invocation.root, AuthorityLevel::explicit_build_action,
invocation.executable, invocation.trust_generation);
if (!checked)
return std::unexpected(checked.error());
if (directory_id(invocation.working_directory) != approval.directory_) {
(void)cancel_build_action(approval);
return std::unexpected(TrustError::invalid_invocation);
}
std::lock_guard lock(mutex_);
auto slot = roots_.find(invocation.root);
if (slot == roots_.end() || slot->second.pending != approval.invocation_ ||
slot->second.generation != checked->trust_generation)
return std::unexpected(TrustError::action_not_current);
slot->second.pending.reset();
return checked;
}
bool TrustPolicy::cancel_build_action(const BuildApproval &approval) {
if (!approval.invocation_)
return false;
std::lock_guard lock(mutex_);
auto slot = roots_.find(approval.invocation_->root);
if (slot == roots_.end() || slot->second.pending != approval.invocation_)
return false;
slot->second.pending.reset();
return true;
}
} // namespace Void::LanguageServer::Workspace
File diff suppressed because it is too large. Load diff
+26
View File
@@ -0,0 +1,26 @@
#pragma once
#include <Void/LanguageServer/Protocol/Json.hpp>
namespace vls::debug {
namespace Protocol = Void::LanguageServer::Protocol;
using Json = Protocol::Json;
inline Json text(std::string_view value) { return Json{std::string(value)}; }
inline Json number(std::int64_t value) { return Json{value}; }
inline std::optional<std::int64_t> integer(const Json::Object &object, std::string_view key) {
const auto *member = Protocol::find_member(object, key);
if (member)
if (const auto *value = std::get_if<std::int64_t>(&member->value))
return *value;
return {};
}
inline std::optional<std::string_view> string_field(const Json::Object &object,
std::string_view key) {
if (const auto *value = Protocol::as_string(Protocol::find_member(object, key)))
return *value;
return {};
}
} // namespace vls::debug
+681
View File
@@ -0,0 +1,681 @@
#include "../Fields.hpp"
#include "Projection.hpp"
#include <vls/debug/live/LiveSession.hpp>
#include <vls/reflection/Provenance.hpp>
#include <Void/LanguageServer/Protocol/Framing.hpp>
#include <algorithm>
#include <csignal>
#include <iostream>
#include <limits>
namespace vls::debug::dap {
namespace {
constexpr auto max_seq = std::numeric_limits<std::int32_t>::max();
struct Request {
std::int64_t seq;
std::string command;
};
struct LiveLaunch {
std::filesystem::path worker, compiler, source, trace;
std::string sha256;
};
std::vector<reflection::SpliceOrigin> splice_origins(const Json::Object &snapshot) {
std::vector<reflection::SpliceOrigin> origins;
const auto *list = Protocol::as_array(Protocol::find_member(snapshot, "origins"));
if (!list)
return origins;
for (const auto &item : *list) {
const auto *fields = Protocol::as_object(&item);
if (!fields)
continue;
reflection::SpliceOrigin origin;
origin.source = string_field(*fields, "source").value_or("");
origin.line = static_cast<std::uint32_t>(integer(*fields, "line").value_or(0));
origin.byteColumn = static_cast<std::uint32_t>(integer(*fields, "byteColumn").value_or(0));
origin.targetKind = string_field(*fields, "targetKind").value_or("");
origin.targetName = string_field(*fields, "targetName").value_or("");
origin.targetSource = string_field(*fields, "targetSource").value_or("");
if (const auto line = integer(*fields, "targetLine"))
origin.targetLine = static_cast<std::uint32_t>(*line);
if (const auto column = integer(*fields, "targetByteColumn"))
origin.targetByteColumn = static_cast<std::uint32_t>(*column);
origins.push_back(std::move(origin));
}
return origins;
}
class Adapter {
public:
explicit Adapter(std::filesystem::path trace, std::optional<LiveLaunch> live = {})
: selected_(std::move(trace)), live_launch_(std::move(live)) {}
void run(std::istream &input, std::ostream &output);
private:
std::filesystem::path selected_;
std::optional<LiveLaunch> live_launch_;
std::optional<live::LiveSession> live_;
std::map<std::string, std::vector<std::int64_t>> live_breakpoints_;
std::uint64_t live_generation_{};
std::ostream *output_{};
std::optional<ReplaySession> session_;
std::optional<Request> launch_;
std::int64_t received_{}, sent_{};
bool initialized_{}, configured_{}, ended_{}, disconnected_{};
bool variable_paging_{};
void begin_live();
void live_stop_event();
void live_breakpoints(const Request &, const Json::Object &);
void move_live(const Request &, bool step);
[[nodiscard]] Json inspect_live();
[[nodiscard]] std::int64_t live_handle(std::size_t frame) const;
[[nodiscard]] std::size_t live_frame(std::int64_t handle) const;
void live_stack(const Request &, const Json::Object &);
void live_scopes(const Request &, const Json::Object &);
void live_variables(const Request &, const Json::Object &);
void write(Json::Object);
void response(const Request &, Json::Object body = {});
void failure(const Request &, std::string_view message);
void event(std::string_view name, Json::Object body = {});
void position_event();
void finish();
void begin_if_ready();
void end_pending_launch(std::string_view reason);
[[noreturn]] void invalid_input(std::string_view reason);
void dispatch(const Request &, const Json::Object &arguments);
};
void Adapter::write(Json::Object message) {
if (sent_ == max_seq)
throw std::runtime_error("DAP output sequence exhausted");
message.emplace("seq", number(++sent_));
auto result = Protocol::write_json_frame(*output_, Json{std::move(message)});
if (!result)
throw std::runtime_error(result.error());
}
void Adapter::response(const Request &r, Json::Object body) {
write({{"type", text("response")},
{"request_seq", number(r.seq)},
{"command", text(r.command)},
{"success", Json{true}},
{"body", Json{std::move(body)}}});
}
void Adapter::failure(const Request &r, std::string_view message) {
write({{"type", text("response")},
{"request_seq", number(r.seq)},
{"command", text(r.command)},
{"success", Json{false}},
{"message", text(message)}});
}
void Adapter::event(std::string_view name, Json::Object body) {
write({{"type", text("event")}, {"event", text(name)}, {"body", Json{std::move(body)}}});
}
void Adapter::position_event() {
if (live_) {
live_stop_event();
return;
}
const auto kind = session_->pause_kind();
const auto description = kind == "recordedStop" ? "Recorded compiler stop"
: kind == "value" ? "Recorded evaluation result"
: "Recorded compiler event";
event("stopped", {{"reason", text(kind)},
{"description", text(description)},
{"threadId", number(1)},
{"allThreadsStopped", Json{true}}});
}
void Adapter::finish() {
if (ended_)
return;
ended_ = true;
if (session_)
session_->finish();
event("terminated");
}
void Adapter::begin_if_ready() {
if (!launch_ || !configured_)
return;
const auto request = std::move(*launch_);
launch_.reset();
auto moved = session_->initial_position();
if (!moved) {
failure(request, moved.error());
finish();
return;
}
response(request);
if (*moved)
position_event();
else
finish();
}
void Adapter::begin_live() {
if (!launch_ || !live_ || !configured_)
return;
auto request = std::move(*launch_);
launch_.reset();
auto started = live_->start();
if (!started) {
failure(request, started.error());
finish();
return;
}
response(request);
live_generation_ = started->generation;
position_event();
}
void Adapter::live_stop_event() {
Json::Object body{{"reason", text("step")},
{"description", text("Private compiler stop")},
{"threadId", number(1)},
{"allThreadsStopped", Json{true}}};
std::vector<std::int64_t> hits;
const auto snapshot = live_->inspect();
if (snapshot) {
const auto *fields = Protocol::as_object(&*snapshot);
const auto *frames =
fields ? Protocol::as_array(Protocol::find_member(*fields, "frames")) : nullptr;
const auto *frame =
frames && !frames->empty() ? Protocol::as_object(&frames->front()) : nullptr;
const auto line = frame ? integer(*frame, "line") : std::nullopt;
const auto source = frame ? string_field(*frame, "source") : std::nullopt;
if (line && source) {
const auto selected = live_breakpoints_.find(std::string{*source});
if (selected != live_breakpoints_.end() &&
std::ranges::contains(selected->second, *line))
hits.push_back(*line);
}
}
if (!hits.empty()) {
Json::Array ids;
for (const auto hit : hits)
ids.push_back(number(hit));
body.insert_or_assign("reason", text("breakpoint"));
body.emplace("hitBreakpointIds", Json{std::move(ids)});
}
event("stopped", std::move(body));
}
void Adapter::live_breakpoints(const Request &r, const Json::Object &args) {
const auto *source = Protocol::find_member(args, "source");
const auto *source_fields = source ? Protocol::as_object(source) : nullptr;
const auto path = source_fields ? string_field(*source_fields, "path") : std::nullopt;
if (!path)
throw RequestError("breakpoints require a source path");
const auto *lines = Protocol::as_array(Protocol::find_member(args, "lines"));
if (!lines || lines->size() > 4096)
throw RequestError("invalid breakpoint list");
std::vector<std::int64_t> selected;
Json::Array returned;
for (const auto &entry : *lines) {
const auto *line = std::get_if<std::int64_t>(&entry.value);
if (!line || *line < 0)
throw RequestError("invalid breakpoint line");
selected.push_back(*line);
returned.push_back(Json{Json::Object{{"verified", Json{true}}, {"line", number(*line)}}});
}
live_breakpoints_[std::string{*path}] = std::move(selected);
response(r, {{"breakpoints", Json{std::move(returned)}}});
}
void Adapter::move_live(const Request &r, bool step) {
auto moved = step ? live_->step() : live_->continue_run();
if (!moved)
throw RequestError(moved.error());
if (step)
response(r);
else
response(r, {{"allThreadsContinued", Json{true}}});
if (*moved) {
live_generation_ = (*moved)->generation;
position_event();
} else {
finish();
}
}
Json Adapter::inspect_live() {
auto snapshot = live_->inspect();
if (!snapshot)
throw RequestError(snapshot.error());
return std::move(*snapshot);
}
std::int64_t Adapter::live_handle(std::size_t frame) const {
return static_cast<std::int64_t>(live_generation_ * 1000 + frame + 1);
}
std::size_t Adapter::live_frame(std::int64_t handle) const {
if (handle <= 0)
throw RequestError("invalid live frame handle");
const auto generation = static_cast<std::uint64_t>(handle) / 1000;
const auto index = static_cast<std::uint64_t>(handle) % 1000;
if (generation != live_generation_ || index == 0)
throw RequestError("stale live frame handle");
return static_cast<std::size_t>(index - 1);
}
void Adapter::live_stack(const Request &r, const Json::Object &args) {
if (argument_number(args, "threadId") != 1)
throw RequestError("unknown live thread");
const auto snapshot = inspect_live();
const auto *snapshot_fields = Protocol::as_object(&snapshot);
const auto *frames = snapshot_fields
? Protocol::as_array(Protocol::find_member(*snapshot_fields, "frames"))
: nullptr;
if (!frames || frames->size() > 256)
throw RequestError("invalid live frame list");
Json::Array stack;
for (std::size_t index = 0; index != frames->size(); ++index) {
const auto *fields = Protocol::as_object(&(*frames)[index]);
if (!fields)
throw RequestError("invalid live frame");
Json::Object frame;
frame.emplace("id", number(live_handle(index)));
frame.emplace("name", text(string_field(*fields, "name").value_or("<unnamed>")));
if (const auto line = integer(*fields, "line"))
frame.emplace("line", number(*line));
if (const auto source = string_field(*fields, "source"))
frame.emplace("source", Json{Json::Object{{"name", text(*source)}}});
stack.push_back(Json{std::move(frame)});
}
response(r, {{"stackFrames", Json{std::move(stack)}},
{"totalFrames", number(static_cast<std::int64_t>(frames->size()))}});
}
void Adapter::live_scopes(const Request &r, const Json::Object &args) {
const auto frame = argument_number(args, "frameId");
static_cast<void>(live_frame(frame));
Json::Array scopes;
scopes.push_back(Json{Json::Object{{"name", text("Compiler state")},
{"variablesReference", number(frame)},
{"expensive", Json{false}}}});
response(r, {{"scopes", Json{std::move(scopes)}}});
}
void Adapter::live_variables(const Request &r, const Json::Object &args) {
const auto handle = argument_number(args, "variablesReference");
const auto index = live_frame(handle);
const auto snapshot = inspect_live();
const auto *snapshot_fields = Protocol::as_object(&snapshot);
const auto *frames = snapshot_fields
? Protocol::as_array(Protocol::find_member(*snapshot_fields, "frames"))
: nullptr;
if (!frames || index >= frames->size())
throw RequestError("unknown live frame");
const auto *fields = Protocol::as_object(&(*frames)[index]);
if (!fields)
throw RequestError("invalid live frame");
Json::Array variables;
for (const auto &[name, value] : *fields) {
if (variables.size() == 64)
break;
std::string rendered;
if (const auto *string = Protocol::as_string(&value))
rendered = *string;
else if (const auto *number_value = std::get_if<std::int64_t>(&value.value))
rendered = std::to_string(*number_value);
else if (const auto flag = Protocol::as_bool(&value))
rendered = *flag ? "true" : "false";
else if (auto encoded = Protocol::serialize_json(value))
rendered = encoded->substr(0, 4096);
else
continue;
if (rendered.size() > 4096)
rendered.resize(4096);
variables.push_back(Json{Json::Object{
{"name", text(name)}, {"value", text(rendered)}, {"variablesReference", number(0)}}});
}
if (const auto *values = Protocol::as_array(Protocol::find_member(*snapshot_fields, "values")))
for (const auto &item : *values) {
if (variables.size() == 64)
break;
const auto *typed = Protocol::as_object(&item);
if (!typed)
continue;
const auto name = string_field(*typed, "name").value_or("value");
const auto rendered = string_field(*typed, "value").value_or("");
variables.push_back(Json{Json::Object{{"name", text(name)},
{"value", text(rendered)},
{"variablesReference", number(0)}}});
}
// Compiler-reported splice origins become read-only reflected-entity
// entries with their provenance chain, never editable text.
const auto origins = splice_origins(*snapshot_fields);
if (!origins.empty()) {
const auto reflected = reflection::snapshot_from_splices(origins);
for (const auto &entity : reflected.entities()) {
if (variables.size() == 64)
break;
const reflection::Origin *declaration{};
const reflection::Origin *splice{};
for (const auto &origin : entity.provenance.origins) {
if (!origin.range)
continue;
if (origin.kind == reflection::OriginKind::reflected_declaration && !declaration)
declaration = &origin;
if (origin.kind == reflection::OriginKind::splice && !splice)
splice = &origin;
}
std::string rendered = "reflected " + entity.name;
const auto append = [&rendered](std::string_view prefix,
const reflection::Range &range) {
rendered += std::string{prefix} + range.path + ":" + std::to_string(range.line) +
":" + std::to_string(range.character);
};
if (declaration)
append(" at ", *declaration->range);
if (splice) {
append(" (splice at ", *splice->range);
rendered += ")";
}
variables.push_back(Json{Json::Object{{"name", text(entity.name)},
{"value", text(rendered)},
{"variablesReference", number(0)}}});
}
}
response(r, {{"variables", Json{std::move(variables)}}});
}
void Adapter::end_pending_launch(std::string_view reason) {
if (!launch_)
return;
const auto pending = std::move(*launch_);
launch_.reset();
failure(pending, reason);
}
void Adapter::invalid_input(std::string_view reason) {
end_pending_launch(reason);
throw std::runtime_error(std::string(reason));
}
Json::Object source_breakpoints(const Json::Object &args) {
if (!Protocol::as_object(Protocol::find_member(args, "source")))
throw RequestError("source breakpoints require a source");
const auto name = args.contains("breakpoints") ? "breakpoints" : "lines";
const auto *requested = Protocol::find_member(args, name);
Json::Array result;
if (requested) {
const auto *entries = Protocol::as_array(requested);
if (!entries || entries->size() > 4096)
throw RequestError("invalid breakpoint list");
for (const auto &entry : *entries) {
constexpr std::int64_t max_coordinate = 9007199254740991;
if (args.contains("breakpoints")) {
const auto *bp = Protocol::as_object(&entry);
if (!bp)
throw RequestError("invalid source breakpoint");
argument_number(*bp, "line", max_coordinate);
if (bp->contains("column"))
argument_number(*bp, "column", max_coordinate);
} else {
const auto *line = std::get_if<std::int64_t>(&entry.value);
if (!line || *line < 0 || *line > max_coordinate)
throw RequestError("invalid breakpoint line");
}
result.push_back(Json{Json::Object{
{"verified", Json{false}},
{"message", text("The recording has no executable source breakpoint locations")}}});
}
}
return {{"breakpoints", Json{std::move(result)}}};
}
void Adapter::dispatch(const Request &r, const Json::Object &args) {
if (r.command == "initialize") {
if (initialized_)
throw RequestError("adapter is already initialized");
if (!string_field(args, "adapterID"))
throw RequestError("initialize requires adapterID");
if (const auto *paging = Protocol::find_member(args, "supportsVariablePaging")) {
const auto supported = Protocol::as_bool(paging);
if (!supported)
throw RequestError("supportsVariablePaging must be a boolean");
variable_paging_ = *supported;
}
initialized_ = true;
response(r, {{"supportsConfigurationDoneRequest", Json{true}},
{"supportsTerminateRequest", Json{true}},
{"supportsLoadedSourcesRequest", Json{true}},
{"supportsDelayedStackTraceLoading", Json{true}}});
event("initialized");
return;
}
if (!initialized_)
throw RequestError("initialize the adapter first");
if (r.command == "disconnect" || r.command == "terminate") {
end_pending_launch("launch ended before configuration completed");
if (live_)
static_cast<void>(live_->cancel());
response(r);
finish();
disconnected_ = r.command == "disconnect";
return;
}
if (r.command == "launch") {
if (live_launch_) {
if (live_ || ended_)
throw RequestError("this adapter accepts one live session");
live_.emplace(live::Options{live_launch_->worker, live_launch_->compiler,
live_launch_->sha256, live_launch_->source,
live_launch_->trace, true});
launch_ = r;
return;
}
if (session_ || ended_)
throw RequestError("this adapter accepts one recording");
if (args.contains("noDebug") &&
Protocol::as_bool(Protocol::find_member(args, "noDebug")) != false)
throw RequestError("replay requires a debug launch");
if (args.contains("trace") && string_field(args, "trace") != selected_.native())
throw RequestError("launch trace differs from the recording selected by the launcher");
auto opened = ReplaySession::open(selected_);
if (!opened)
throw RequestError(opened.error());
session_.emplace(std::move(*opened));
launch_ = r;
begin_if_ready();
return;
}
if (r.command == "configurationDone") {
if (configured_ || ended_)
throw RequestError("configuration is closed");
configured_ = true;
response(r);
if (live_)
begin_live();
else
begin_if_ready();
return;
}
if (r.command == "setBreakpoints" && !ended_ && !live_) {
response(r, source_breakpoints(args));
return;
}
if (r.command == "setExceptionBreakpoints" && !ended_) {
for (const auto *key : {"filters", "filterOptions", "exceptionOptions"}) {
const auto *field = Protocol::find_member(args, key);
if (!field && std::string_view(key) != "filters")
continue;
const auto *list = Protocol::as_array(field);
if (!list || !list->empty())
throw RequestError(
"no exception breakpoint filters are available in this recording");
}
response(r, {{"breakpoints", Json{Json::Array{}}}});
return;
}
if (live_) {
if (r.command == "setBreakpoints") {
live_breakpoints(r, args);
return;
}
if (r.command == "continue" || r.command == "next") {
move_live(r, r.command == "next");
return;
}
if (r.command == "threads") {
Json::Array threads;
threads.push_back(
Json{Json::Object{{"id", number(1)}, {"name", text("Private GCC worker")}}});
response(r, {{"threads", Json{std::move(threads)}}});
return;
}
if (r.command == "stackTrace") {
live_stack(r, args);
return;
}
if (r.command == "scopes") {
live_scopes(r, args);
return;
}
if (r.command == "variables") {
live_variables(r, args);
return;
}
if (r.command == "pause" || r.command == "stepIn" || r.command == "stepOut")
throw RequestError("the private worker supports only next and continue");
throw RequestError("unsupported live request");
}
if (!session_ || !configured_)
throw RequestError("no configured replay session");
if (r.command == "continue" || r.command == "vls/seek") {
if (ended_ || !session_->paused())
throw RequestError("no active replay cursor");
if (r.command == "continue") {
if (argument_number(args, "threadId") != 1)
throw RequestError("unknown replay thread");
if (const auto *context = Protocol::find_member(args, "vlsContext")) {
const auto *fields = Protocol::as_object(context);
if (!fields || !session_->matches(*fields))
throw RequestError("stale or incompatible replay context");
}
auto moved = session_->move_to_value(true);
if (!moved)
throw RequestError(moved.error());
response(r, {{"allThreadsContinued", Json{true}}});
if (!*moved) {
finish();
return;
}
} else {
if (!session_->matches(args))
throw RequestError("stale or incompatible inspection context");
if (args.contains("eventSequence") == args.contains("direction"))
throw RequestError("select one event or value direction");
if (args.contains("eventSequence")) {
auto moved = session_->seek(
static_cast<std::uint32_t>(argument_number(args, "eventSequence")));
if (!moved)
throw RequestError(moved.error());
} else {
const auto direction = string_field(args, "direction");
if (direction != "nextValue" && direction != "previousValue")
throw RequestError("unknown seek direction");
auto moved = session_->move_to_value(direction == "nextValue");
if (!moved)
throw RequestError(moved.error());
if (!*moved)
throw RequestError("no recorded value in that direction");
}
response(r, session_->describe());
}
position_event();
return;
}
response(r, inspect(r.command, args, *session_, variable_paging_));
}
void Adapter::run(std::istream &input, std::ostream &output) {
output_ = &output;
while (!disconnected_) {
auto frame = Protocol::read_frame(input, {.body_bytes = 1024 * 1024});
if (!frame)
invalid_input(frame.error());
if (!*frame) {
end_pending_launch("input closed before configuration completed");
return;
}
auto decoded = Protocol::parse_json(**frame);
const auto *fields = decoded ? Protocol::as_object(&*decoded) : nullptr;
if (!fields)
invalid_input("invalid DAP message");
if (string_field(*fields, "type") != "request")
invalid_input("expected a DAP request");
const auto seq = integer(*fields, "seq");
const auto command = string_field(*fields, "command");
if (!seq || *seq < 1 || *seq > max_seq || !command || command->empty() ||
command->size() > 256)
invalid_input("uncorrelatable DAP request");
const Request request{*seq, std::string(*command)};
if (*seq != received_ + 1) {
// A repeated sequence cannot identify a new request. Never emit two
// responses for the same correlation, even while launch is deferred.
if (*seq > received_)
failure(request, "out-of-order request sequence");
invalid_input("out-of-order DAP request sequence");
}
received_ = *seq;
try {
const auto *arguments = Protocol::find_member(*fields, "arguments");
const auto *args = Protocol::as_object(arguments);
if (arguments && !args)
throw RequestError("arguments must be an object");
static const Json::Object empty;
dispatch(request, args ? *args : empty);
} catch (const RequestError &err) {
failure(request, err.what());
}
}
}
} // namespace
} // namespace vls::debug::dap
int main(int argc, char **argv) {
if (argc == 2 && std::string_view(argv[1]) == "--help") {
std::cout << "Usage: vls-dap --replay ABSOLUTE_TRACE\n"
" vls-dap --live WORKER COMPILER SHA256 SOURCE TRACE\n";
return 0;
}
if (argc == 2 && std::string_view(argv[1]) == "--version") {
std::cout << "vls-dap 0.1.0\n";
return 0;
}
std::optional<vls::debug::dap::LiveLaunch> live;
if (argc == 7 && std::string_view(argv[1]) == "--live") {
const std::string sha{argv[4]};
if (sha.size() != 64 || sha.find_first_not_of("0123456789abcdef") != std::string::npos ||
!std::filesystem::path(argv[2]).is_absolute() ||
!std::filesystem::path(argv[3]).is_absolute() ||
!std::filesystem::path(argv[5]).is_absolute() ||
!std::filesystem::path(argv[6]).is_absolute()) {
std::cerr << "Usage: vls-dap --live WORKER COMPILER SHA256 SOURCE TRACE\n";
return 2;
}
live = vls::debug::dap::LiveLaunch{argv[2], argv[3], argv[5], argv[6], sha};
} else if (argc != 3 || std::string_view(argv[1]) != "--replay" ||
!std::filesystem::path(argv[2]).is_absolute()) {
std::cerr << "Usage: vls-dap --replay ABSOLUTE_TRACE\n";
return 2;
}
std::signal(SIGPIPE, SIG_IGN);
try {
vls::debug::dap::Adapter(argc == 7 ? std::filesystem::path{argv[6]}
: std::filesystem::path{argv[2]},
std::move(live))
.run(std::cin, std::cout);
} catch (const std::exception &err) {
std::cerr << "vls-dap: " << err.what() << '\n';
return 1;
}
return 0;
}
+163
View File
@@ -0,0 +1,163 @@
#include "Projection.hpp"
#include "../Fields.hpp"
#include <algorithm>
#include <charconv>
#include <limits>
namespace vls::debug::dap {
std::int64_t argument_number(const Json::Object &arguments, std::string_view key,
std::int64_t maximum) {
auto n = integer(arguments, key);
if (!n || *n < 0 || *n > maximum)
throw RequestError("invalid integer argument " + std::string(key));
return *n;
}
namespace {
Json captured_source() {
return Json{Json::Object{{"name", text("input.cpp")}, {"sourceReference", number(1)}}};
}
struct Page {
std::size_t start, end;
};
Page dap_page(const Json::Object &args, std::string_view start_key, std::string_view count_key,
std::size_t total) {
constexpr auto max_index = std::numeric_limits<std::uint32_t>::max();
const auto start = args.contains(start_key) ? argument_number(args, start_key, max_index) : 0;
const auto count = args.contains(count_key) ? argument_number(args, count_key, max_index) : 0;
const auto first = std::min(total, static_cast<std::size_t>(start));
return {first,
count ? first + std::min(total - first, static_cast<std::size_t>(count)) : total};
}
std::string integer_value(const Json::Object &value) {
const auto width = integer(value, "precision");
const auto bits = string_field(value, "bitsHex");
const auto is_signed = Protocol::as_bool(Protocol::find_member(value, "signed"));
if (!width || *width < 1 || *width > 64 || !bits || !is_signed)
throw RequestError("invalid recorded integer");
std::uint64_t word{};
const auto [end, error] = std::from_chars(bits->data(), bits->data() + bits->size(), word, 16);
if (error != std::errc{} || end != bits->data() + bits->size())
throw RequestError("invalid recorded bits");
const auto sign = std::uint64_t{1} << (*width - 1);
if (*is_signed && (word & sign)) {
const auto mask = *width == 64 ? ~std::uint64_t{} : (sign << 1) - 1;
return "-" + std::to_string((~word & mask) + 1);
}
return std::to_string(word);
}
Json variable(std::string_view name, std::string_view value) {
return Json{Json::Object{
{"name", text(name)}, {"value", text(value)}, {"variablesReference", number(0)}}};
}
Json::Array frame_variables(const Json::Object &fields) {
Json::Array result;
const auto *value = Protocol::as_object(Protocol::find_member(fields, "value"));
if (value && string_field(*value, "kind") == "integer") {
result.push_back(variable("Result", integer_value(*value)));
result.push_back(variable("Bits", *string_field(*value, "bitsHex")));
result.push_back(variable("Precision", std::to_string(*integer(*value, "precision"))));
result.push_back(variable(
"Signed",
*Protocol::as_bool(Protocol::find_member(*value, "signed")) ? "true" : "false"));
} else if (value) {
result.push_back(
variable("Result", string_field(*value, "reason").value_or("unavailable")));
}
if (const auto provisional =
Protocol::as_bool(Protocol::find_member(fields, "valueProvisional")))
result.push_back(variable("Provisional", *provisional ? "true" : "false"));
if (const auto outcome = string_field(fields, "outcome"))
result.push_back(variable("Outcome", *outcome));
if (Protocol::as_bool(Protocol::find_member(fields, "cached")).value_or(false))
result.push_back(variable("Cached", "true"));
return result;
}
} // namespace
Json::Object inspect(std::string_view command, const Json::Object &args,
const ReplaySession &session, bool variable_paging) {
if (command == "vls/session")
return session.describe();
if (command == "vls/timeline" || command == "vls/frames") {
if (!session.matches(args))
throw RequestError("stale or incompatible inspection context");
const auto start = argument_number(args, "start");
const auto count = argument_number(args, "count");
auto page = command == "vls/timeline" ? session.timeline(start, count)
: session.frames(start, count);
if (!page)
throw RequestError(page.error());
return std::move(*page);
}
if (command == "loadedSources") {
Json::Array sources;
if (session.source_available())
sources.push_back(captured_source());
return {{"sources", Json{std::move(sources)}}};
}
if (command == "source") {
if (!session.source_available() || argument_number(args, "sourceReference") != 1)
throw RequestError("unknown captured source");
if (const auto *source = Protocol::find_member(args, "source")) {
const auto *fields = Protocol::as_object(source);
if (!fields ||
(fields->contains("sourceReference") && integer(*fields, "sourceReference") != 1))
throw RequestError("conflicting captured source reference");
}
return {{"content", text(session.source_bytes())}, {"mimeType", text("text/x-c++src")}};
}
if (!session.paused())
throw RequestError("no active replay cursor");
if (command == "threads")
return {{"threads", Json{Json::Array{Json{Json::Object{
{"id", number(1)}, {"name", text("C++ constant evaluation")}}}}}}};
if (command == "stackTrace") {
if (argument_number(args, "threadId") != 1)
throw RequestError("unknown replay thread");
auto [start, end] = dap_page(args, "startFrame", "levels", session.frame_count());
Json::Array frames;
for (auto i = start; i < end; ++i) {
const auto &fields = std::get<Json::Object>(session.frame(i).value);
frames.push_back(Json{
Json::Object{{"id", number(session.frame_handle(i))},
{"name", text(string_field(fields, "name").value_or("<unnamed>"))},
{"line", number(0)},
{"column", number(0)}}});
}
return {{"stackFrames", Json{std::move(frames)}},
{"totalFrames", number(session.frame_count())}};
}
if (command == "scopes") {
auto index = session.handle_index(argument_number(args, "frameId"), false);
if (!index)
throw RequestError("expired or unknown frame");
Json::Object scope{{"name", text("Constant evaluation")},
{"variablesReference", number(session.scope_handle(*index))},
{"expensive", Json{false}}};
return {{"scopes", Json{Json::Array{Json{std::move(scope)}}}}};
}
if (command == "variables") {
auto index = session.handle_index(argument_number(args, "variablesReference"), true);
if (!index)
throw RequestError("expired or unknown variables reference");
const auto filter = string_field(args, "filter");
if (args.contains("filter") && filter != "named" && filter != "indexed")
throw RequestError("unknown variable filter");
auto vars = filter == "indexed"
? Json::Array{}
: frame_variables(std::get<Json::Object>(session.frame(*index).value));
if (!variable_paging)
return {{"variables", Json{std::move(vars)}}};
const auto [start, end] = dap_page(args, "start", "count", vars.size());
return {{"variables", Json{Json::Array(vars.begin() + start, vars.begin() + end)}}};
}
throw RequestError("unsupported replay request");
}
} // namespace vls::debug::dap
+17
View File
@@ -0,0 +1,17 @@
#pragma once
#include <vls/debug/inspection/ReplaySession.hpp>
#include <limits>
#include <stdexcept>
namespace vls::debug::dap {
// Errors with a request sequence can be reported to the client and leave the session usable.
struct RequestError : std::runtime_error {
using std::runtime_error::runtime_error;
};
std::int64_t argument_number(const Json::Object &, std::string_view key,
std::int64_t maximum = std::numeric_limits<std::int32_t>::max());
Json::Object inspect(std::string_view command, const Json::Object &arguments,
const ReplaySession &session, bool variable_paging);
} // namespace vls::debug::dap
+215
View File
@@ -0,0 +1,215 @@
#include <vls/debug/inspection/ReplaySession.hpp>
#include "../Fields.hpp"
#include "Trace.hpp"
#include <Void/Unicode/Utf.hpp>
#include <algorithm>
#include <array>
#include <cerrno>
#include <limits>
#include <sys/random.h>
namespace vls::debug {
namespace {
std::expected<std::string, std::string> session_id() {
std::array<unsigned char, 16> bytes{};
for (std::size_t used = 0; used < bytes.size();) {
const auto n = ::getrandom(bytes.data() + used, bytes.size() - used, 0);
if (n < 0 && errno == EINTR)
continue;
if (n <= 0)
return std::unexpected{"could not allocate a debug session identity"};
used += static_cast<std::size_t>(n);
}
constexpr std::string_view hex = "0123456789abcdef";
std::string id;
for (auto byte : bytes) {
id += hex[byte >> 4];
id += hex[byte & 15];
}
return id;
}
} // namespace
ReplaySession::ReplaySession(std::shared_ptr<const gcc::ReplayRecording> recording, std::string id)
: recording_(std::move(recording)), id_(std::move(id)),
source_available_(Void::Unicode::validate_utf8(recording_->source_bytes()).has_value()) {}
std::expected<ReplaySession, std::string> ReplaySession::open(const std::filesystem::path &path) {
auto recording = gcc::ReplayRecording::open(path);
if (!recording)
return std::unexpected{std::move(recording.error())};
auto id = session_id();
if (!id)
return std::unexpected{std::move(id.error())};
return ReplaySession(std::move(*recording), std::move(*id));
}
Json::Object ReplaySession::identity() const {
return {{"schemaVersion", number(1)},
{"sessionId", text(id_)},
{"generation", number(generation_)}};
}
bool ReplaySession::matches(const Json::Object &arguments) const {
return integer(arguments, "schemaVersion") == 1 &&
string_field(arguments, "sessionId") == id_ &&
integer(arguments, "generation") == generation_;
}
Json::Object ReplaySession::describe() const {
auto result = identity();
const auto meta = recording_->metadata();
Json::Object record{{"partial", Json{meta.partial}},
{"corrupt", Json{meta.corrupt}},
{"eventCount", number(recording_->event_count())},
{"outcome", meta.outcome ? text(*meta.outcome) : Json{nullptr}},
{"exitCode", meta.exit_code ? number(*meta.exit_code) : Json{nullptr}}};
if (meta.journal_error)
record.emplace("journalError", text(*meta.journal_error));
result.emplace("recording", Json{std::move(record)});
result.emplace("mode", text("replay"));
result.emplace("backend", text(meta.backend));
result.emplace("compilerPid", number(meta.pid));
result.emplace("compilerSha256", text(meta.compiler_sha256));
result.emplace("sourceSha256", text(meta.source_sha256));
result.emplace("sourceByteLength", number(source_bytes().size()));
result.emplace("sourceAvailable", Json{source_available_});
if (source_available_)
result.emplace("sourceReference", number(1));
result.emplace("eventSequence", sequence_ ? number(*sequence_) : Json{nullptr});
result.emplace("pauseKind", text(pause_kind_));
return result;
}
std::string_view ReplaySession::source_bytes() const { return recording_->source_bytes(); }
std::size_t ReplaySession::frame_count() const {
if (!paused())
return 0;
return std::get<Json::Array>(std::get<Json::Object>(cursor_.value).at("frames").value).size();
}
const Json &ReplaySession::frame(std::size_t index) const {
const auto &frames =
std::get<Json::Array>(std::get<Json::Object>(cursor_.value).at("frames").value);
return frames.at(frames.size() - 1 - index);
}
std::int64_t ReplaySession::frame_handle(std::size_t index) const {
return frame_base_ + static_cast<std::int64_t>(index);
}
std::int64_t ReplaySession::scope_handle(std::size_t index) const {
return frame_handle(index) + static_cast<std::int64_t>(frame_count());
}
std::optional<std::size_t> ReplaySession::handle_index(std::int64_t handle, bool scope) const {
const auto base = scope ? scope_handle(0) : frame_base_;
if (handle < base || handle >= base + static_cast<std::int64_t>(frame_count()))
return {};
return static_cast<std::size_t>(handle - base);
}
std::expected<void, std::string> ReplaySession::seek(std::uint32_t sequence) {
if (finished_)
return std::unexpected{"replay session has terminated"};
auto page = recording_->event_page(sequence, 1);
if (!page || page->empty())
return std::unexpected{"event is outside the verified prefix"};
auto cursor = recording_->cursor_at(sequence);
if (!cursor)
return std::unexpected{std::move(cursor.error())};
const auto *frames =
Protocol::as_array(Protocol::find_member(std::get<Json::Object>(cursor->value), "frames"));
const auto handles = 2 * static_cast<std::int64_t>(frames->size());
if (next_handle_ + handles - 1 > std::numeric_limits<std::int32_t>::max())
return std::unexpected{"debug handle limit reached"};
const auto kind = page->front().kind;
pause_kind_ = kind == "stopped" ? "recordedStop" : kind == "value" ? "value" : "event";
sequence_ = sequence;
cursor_ = std::move(*cursor);
++generation_;
frame_base_ = next_handle_;
next_handle_ += handles;
return {};
}
std::expected<bool, std::string> ReplaySession::initial_position() {
auto first = move_to_value(true);
if (!first || *first || !recording_->event_count())
return first;
// A compiler can stop producing events before its first integral return. Its
// last verified event still owns an inspectable stack and earlier history.
auto cursor = seek(static_cast<std::uint32_t>(recording_->event_count() - 1));
if (!cursor)
return std::unexpected{std::move(cursor.error())};
return true;
}
std::expected<bool, std::string> ReplaySession::move_to_value(bool forward) {
if (finished_)
return std::unexpected{"replay session has terminated"};
auto point =
forward ? recording_->next_value(sequence_) : recording_->previous_value(sequence_);
if (!point)
return std::unexpected{std::move(point.error())};
if (!point->has_value())
return false;
auto moved = seek((*point)->stop_sequence.value_or((*point)->value_sequence));
if (!moved)
return std::unexpected{std::move(moved.error())};
return true;
}
void ReplaySession::finish() {
if (finished_)
return;
finished_ = true;
++generation_;
sequence_.reset();
cursor_ = Json{nullptr};
pause_kind_ = "none";
}
std::expected<Json::Object, std::string> ReplaySession::timeline(std::size_t start,
std::size_t count) const {
auto page = recording_->event_page(start, count);
if (!page)
return std::unexpected{std::move(page.error())};
Json::Array events;
for (const auto &entry : *page) {
Json::Object fields{{"sequence", number(entry.sequence)}, {"kind", text(entry.kind)}};
if (entry.frame)
fields.emplace("frame", number(*entry.frame));
if (entry.parent)
fields.emplace("parent", number(*entry.parent));
if (entry.acknowledged_stop) {
fields.emplace("acknowledgedStop", number(*entry.acknowledged_stop));
fields.emplace("acknowledgedAction", text(*entry.acknowledged_action));
}
events.push_back(Json{std::move(fields)});
}
auto body = identity();
body.emplace("total", number(recording_->event_count()));
body.emplace("events", Json{std::move(events)});
return body;
}
std::expected<Json::Object, std::string> ReplaySession::frames(std::size_t start,
std::size_t count) const {
if (!paused() || start > frame_count() || count > gcc::ReplayRecording::max_page_size)
return std::unexpected{"frame page is unavailable"};
Json::Array frames;
const auto end = start + std::min(count, frame_count() - start);
for (auto i = start; i < end; ++i)
frames.push_back(frame(i));
auto result = identity();
result.emplace("total", number(frame_count()));
result.emplace("frames", Json{std::move(frames)});
const auto &cursor = std::get<Json::Object>(cursor_.value);
for (const auto *key : {"lastLeave", "stop", "pendingAction", "frontendEnded", "terminal"})
result.emplace(key, cursor.at(key));
return result;
}
} // namespace vls::debug
+327
View File
@@ -0,0 +1,327 @@
#include <vls/debug/live/LiveSession.hpp>
#include <Void/System/Process.hpp>
#include <algorithm>
#include <cerrno>
#include <chrono>
#include <limits>
#include <poll.h>
#include <stdexcept>
#include <string_view>
#include <unistd.h>
namespace vls::debug::live {
namespace P = Void::LanguageServer::Protocol;
using Json = P::Json;
using Clock = std::chrono::steady_clock;
using namespace std::chrono_literals;
namespace {
constexpr std::size_t max_stderr_bytes = 256 * 1024;
constexpr std::size_t max_buffer_bytes = 256 * 1024;
bool write_bounded(int fd, std::string_view bytes) {
const auto deadline = Clock::now() + 2s;
while (!bytes.empty() && Clock::now() < deadline) {
const auto written = ::write(fd, bytes.data(), bytes.size());
if (written > 0) {
bytes.remove_prefix(static_cast<std::size_t>(written));
continue;
}
if (written < 0 && errno == EINTR)
continue;
if (written < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
pollfd pipe{fd, POLLOUT, 0};
if (::poll(&pipe, 1, 10) < 0 && errno != EINTR)
return false;
continue;
}
return false;
}
return bytes.empty();
}
const Json *member(const Json &value, std::string_view key) {
const auto *object = P::as_object(&value);
return object ? P::find_member(*object, key) : nullptr;
}
std::optional<std::int64_t> integer(const Json *value) {
if (!value)
return std::nullopt;
if (const auto *number = std::get_if<std::int64_t>(&value->value))
return *number;
return std::nullopt;
}
} // namespace
struct LiveSession::State_ {
explicit State_(Options value) : options(std::move(value)) {}
Options options;
Void::Process::Child child;
std::string buffer, errors, nonce, outcome, reason;
State state{State::idle};
std::optional<Stop> current;
std::uint64_t generation{};
bool child_running{true};
Clock::time_point deadline{};
struct Notice {
std::string kind;
std::optional<std::uint32_t> stop;
std::optional<Json> snapshot;
std::string outcome, reason;
};
bool reap() {
if (!child_running)
return true;
auto waited = child.try_wait();
if (!waited)
return false;
if (!*waited)
return true;
child_running = false;
return true;
}
// Reads one complete notice line within the deadline.
std::expected<Notice, std::string> next_notice() {
while (true) {
const auto newline = buffer.find('\n');
if (newline != std::string::npos) {
const auto line = buffer.substr(0, newline);
buffer.erase(0, newline + 1);
if (line.empty())
continue;
if (line.size() > options.max_notice_bytes)
return std::unexpected("worker notice exceeds its bound");
auto parsed = P::parse_json(line, 8);
if (!parsed)
return std::unexpected("worker notice is not valid JSON");
const auto *kind = P::as_string(member(*parsed, "kind"));
if (!kind)
return std::unexpected("worker notice lacks a kind");
Notice notice{.kind = *kind};
if (*kind == "started" || *kind == "stopped") {
const auto *nonce = P::as_string(member(*parsed, "nonce"));
if (!nonce || nonce->size() != 32)
return std::unexpected("worker notice has an invalid nonce");
this->nonce = *nonce;
}
if (*kind == "stopped") {
const auto sequence = integer(member(*parsed, "stop"));
if (!sequence || *sequence < 1 ||
*sequence > std::numeric_limits<std::uint32_t>::max())
return std::unexpected("worker stop is invalid");
notice.stop = static_cast<std::uint32_t>(*sequence);
} else if (*kind == "inspection") {
const auto *snapshot = member(*parsed, "snapshot");
if (!snapshot)
return std::unexpected("inspection notice lacks a snapshot");
auto encoded = P::serialize_json(*snapshot);
if (!encoded || encoded->size() > options.max_notice_bytes)
return std::unexpected("inspection snapshot exceeds its bound");
notice.snapshot = *snapshot;
} else if (*kind == "inspectionLimit") {
return std::unexpected("inspection snapshot exceeds the worker limit");
} else if (*kind == "finished") {
const auto *outcome = P::as_string(member(*parsed, "outcome"));
const auto *reason = P::as_string(member(*parsed, "reason"));
if (!outcome || !reason || reason->size() > 1024)
return std::unexpected("worker completion notice is invalid");
notice.outcome = *outcome;
notice.reason = *reason;
} else if (*kind == "rejected") {
return std::unexpected("the worker rejected the command");
}
return notice;
}
if (Clock::now() >= deadline)
return std::unexpected("worker notice deadline expired");
pollfd pipes[]{{child.stdout_fd(), POLLIN, 0}, {child.stderr_fd(), POLLIN, 0}};
const auto remaining =
std::chrono::duration_cast<std::chrono::milliseconds>(deadline - Clock::now());
const int count = ::poll(pipes, 2,
static_cast<int>(std::max<std::int64_t>(
1, std::min<std::int64_t>(remaining.count(), 50))));
if (count < 0 && errno != EINTR)
return std::unexpected("cannot poll the worker");
if (count <= 0)
continue;
if (pipes[0].revents != 0) {
char bytes[8192];
const auto read = ::read(child.stdout_fd(), bytes, sizeof bytes);
if (read == 0) {
reap();
return std::unexpected("worker closed its output");
}
if (read < 0 && errno != EAGAIN && errno != EINTR)
return std::unexpected("cannot read the worker output");
if (read > 0) {
buffer.append(bytes, static_cast<std::size_t>(read));
if (buffer.size() > max_buffer_bytes)
return std::unexpected("worker output exceeds its bound");
}
}
if (pipes[1].revents != 0) {
char bytes[8192];
const auto read = ::read(child.stderr_fd(), bytes, sizeof bytes);
if (read > 0 && errors.size() < max_stderr_bytes)
errors.append(bytes, std::min<std::size_t>(static_cast<std::size_t>(read),
max_stderr_bytes - errors.size()));
}
}
}
bool send(std::string_view action) {
if (nonce.size() != 32 || !current)
return false;
const std::string line =
nonce + " " + std::to_string(current->sequence) + " " + std::string{action} + "\n";
return write_bounded(child.stdin_fd(), line);
}
std::expected<std::optional<Stop>, std::string> move(std::string_view action) {
if (state != State::stopped || !current)
return std::unexpected("the session is not stopped");
deadline = Clock::now() + options.deadline;
if (!send(action))
return std::unexpected("cannot send the control command");
state = State::running;
while (true) {
auto notice = next_notice();
if (!notice)
return std::unexpected(notice.error());
if (notice->kind == "stopped") {
current = Stop{++generation, *notice->stop};
state = State::stopped;
return current;
}
if (notice->kind == "finished") {
finish(notice->outcome, notice->reason);
return std::optional<Stop>{};
}
}
}
void finish(std::string_view result, std::string_view detail) {
outcome = std::string{result};
reason = std::string{detail};
current.reset();
state = result == "completed" ? State::completed
: result == "cancelled" ? State::cancelled
: State::failed;
}
};
LiveSession::LiveSession(Options options) : state_(std::make_unique<State_>(std::move(options))) {}
LiveSession::~LiveSession() {
if (state_->state == State::running || state_->state == State::stopped) {
static_cast<void>(state_->reap());
if (!state_->child_running)
return;
if (state_->current)
state_->send("cancel");
else
write_bounded(state_->child.stdin_fd(), state_->nonce + " cancel\n");
state_->child.terminate(100ms);
}
}
std::expected<Stop, std::string> LiveSession::start() {
auto &state = *state_;
if (state.state != State::idle)
return std::unexpected("the session already started");
state.state = State::running;
state.deadline = Clock::now() + state.options.deadline;
Void::Process::SpawnOptions spawn;
spawn.executable = state.options.worker;
spawn.arguments = {"run", state.options.compiler.native(), state.options.compiler_sha256,
state.options.source.native(), state.options.trace.native()};
if (state.options.stepping)
spawn.arguments.push_back("--step");
spawn.working_directory = state.options.trace.parent_path();
spawn.search_path = false;
auto child = Void::Process::spawn(spawn);
if (!child)
return std::unexpected("could not start the private GCC worker: " +
child.error().message());
state.child = std::move(*child);
while (true) {
auto notice = state.next_notice();
if (!notice)
return std::unexpected(notice.error());
if (notice->kind == "stopped") {
state.current = Stop{++state.generation, *notice->stop};
state.state = State::stopped;
return *state.current;
}
if (notice->kind == "finished") {
state.finish(notice->outcome, notice->reason);
return std::unexpected("the session finished before its first stop: " + state.reason);
}
}
}
std::expected<std::optional<Stop>, std::string> LiveSession::step() { return state_->move("step"); }
std::expected<std::optional<Stop>, std::string> LiveSession::continue_run() {
return state_->move("continue");
}
std::expected<void, std::string> LiveSession::cancel() {
auto &state = *state_;
if (state.state == State::completed || state.state == State::failed ||
state.state == State::cancelled)
return {};
if (state.state == State::idle)
return std::unexpected("the session did not start");
state.deadline = Clock::now() + state.options.deadline;
if (state.current)
state.send("cancel");
else
write_bounded(state.child.stdin_fd(), state.nonce + " cancel\n");
state.state = State::running;
while (true) {
auto notice = state.next_notice();
if (!notice)
return std::unexpected(notice.error());
if (notice->kind == "finished") {
state.finish(notice->outcome, notice->reason);
if (state.state == State::cancelled)
return {};
return std::unexpected("the worker finished as " + state.outcome + ": " + state.reason);
}
}
}
std::expected<Json, std::string> LiveSession::inspect() {
auto &state = *state_;
if (state.state != State::stopped || !state.current)
return std::unexpected("the session is not stopped");
state.deadline = Clock::now() + state.options.deadline;
if (!state.send("inspect"))
return std::unexpected("cannot send the inspection command");
while (true) {
auto notice = state.next_notice();
if (!notice)
return std::unexpected(notice.error());
if (notice->kind == "inspection")
return *notice->snapshot;
if (notice->kind == "finished") {
state.finish(notice->outcome, notice->reason);
return std::unexpected("the session finished during inspection: " + state.reason);
}
}
}
State LiveSession::state() const { return state_->state; }
std::optional<Stop> LiveSession::stop() const { return state_->current; }
std::string LiveSession::outcome() const { return state_->outcome; }
std::string LiveSession::reason() const { return state_->reason; }
} // namespace vls::debug::live
+135
View File
@@ -0,0 +1,135 @@
#include <vls/features/Completion.hpp>
#include <algorithm>
#include <ranges>
#include <set>
#include <tuple>
#include <utility>
namespace vls::features::completion {
namespace {
bool identifier(char ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') ||
ch == '_';
}
int priority(Kind kind) {
switch (kind) {
case Kind::type:
return 0;
case Kind::function:
return 1;
case Kind::field:
return 2;
case Kind::variable:
return 3;
case Kind::namespace_:
return 4;
case Kind::module:
return 5;
case Kind::keyword:
return 6;
case Kind::unknown:
return 7;
}
return 7;
}
std::string bounded(std::string value, std::size_t limit) {
if (value.size() > limit)
value.resize(limit);
return value;
}
} // namespace
std::string_view prefix_at(std::string_view text, std::size_t offset) {
if (offset > text.size())
return {};
std::size_t start = offset;
while (start > 0 && identifier(text[start - 1]))
--start;
const auto prefix = text.substr(start, offset - start);
if (prefix.empty() || (prefix.front() >= '0' && prefix.front() <= '9'))
return {};
return prefix;
}
Result complete(std::span<const Candidate> candidates, std::string_view text, std::size_t offset,
const Limits &limits) {
Result result;
const auto prefix = prefix_at(text, offset);
const std::size_t start = offset - prefix.size();
std::set<std::pair<std::string, Kind>> seen;
std::vector<Item> items;
for (const auto &candidate : candidates) {
if (candidate.label.empty() || candidate.label.size() > limits.labelBytes ||
!candidate.label.starts_with(prefix))
continue;
if (!seen.emplace(candidate.label, candidate.kind).second)
continue;
items.push_back(
Item{.label = candidate.label,
.kind = candidate.kind,
.detail = bounded(candidate.detail, limits.detailBytes),
.provenance = bounded(candidate.provenance, limits.provenanceBytes),
.sort_text = std::to_string(priority(candidate.kind)) + candidate.label,
.identity = candidate.identity,
.replacement_start = start,
.replacement_end = offset});
}
std::ranges::sort(items, [](const Item &left, const Item &right) {
return std::tie(left.sort_text, left.label) < std::tie(right.sort_text, right.label);
});
if (items.size() > limits.candidates)
items.resize(limits.candidates);
result.items = std::move(items);
return result;
}
Resolved resolve(const Identity &identity, std::uint64_t captured_generation,
std::uint64_t current_generation, std::span<const Detail> current,
const Limits &limits) {
Resolved result;
if (captured_generation != current_generation) {
result.status = Resolved::Status::stale;
return result;
}
const auto found = std::ranges::find_if(
current, [&identity](const Detail &entry) { return entry.identity == identity; });
if (found == current.end()) {
result.status = Resolved::Status::unknown;
return result;
}
result.status = Resolved::Status::resolved;
result.detail = bounded(found->detail, limits.detailBytes);
// A fence longer than any backtick run in the content cannot be closed by it.
std::size_t longest{};
std::size_t run{};
for (const char ch : found->detail) {
run = ch == '`' ? run + 1 : 0;
longest = std::max(longest, run);
}
const std::string fence(std::max<std::size_t>(3, longest + 1), '`');
const std::string head = fence + "text\n";
const std::string closing = "\n" + fence + "\n";
// The closing fence is always kept: a truncated value must never leave an
// open fence that lets content escape into the editor's Markdown.
const std::size_t fixed = head.size() + closing.size();
const std::size_t budget =
limits.detailBytes > fixed ? limits.detailBytes - fixed : std::size_t{};
std::string documentation = head + result.detail.substr(0, budget) + closing;
const auto append = [&](std::string piece) {
if (documentation.size() + piece.size() <= limits.detailBytes)
documentation += std::move(piece);
};
if (!found->provenance.empty())
append("\nProvenance: " + bounded(found->provenance, limits.provenanceBytes) + "\n");
append("\nLocation: `" + bounded(found->identity.path, limits.detailBytes) + ":" +
std::to_string(found->identity.line) + ":" + std::to_string(found->identity.character) +
"`\n");
result.documentation = std::move(documentation);
return result;
}
} // namespace vls::features::completion
+74
View File
@@ -0,0 +1,74 @@
#include <vls/features/IndexNavigation.hpp>
#include <algorithm>
#include <set>
#include <tuple>
#include <utility>
namespace vls::features {
namespace {
using Key = std::tuple<navigation::Binding, std::string, navigation::Range>;
navigation::Location location(const index::Location &value) {
return {value.path, {value.line, value.character, value.endLine, value.endCharacter}};
}
navigation::Range range(const index::Location &value) {
return {{value.line, value.character}, {value.endLine, value.endCharacter}};
}
const IndexedSource *source_of(std::span<const IndexedSource> sources, std::string_view path) {
const auto found = std::ranges::find_if(
sources, [path](const IndexedSource &source) { return source.path == path; });
return found == sources.end() ? nullptr : &*found;
}
} // namespace
std::size_t ingest_index_facts(navigation::FactSet &set, const index::Generation &generation,
std::span<const IndexedSource> sources, std::size_t limit) {
std::set<std::string> known_contexts;
for (const auto &context : set.contexts)
known_contexts.insert(context.context);
for (const auto &[name, coverage] : generation.contexts())
if (!known_contexts.contains(name))
set.contexts.push_back(
{name, coverage.complete, coverage.complete ? "" : "index coverage incomplete"});
std::set<Key> present;
for (const auto &fact : set.facts)
present.emplace(fact.binding, fact.source, fact.use);
std::size_t added{};
for (const auto &record : generation.symbols()) {
if (added >= limit)
break;
navigation::Binding binding;
binding.name = record.name;
if (record.definition)
binding.definition = location(*record.definition);
std::vector<const index::Location *> uses{&record.location};
for (const auto &reference : record.references)
uses.push_back(&reference);
for (const auto *use : uses) {
if (added >= limit)
break;
const auto *source = source_of(sources, use->path);
navigation::Fact fact;
fact.binding = binding;
fact.context = "symbol-index";
fact.source = use->path;
fact.content = source ? source->content : std::string{};
fact.use = range(*use);
fact.editable = source != nullptr && source->editable && !fact.content.empty();
fact.provenance =
record.provenance.empty() ? std::string{"symbol-index"} : record.provenance;
if (!present.emplace(fact.binding, fact.source, fact.use).second)
continue;
set.facts.push_back(std::move(fact));
++added;
}
}
return added;
}
} // namespace vls::features
+258
View File
@@ -0,0 +1,258 @@
#include <vls/features/SignatureHelp.hpp>
#include <algorithm>
#include <utility>
namespace vls::features::signature {
namespace {
bool word(char ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') ||
ch == '_' || ch == ':';
}
// Opens an angle bracket only where a template argument list plausibly starts:
// after a name, '>' or ':' and not before '=' or '<' (operators).
bool opens_angle(std::string_view text, std::size_t index) {
if (index == 0 || index + 1 >= text.size())
return false;
const char previous = text[index - 1];
const char next = text[index + 1];
return (word(previous) || previous == '>' || previous == '*') && next != '=' && next != '<';
}
std::string bounded(std::string value, std::size_t limit) {
if (value.size() > limit)
value.resize(limit);
return value;
}
std::string trim(std::string_view text) {
const auto first = text.find_first_not_of(" \t\r\n");
if (first == std::string_view::npos)
return {};
const auto last = text.find_last_not_of(" \t\r\n");
return std::string{text.substr(first, last - first + 1)};
}
} // namespace
Signature parse(std::string_view signature, const Limits &limits) {
Signature result;
result.label = bounded(std::string{signature}, limits.labelBytes);
const auto open = signature.find('(');
if (open == std::string_view::npos)
return result;
const auto close = signature.find_last_of(')');
if (close == std::string_view::npos || close < open)
return result;
const auto list = signature.substr(open + 1, close - open - 1);
if (trim(list).empty())
return result;
int paren{}, square{}, brace{}, angle{};
std::size_t start{};
const auto emit = [&](std::size_t end) {
const auto piece = list.substr(start, end - start);
const auto cleaned = trim(piece);
if (cleaned.empty())
return;
const auto first = piece.find(cleaned.front());
Parameter parameter;
parameter.label = bounded(cleaned, limits.parameterBytes);
if (first != std::string_view::npos && first < limits.labelBytes) {
const auto begin = static_cast<std::uint32_t>(open + 1 + start + first);
parameter.range =
std::pair{begin, static_cast<std::uint32_t>(std::min<std::size_t>(
begin + parameter.label.size(), limits.labelBytes))};
}
if (result.parameters.size() < limits.parameters)
result.parameters.push_back(std::move(parameter));
};
for (std::size_t index = 0; index != list.size(); ++index) {
const char ch = list[index];
switch (ch) {
case '(':
++paren;
break;
case ')':
paren = std::max(0, paren - 1);
break;
case '[':
++square;
break;
case ']':
square = std::max(0, square - 1);
break;
case '{':
++brace;
break;
case '}':
brace = std::max(0, brace - 1);
break;
case '<':
if (opens_angle(list, index))
++angle;
break;
case '>':
angle = std::max(0, angle - 1);
break;
case ',':
if (paren == 0 && square == 0 && brace == 0 && angle == 0) {
emit(index);
start = index + 1;
}
break;
default:
break;
}
}
emit(list.size());
return result;
}
std::uint32_t active_parameter(std::string_view text, std::size_t offset, const Limits &limits) {
if (offset > text.size())
offset = text.size();
const std::size_t lower = offset > limits.scanBytes ? offset - limits.scanBytes : 0;
std::size_t open{};
bool found{};
int depth{};
for (std::size_t index = offset; index > lower; --index) {
const char ch = text[index - 1];
if (ch == ')')
++depth;
else if (ch == '(') {
if (depth == 0) {
open = index - 1;
found = true;
break;
}
--depth;
}
}
if (!found)
return 0;
std::uint32_t commas{};
int paren{}, square{}, brace{};
char quote{'\0'};
bool line_comment{};
bool block_comment{};
for (std::size_t index = open + 1; index < offset && index < open + 1 + limits.scanBytes;
++index) {
const char ch = text[index];
const char next = index + 1 < offset ? text[index + 1] : '\0';
if (line_comment) {
if (ch == '\n')
line_comment = false;
continue;
}
if (block_comment) {
if (ch == '*' && next == '/') {
block_comment = false;
++index;
}
continue;
}
if (quote != '\0') {
if (ch == '\\')
++index;
else if (ch == quote)
quote = '\0';
continue;
}
if (ch == '/' && next == '/') {
line_comment = true;
++index;
} else if (ch == '/' && next == '*') {
block_comment = true;
++index;
} else if (ch == '"' || ch == '\'') {
quote = ch;
} else if (ch == '(') {
++paren;
} else if (ch == ')') {
paren = std::max(0, paren - 1);
} else if (ch == '[') {
++square;
} else if (ch == ']') {
square = std::max(0, square - 1);
} else if (ch == '{') {
++brace;
} else if (ch == '}') {
brace = std::max(0, brace - 1);
} else if (ch == ',' && paren == 0 && square == 0 && brace == 0) {
++commas;
}
}
return commas;
}
bool in_call(std::string_view text, std::size_t use_start, std::size_t use_end, std::size_t offset,
const Limits &limits) {
if (offset > text.size() || use_end > offset || use_start > use_end)
return false;
const auto open = text.find('(', use_end);
if (open == std::string_view::npos || open >= offset)
return false;
const auto stop = std::min({text.size(), offset, open + 1 + limits.scanBytes});
int depth{};
char quote{'\0'};
bool line_comment{};
bool block_comment{};
for (std::size_t index = open; index < stop; ++index) {
const char ch = text[index];
const char next = index + 1 < stop ? text[index + 1] : '\0';
if (line_comment) {
if (ch == '\n')
line_comment = false;
continue;
}
if (block_comment) {
if (ch == '*' && next == '/') {
block_comment = false;
++index;
}
continue;
}
if (quote != '\0') {
if (ch == '\\')
++index;
else if (ch == quote)
quote = '\0';
continue;
}
if (ch == '/' && next == '/') {
line_comment = true;
++index;
} else if (ch == '/' && next == '*') {
block_comment = true;
++index;
} else if (ch == '"' || ch == '\'') {
quote = ch;
} else if (ch == '(') {
++depth;
} else if (ch == ')') {
if (--depth == 0)
return false;
}
}
return depth > 0;
}
Result build(std::span<const std::string> signatures, std::string_view text, std::size_t offset,
const Limits &limits) {
Result result;
for (const auto &candidate : signatures) {
if (result.signatures.size() >= limits.signatures)
break;
if (candidate.empty())
continue;
auto parsed = parse(candidate, limits);
if (parsed.label.empty())
continue;
result.signatures.push_back(std::move(parsed));
}
if (!result.signatures.empty())
result.active_parameter = active_parameter(text, offset, limits);
return result;
}
} // namespace vls::features::signature
+709
View File
@@ -0,0 +1,709 @@
#include <vls/index/SymbolIndex.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <Void/LanguageServer/Protocol/Json.hpp>
#include <Void/Text/Hex.hpp>
#include <algorithm>
#include <atomic>
#include <fcntl.h>
#include <fstream>
#include <limits>
#include <map>
#include <mutex>
#include <ranges>
#include <set>
#include <stdexcept>
#include <tuple>
#include <unistd.h>
namespace vls::index {
namespace fs = std::filesystem;
namespace P = Void::LanguageServer::Protocol;
using Json = P::Json;
namespace {
constexpr std::size_t max_json_depth = 8;
constexpr std::int64_t snapshot_schema = 2;
constexpr std::int64_t legacy_snapshot_schema = 1;
const char *backend_name = "vls-symbol-index";
bool plain(std::string_view text, std::size_t limit) {
return !text.empty() && text.size() <= limit &&
std::ranges::none_of(text, [](unsigned char c) { return c == 0; });
}
bool valid_location(const Location &location, const Limits &limits) {
return plain(location.path, limits.pathBytes) && location.endLine >= location.line &&
(location.endLine != location.line || location.endCharacter >= location.character);
}
bool valid_record(const SymbolRecord &record, const Limits &limits) {
if (!plain(record.name, limits.nameBytes) || !valid_location(record.location, limits) ||
record.references.size() > limits.referencesPerRecord)
return false;
if (record.definition && !valid_location(*record.definition, limits))
return false;
return std::ranges::all_of(
record.references, [&](const auto &location) { return valid_location(location, limits); });
}
Json location_json(const Location &location) {
return Json{Json::Object{{"path", Json{location.path}},
{"line", Json{std::int64_t{location.line}}},
{"character", Json{std::int64_t{location.character}}},
{"endLine", Json{std::int64_t{location.endLine}}},
{"endCharacter", Json{std::int64_t{location.endCharacter}}}}};
}
Json record_json(const SymbolRecord &record) {
Json::Array references;
for (const auto &reference : record.references)
references.push_back(location_json(reference));
Json::Object fields{{"name", Json{record.name}},
{"kind", Json{std::int64_t{static_cast<int>(record.kind)}}},
{"location", location_json(record.location)},
{"references", Json{std::move(references)}},
{"provenance", Json{record.provenance}}};
if (record.definition)
fields.emplace("definition", location_json(*record.definition));
return Json{std::move(fields)};
}
std::optional<std::string> text(const Json *value, std::size_t limit = 4096) {
const auto *string = value ? P::as_string(value) : nullptr;
if (!string || !plain(*string, limit))
return std::nullopt;
return *string;
}
std::optional<std::uint32_t> coordinate(const Json *value) {
if (!value)
return std::nullopt;
const auto *number = std::get_if<std::int64_t>(&value->value);
if (!number || *number < 0 || *number > std::numeric_limits<std::uint32_t>::max())
return std::nullopt;
return static_cast<std::uint32_t>(*number);
}
std::optional<Location> read_location(const Json *value, const Limits &limits) {
const auto *fields = value ? P::as_object(value) : nullptr;
if (!fields)
return std::nullopt;
const auto path = text(P::find_member(*fields, "path"), limits.pathBytes);
const auto line = coordinate(P::find_member(*fields, "line"));
const auto character = coordinate(P::find_member(*fields, "character"));
const auto end_line = coordinate(P::find_member(*fields, "endLine"));
const auto end_character = coordinate(P::find_member(*fields, "endCharacter"));
if (!path || !line || !character || !end_line || !end_character)
return std::nullopt;
Location location{*path, *line, *character, *end_line, *end_character};
return valid_location(location, limits) ? std::optional{location} : std::nullopt;
}
std::optional<SymbolRecord> read_record(const Json &value, const Limits &limits) {
const auto *fields = P::as_object(&value);
if (!fields)
return std::nullopt;
const auto name = text(P::find_member(*fields, "name"), limits.nameBytes);
const auto kind = coordinate(P::find_member(*fields, "kind"));
const auto provenance = text(P::find_member(*fields, "provenance"), limits.nameBytes);
const auto location = read_location(P::find_member(*fields, "location"), limits);
if (!name || !kind || !provenance || !location || *kind > static_cast<int>(SymbolKind::module))
return std::nullopt;
SymbolRecord record;
record.name = *name;
record.kind = static_cast<SymbolKind>(*kind);
record.provenance = *provenance;
record.location = *location;
if (const auto *definition = P::find_member(*fields, "definition")) {
auto parsed = read_location(definition, limits);
if (!parsed)
return std::nullopt;
record.definition = *parsed;
}
const auto *references = P::as_array(P::find_member(*fields, "references"));
if (!references || references->size() > limits.referencesPerRecord)
return std::nullopt;
for (const auto &reference : *references) {
auto parsed = read_location(&reference, limits);
if (!parsed)
return std::nullopt;
record.references.push_back(*parsed);
}
return valid_record(record, limits) ? std::optional{record} : std::nullopt;
}
struct ContextEntry {
std::vector<std::string> dependencies;
std::map<std::string, std::string> sources;
std::vector<SymbolRecord> records;
bool complete{true};
std::string reason;
};
struct OverlayEntry {
std::string content;
std::vector<SymbolRecord> records;
};
enum class SnapshotStatus { ok, incompatible, corrupt, oversized };
struct ParsedSnapshot {
std::map<std::string, ContextEntry> contexts;
std::map<std::string, OverlayEntry> overlays;
std::uint64_t generation{};
bool migrated{};
};
std::string digest_of(std::string_view bytes) {
auto digest = Void::Crypto::sha256(bytes);
return digest ? Void::Encoding::Hex::encode(*digest) : std::string{};
}
// Classifies snapshot bytes without touching index state. Schema 1 is accepted
// and flagged for migration; an unknown schema or backend is incompatible, and
// malformed content or a digest mismatch is corrupt.
SnapshotStatus parse_snapshot(std::string_view bytes, const Limits &limits, ParsedSnapshot &out) {
if (bytes.size() > limits.snapshotBytes)
return SnapshotStatus::oversized;
auto parsed = P::parse_json(bytes, max_json_depth);
if (!parsed)
return SnapshotStatus::corrupt;
const auto *root = P::as_object(&*parsed);
if (!root)
return SnapshotStatus::corrupt;
const auto *schema = P::find_member(*root, "schema");
const auto *backend = P::as_string(P::find_member(*root, "backend"));
const auto schema_value = schema ? std::get_if<std::int64_t>(&schema->value) : nullptr;
if (!schema_value || !backend || *backend != backend_name ||
(*schema_value != snapshot_schema && *schema_value != legacy_snapshot_schema))
return SnapshotStatus::incompatible;
if (*schema_value == snapshot_schema) {
const auto *digest = P::as_string(P::find_member(*root, "digest"));
if (!digest || digest->size() != 64)
return SnapshotStatus::corrupt;
auto payload = *root;
payload.erase("digest");
auto encoded = P::serialize_json(Json{std::move(payload)});
if (!encoded || digest_of(*encoded) != *digest)
return SnapshotStatus::corrupt;
}
const auto *generation = P::find_member(*root, "generation");
const auto *contexts = P::as_array(P::find_member(*root, "contexts"));
const auto *overlays = P::as_array(P::find_member(*root, "overlays"));
const auto generation_value =
generation ? std::get_if<std::int64_t>(&generation->value) : nullptr;
if (!generation_value || *generation_value < 0 || !contexts || !overlays)
return SnapshotStatus::corrupt;
out.generation = static_cast<std::uint64_t>(*generation_value);
out.migrated = *schema_value == legacy_snapshot_schema;
std::size_t total{};
for (const auto &item : *contexts) {
const auto *fields = P::as_object(&item);
if (!fields)
return SnapshotStatus::corrupt;
const auto name = text(P::find_member(*fields, "context"), limits.nameBytes);
const auto complete = P::as_bool(P::find_member(*fields, "complete"));
const auto *reason = P::as_string(P::find_member(*fields, "reason"));
const auto *dependencies = P::as_array(P::find_member(*fields, "dependencies"));
const auto *sources = P::as_array(P::find_member(*fields, "sources"));
const auto *records = P::as_array(P::find_member(*fields, "records"));
if (!name || !complete || !reason || reason->size() > limits.nameBytes || !dependencies ||
dependencies->size() > limits.contexts || !sources || !records ||
records->size() > limits.recordsPerContext || out.contexts.size() >= limits.contexts)
return SnapshotStatus::corrupt;
ContextEntry entry;
entry.complete = *complete;
entry.reason = *reason;
for (const auto &dependency : *dependencies) {
const auto value = text(&dependency, limits.pathBytes);
if (!value)
return SnapshotStatus::corrupt;
entry.dependencies.push_back(*value);
}
for (const auto &source : *sources) {
const auto *fields_source = P::as_object(&source);
if (!fields_source)
return SnapshotStatus::corrupt;
const auto source_path = text(P::find_member(*fields_source, "path"), limits.pathBytes);
const auto content = text(P::find_member(*fields_source, "content"), limits.nameBytes);
if (!source_path || !content)
return SnapshotStatus::corrupt;
entry.sources.emplace(*source_path, *content);
}
for (const auto &record : *records) {
auto parsed_record = read_record(record, limits);
if (!parsed_record)
return SnapshotStatus::corrupt;
entry.records.push_back(std::move(*parsed_record));
}
total += entry.records.size();
if (total > limits.records)
return SnapshotStatus::corrupt;
if (!out.contexts.emplace(*name, std::move(entry)).second)
return SnapshotStatus::corrupt;
}
for (const auto &item : *overlays) {
const auto *fields = P::as_object(&item);
if (!fields)
return SnapshotStatus::corrupt;
const auto path = text(P::find_member(*fields, "path"), limits.pathBytes);
const auto content = text(P::find_member(*fields, "content"), limits.nameBytes);
const auto *records = P::as_array(P::find_member(*fields, "records"));
if (!path || !content || !records || records->size() > limits.recordsPerContext)
return SnapshotStatus::corrupt;
OverlayEntry overlay;
overlay.content = *content;
for (const auto &record : *records) {
auto parsed_record = read_record(record, limits);
if (!parsed_record)
return SnapshotStatus::corrupt;
overlay.records.push_back(std::move(*parsed_record));
}
total += overlay.records.size();
if (total > limits.records || !out.overlays.emplace(*path, std::move(overlay)).second)
return SnapshotStatus::corrupt;
}
return SnapshotStatus::ok;
}
std::optional<std::string> read_snapshot(const std::filesystem::path &path, std::size_t limit) {
std::ifstream stream{path, std::ios::binary};
if (!stream)
return std::nullopt;
std::string bytes;
char buffer[65536];
while (stream) {
stream.read(buffer, sizeof buffer);
bytes.append(buffer, static_cast<std::size_t>(stream.gcount()));
if (bytes.size() > limit)
return std::nullopt;
}
return stream.eof() ? std::optional{std::move(bytes)} : std::nullopt;
}
} // namespace
struct SymbolIndex::State {
explicit State(Limits value) : limits(value) {}
Limits limits;
mutable std::mutex mutex;
std::map<std::string, ContextEntry> contexts;
std::map<std::string, OverlayEntry> overlays;
std::uint64_t generation{};
std::shared_ptr<const Generation> current;
Coverage coverage_locked(const std::optional<std::string> &filter) const {
Coverage result;
for (const auto &[name, entry] : contexts) {
if (filter && name != *filter)
continue;
result.indexed = true;
if (!entry.complete)
result.incomplete.push_back(name);
}
if (!filter && !overlays.empty())
result.indexed = true;
result.complete = result.indexed && result.incomplete.empty();
return result;
}
std::vector<SymbolRecord>
snapshot_locked(std::vector<std::pair<std::string, Coverage>> &contexts_out) const {
std::vector<SymbolRecord> records;
for (const auto &[name, entry] : contexts) {
records.insert(records.end(), entry.records.begin(), entry.records.end());
contexts_out.emplace_back(name, Coverage{true, entry.complete, {}});
}
for (const auto &[path, overlay] : overlays)
records.insert(records.end(), overlay.records.begin(), overlay.records.end());
return records;
}
void publish_locked() {
++generation;
std::vector<std::pair<std::string, Coverage>> contexts_out;
auto records = snapshot_locked(contexts_out);
current = std::shared_ptr<const Generation>(
new Generation{generation, std::move(records), std::move(contexts_out)});
}
};
SymbolIndex::SymbolIndex(Limits limits) : state_(std::make_shared<State>(limits)) {}
SymbolIndex::~SymbolIndex() = default;
bool SymbolIndex::publish(const ContextInput &input) {
auto &state = *state_;
for (const auto &record : input.records)
if (!valid_record(record, state.limits))
return false;
for (const auto &dependency : input.dependencies)
if (!plain(dependency, state.limits.pathBytes))
return false;
for (const auto &[path, content] : input.sources)
if (!plain(path, state.limits.pathBytes) || !plain(content, state.limits.nameBytes))
return false;
std::lock_guard lock{state.mutex};
if (!plain(input.context, state.limits.nameBytes) ||
input.records.size() > state.limits.recordsPerContext ||
(!state.contexts.contains(input.context) && state.contexts.size() >= state.limits.contexts))
return false;
std::size_t total = input.records.size();
for (const auto &[name, entry] : state.contexts)
if (name != input.context)
total += entry.records.size();
if (total > state.limits.records)
return false;
ContextEntry entry;
entry.dependencies = input.dependencies;
entry.records = input.records;
entry.complete = input.complete;
entry.reason = input.reason;
for (const auto &[path, content] : input.sources)
entry.sources.emplace(path, content);
state.contexts[input.context] = std::move(entry);
state.publish_locked();
return true;
}
bool SymbolIndex::remove(std::string_view context) {
auto &state = *state_;
std::lock_guard lock{state.mutex};
if (state.contexts.erase(std::string{context}) == 0)
return false;
state.publish_locked();
return true;
}
bool SymbolIndex::set_overlay(std::string path, std::string content,
std::vector<SymbolRecord> records) {
auto &state = *state_;
if (!plain(path, state.limits.pathBytes) || !plain(content, state.limits.nameBytes) ||
records.size() > state.limits.recordsPerContext)
return false;
for (const auto &record : records)
if (!valid_record(record, state.limits))
return false;
std::lock_guard lock{state.mutex};
state.overlays[std::move(path)] = OverlayEntry{std::move(content), std::move(records)};
return true;
}
bool SymbolIndex::clear_overlay(std::string_view path) {
auto &state = *state_;
std::lock_guard lock{state.mutex};
return state.overlays.erase(std::string{path}) != 0;
}
std::size_t SymbolIndex::invalidate(std::string_view path,
const std::optional<std::string> &content) {
auto &state = *state_;
std::lock_guard lock{state.mutex};
std::size_t affected{};
for (auto &[name, entry] : state.contexts) {
const bool dependent = std::ranges::contains(entry.dependencies, path) ||
entry.sources.contains(std::string{path});
if (!dependent)
continue;
const auto source = entry.sources.find(std::string{path});
if (content && source != entry.sources.end() && source->second == *content)
continue;
if (source != entry.sources.end())
entry.sources.erase(source);
if (entry.complete) {
entry.complete = false;
entry.reason = "changed source";
++affected;
}
}
if (affected)
state.publish_locked();
return affected;
}
Result SymbolIndex::find(const Query &query) const {
auto &state = *state_;
std::lock_guard lock{state.mutex};
Result result;
result.coverage = state.coverage_locked(query.context);
std::set<std::tuple<std::string, SymbolKind, Location>> seen;
auto consider = [&](const SymbolRecord &record) {
if (query.name.empty() && !query.substring)
return;
const bool matches =
query.substring ? record.name.contains(query.name) : record.name == query.name;
if (!matches)
return;
if (!seen.emplace(record.name, record.kind, record.location).second)
return;
result.symbols.push_back(record);
};
std::set<std::string> shadowed;
for (const auto &[path, overlay] : state.overlays)
shadowed.insert(path);
for (const auto &[name, entry] : state.contexts) {
if (query.context && name != *query.context)
continue;
for (const auto &record : entry.records)
if (!shadowed.contains(record.location.path))
consider(record);
}
for (const auto &[path, overlay] : state.overlays)
for (const auto &record : overlay.records)
consider(record);
std::ranges::sort(result.symbols, [](const auto &left, const auto &right) {
return std::tie(left.name, left.location, left.kind) <
std::tie(right.name, right.location, right.kind);
});
if (result.symbols.size() > query.limit) {
result.symbols.resize(query.limit);
result.truncated = true;
}
return result;
}
Coverage SymbolIndex::coverage() const {
auto &state = *state_;
std::lock_guard lock{state.mutex};
return state.coverage_locked(std::nullopt);
}
std::shared_ptr<const Generation> SymbolIndex::current() const {
auto &state = *state_;
std::lock_guard lock{state.mutex};
return state.current;
}
std::uint64_t SymbolIndex::generation() const {
auto &state = *state_;
std::lock_guard lock{state.mutex};
return state.generation;
}
std::size_t SymbolIndex::records() const {
auto &state = *state_;
std::lock_guard lock{state.mutex};
std::size_t total{};
for (const auto &[name, entry] : state.contexts)
total += entry.records.size();
for (const auto &[path, overlay] : state.overlays)
total += overlay.records.size();
return total;
}
const Limits &SymbolIndex::limits() const noexcept { return state_->limits; }
bool SymbolIndex::save(const fs::path &path) const {
auto &state = *state_;
Json root;
{
std::lock_guard lock{state.mutex};
Json::Array contexts;
for (const auto &[name, entry] : state.contexts) {
Json::Array dependencies, sources, records;
for (const auto &dependency : entry.dependencies)
dependencies.push_back(Json{dependency});
for (const auto &[source, content] : entry.sources)
sources.push_back(
Json{Json::Object{{"path", Json{source}}, {"content", Json{content}}}});
for (const auto &record : entry.records)
records.push_back(record_json(record));
contexts.push_back(Json{Json::Object{{"context", Json{name}},
{"complete", Json{entry.complete}},
{"reason", Json{entry.reason}},
{"dependencies", Json{std::move(dependencies)}},
{"sources", Json{std::move(sources)}},
{"records", Json{std::move(records)}}}});
}
Json::Array overlays;
for (const auto &[path, overlay] : state.overlays) {
Json::Array records;
for (const auto &record : overlay.records)
records.push_back(record_json(record));
overlays.push_back(Json{Json::Object{{"path", Json{path}},
{"content", Json{overlay.content}},
{"records", Json{std::move(records)}}}});
}
root = Json{Json::Object{{"schema", Json{snapshot_schema}},
{"backend", Json{std::string{backend_name}}},
{"generation", Json{static_cast<std::int64_t>(state.generation)}},
{"contexts", Json{std::move(contexts)}},
{"overlays", Json{std::move(overlays)}}}};
}
// The digest covers the canonical payload without itself, so a flipped
// byte in valid JSON is corruption rather than silently trusted data.
auto payload = P::serialize_json(root);
if (!payload)
return false;
const auto digest = digest_of(*payload);
if (digest.size() != 64)
return false;
std::get<Json::Object>(root.value).emplace("digest", Json{digest});
auto serialized = P::serialize_json(root);
if (!serialized || serialized->size() > state.limits.snapshotBytes)
return false;
const auto temporary = path.parent_path() / (path.filename().native() + ".tmp");
try {
fs::create_directories(path.parent_path());
std::ofstream stream{temporary, std::ios::binary | std::ios::trunc};
stream.write(serialized->data(), static_cast<std::streamsize>(serialized->size()));
stream.close();
if (!stream)
return false;
const int descriptor = ::open(temporary.c_str(), O_RDONLY | O_CLOEXEC);
if (descriptor < 0 || ::fsync(descriptor) != 0) {
if (descriptor >= 0)
::close(descriptor);
return false;
}
::close(descriptor);
fs::rename(temporary, path);
return true;
} catch (const std::exception &) {
std::error_code error;
fs::remove(temporary, error);
return false;
}
}
std::expected<SymbolIndex::LoadResult, std::string> SymbolIndex::restore(const fs::path &path) {
std::error_code error;
if (!fs::exists(path, error))
return LoadResult{LoadStatus::missing, generation(), std::nullopt, false};
ParsedSnapshot parsed;
auto bytes = read_snapshot(path, limits().snapshotBytes + 1);
auto status = bytes ? parse_snapshot(*bytes, limits(), parsed) : SnapshotStatus::corrupt;
if (!bytes && fs::file_size(path, error) > limits().snapshotBytes)
status = SnapshotStatus::oversized;
if (status == SnapshotStatus::ok) {
auto &state = *state_;
std::lock_guard lock{state.mutex};
state.contexts = std::move(parsed.contexts);
state.overlays = std::move(parsed.overlays);
state.generation = parsed.generation;
state.publish_locked();
return LoadResult{LoadStatus::loaded, state.generation, std::nullopt, parsed.migrated};
}
static std::atomic<unsigned long> quarantined{};
const auto target = path.parent_path() /
(path.filename().native() + ".quarantine-" + std::to_string(::getpid()) +
"-" + std::to_string(quarantined.fetch_add(1)));
fs::rename(path, target, error);
if (error)
return std::unexpected("cannot quarantine the rejected index snapshot");
auto &state = *state_;
std::lock_guard lock{state.mutex};
state.contexts.clear();
state.overlays.clear();
state.publish_locked();
const auto result = status == SnapshotStatus::incompatible ? LoadStatus::incompatible
: status == SnapshotStatus::oversized ? LoadStatus::oversized
: LoadStatus::corrupt;
return LoadResult{result, state.generation, target, false};
}
bool SymbolIndex::save_generation(const fs::path &root) {
std::error_code error;
fs::create_directories(root, error);
if (error)
return false;
const auto current = root / "snapshot.json";
const auto previous = root / "snapshot.prev.json";
if (fs::exists(current, error))
fs::rename(current, previous, error);
if (!save(current))
return false;
const auto temporary = root / "CURRENT.tmp";
{
std::ofstream stream{temporary, std::ios::binary | std::ios::trunc};
stream << "{\"schema\":2,\"file\":\"snapshot.json\"}\n";
}
fs::rename(temporary, root / "CURRENT", error);
return !error;
}
std::expected<SymbolIndex::LoadResult, std::string>
SymbolIndex::restore_generation(const fs::path &root) {
std::error_code error;
if (!fs::exists(root, error))
return LoadResult{LoadStatus::missing, generation(), std::nullopt};
const auto current = root / "CURRENT";
const auto legacy = root / "index.json";
fs::path selected;
bool migrate_selector{};
if (fs::exists(current, error)) {
std::ifstream stream{current, std::ios::binary};
std::string line(256, '\0');
stream.read(line.data(), static_cast<std::streamsize>(line.size()));
line.resize(static_cast<std::size_t>(stream.gcount()));
while (!line.empty() && (line.back() == '\n' || line.back() == '\r'))
line.pop_back();
std::string file;
if (line == "snapshot.json") {
// Schema 1 selector: a bare file name.
file = line;
migrate_selector = true;
} else {
auto parsed = P::parse_json(line, max_json_depth);
const auto *fields = parsed ? P::as_object(&*parsed) : nullptr;
const auto *schema = fields ? P::find_member(*fields, "schema") : nullptr;
const auto *name = fields ? P::as_string(P::find_member(*fields, "file")) : nullptr;
const auto *value = schema ? std::get_if<std::int64_t>(&schema->value) : nullptr;
if (!fields || !name || !value || *value != 2)
return std::unexpected("unsupported index generation selector");
file = *name;
}
if (file != "snapshot.json")
return std::unexpected("unsupported index generation selector");
selected = root / file;
} else if (fs::exists(legacy, error)) {
selected = legacy;
} else {
return LoadResult{LoadStatus::missing, generation(), std::nullopt};
}
auto result = restore(selected);
if (!result)
return result;
if (result->status != LoadStatus::loaded) {
const auto previous = root / "snapshot.prev.json";
if (fs::exists(previous, error)) {
result = restore(previous);
// Keep CURRENT consistent: the recovered generation becomes current.
if (result && result->status == LoadStatus::loaded)
fs::copy_file(previous, root / "snapshot.json",
fs::copy_options::overwrite_existing, error);
}
}
if (result && result->status == LoadStatus::loaded && (migrate_selector || result->migrated)) {
const auto temporary = root / "CURRENT.tmp";
std::ofstream stream{temporary, std::ios::binary | std::ios::trunc};
stream << "{\"schema\":2,\"file\":\"snapshot.json\"}\n";
stream.close();
fs::rename(temporary, current, error);
// Persist the upgraded snapshot format; the previous generation is
// kept as snapshot.prev.json for crash recovery.
if (!save_generation(root))
return std::unexpected("cannot persist the migrated index generation");
}
if (result && result->status == LoadStatus::loaded && !fs::exists(current, error))
static_cast<void>(save_generation(root));
return result;
}
bool SymbolIndex::load(const fs::path &path) {
auto bytes = read_snapshot(path, limits().snapshotBytes);
if (!bytes)
return false;
ParsedSnapshot parsed;
if (parse_snapshot(*bytes, limits(), parsed) != SnapshotStatus::ok)
return false;
auto &state = *state_;
std::lock_guard lock{state.mutex};
state.contexts = std::move(parsed.contexts);
state.overlays = std::move(parsed.overlays);
state.generation = parsed.generation;
state.publish_locked();
return true;
}
} // namespace vls::index
+136 -8
View File
@@ -1,27 +1,150 @@
#include <vls/Server.hpp>
#include <vls/semantic/StockCompiler.hpp>
#include <Void/Configuration/Argparse.hpp>
#include <csignal>
#include <filesystem>
#include <iostream>
#include <set>
#include <string_view>
namespace {
namespace fs = std::filesystem;
namespace Workspace = Void::LanguageServer::Workspace;
struct Options {
std::optional<std::string> root, user_file, provider, database, selector, build_root,
producer_cwd, profile, gcc_profile;
bool gcc_diagnostics{};
};
std::expected<vls::WorkspaceLaunch, std::string> workspace_launch(const Options &options) {
vls::WorkspaceLaunch launch;
if (!options.root) {
if (options.user_file || options.provider || options.database || options.selector ||
options.build_root || options.producer_cwd || options.profile ||
options.gcc_profile || options.gcc_diagnostics)
return std::unexpected{"workspace options require --workspace-root"};
return launch;
}
const fs::path root{*options.root};
std::error_code ec;
if (!root.is_absolute() || !fs::is_directory(root, ec))
return std::unexpected{"--workspace-root requires an existing absolute directory"};
launch.root = fs::canonical(root, ec);
if (ec)
return std::unexpected{"could not resolve the selected workspace"};
if (options.user_file) {
auto user = Workspace::read_user_settings(*options.user_file);
if (!user)
return std::unexpected{user.error().message};
launch.user_settings = std::move(*user);
}
auto directory = [](const std::optional<std::string> &value)
-> std::expected<std::optional<fs::path>, std::string> {
if (!value)
return std::nullopt;
const fs::path path{*value};
std::error_code error;
if (!path.is_absolute() || path != path.lexically_normal() ||
!fs::is_directory(path, error))
return std::unexpected{
"VBS directory options require an existing normalized absolute directory"};
return path;
};
auto build = directory(options.build_root), producer = directory(options.producer_cwd);
if (!build || !producer)
return std::unexpected{!build ? build.error() : producer.error()};
launch.build_root = std::move(*build);
launch.producer_cwd = std::move(*producer);
Workspace::SettingsOverrides overrides;
overrides.compdb_path = options.database;
overrides.vbs_manifest_path = options.selector;
overrides.selected_profile = options.profile;
if (options.gcc_profile && options.gcc_diagnostics)
return std::unexpected{"choose either --gcc-profile or --gcc-diagnostics"};
// D-031: diagnostics are prepared in process by default for a selected
// workspace. An explicit flag fails loudly; the default falls back to a
// passive session when the local toolchain is unavailable.
const bool diagnostics_default =
!options.gcc_profile && (!options.provider || *options.provider != "none");
if (options.gcc_profile || options.gcc_diagnostics || diagnostics_default) {
auto profile = options.gcc_profile
? vls::semantic::GccProfile::load(*options.gcc_profile)
: vls::semantic::GccProfile::prepare("g++");
if (!profile) {
if (options.gcc_profile || options.gcc_diagnostics)
return std::unexpected{profile.error()};
} else {
launch.diagnostics_profile = std::move(*profile);
}
if (launch.diagnostics_profile)
overrides.tool_approvals = {{*launch.root, Workspace::AuthorityLevel::compiler_use,
launch.diagnostics_profile->driver}};
}
if (options.provider) {
for (auto choice :
{Workspace::ProviderPreference::auto_detect, Workspace::ProviderPreference::vbs,
Workspace::ProviderPreference::compdb, Workspace::ProviderPreference::none}) {
if (*options.provider == Workspace::provider_preference_name(choice))
overrides.provider = choice;
}
if (!overrides.provider)
return std::unexpected{"--provider expects auto, vbs, compdb or none"};
}
auto cli = Workspace::settings_from_cli(std::move(overrides), *launch.root);
if (!cli.diagnostics().empty())
return std::unexpected{cli.diagnostics().front().message};
launch.cli_settings = std::move(cli);
return launch;
}
} // namespace
int main(int argc, char **argv) {
bool stdio = false;
bool version = false;
Options options;
Void::Argparse::Parser parser{
"vls", "VoidLanguageServer 0.1.0: stdio LSP lifecycle shell.\n"
"No arguments starts stdio. Language and debugger features are planned."};
parser.flag("--stdio", "", "run the stdio LSP lifecycle shell", stdio);
"vls", "VoidLanguageServer provides C++26 language services for Void projects.\n"
"With no arguments, VLS serves LSP over standard input and output."};
parser.flag("--stdio", "", "run the language server over standard input and output", stdio);
parser.flag("--version", "-V", "show version", version);
parser.option("--workspace-root", "", "workspace for these launcher settings", options.root);
parser.option("--user-config", "", "absolute user settings file for this workspace",
options.user_file);
parser.option("--provider", "", "auto, vbs, compdb or none", options.provider);
parser.option("--compdb", "", "compilation database locator", options.database);
parser.option("--vbs-manifest", "", "VBS editor selection record", options.selector);
parser.option("--vbs-build-root", "", "absolute directory containing VBS profiles",
options.build_root);
parser.option("--vbs-producer-cwd", "", "working directory used to publish relative VBS paths",
options.producer_cwd);
parser.option("--profile", "", "preferred build context profile", options.profile);
parser.option(
"--gcc-profile", "",
"enable stock GCC diagnostics for this workspace using an absolute prepared profile",
options.gcc_profile);
parser.flag("--gcc-diagnostics", "",
"prepare stock GCC diagnostics in process from the selected GCC driver "
"(enabled by default when a workspace is selected)",
options.gcc_diagnostics);
if (argc == 2 && (std::string_view{argv[1]} == "--help" || std::string_view{argv[1]} == "-h")) {
std::cout << parser.help();
return std::cout ? 0 : 1;
}
// Each mode is standalone. This also rejects duplicate flags deterministically.
if (argc > 2) {
std::cerr << "vls: options must be used alone; use --help\n";
return 2;
std::set<std::string_view> seen;
for (int i = 1; i < argc; ++i) {
const std::string_view arg = argv[i];
if (!arg.starts_with('-'))
continue;
const auto name = arg.substr(0, arg.find('='));
if (arg == "--" || !seen.insert(name).second ||
(argc != 2 &&
(name == "--help" || name == "-h" || name == "--version" || name == "-V"))) {
std::cerr << "vls: invalid option combination; use --help\n";
return 2;
}
}
const auto parsed = parser.parse(argc, argv);
if (!parsed) {
@@ -32,8 +155,13 @@ int main(int argc, char **argv) {
std::cout << "VoidLanguageServer " << vls::server_version << '\n';
return std::cout ? 0 : 1;
}
auto launch = workspace_launch(options);
if (!launch) {
std::cerr << "vls: " << launch.error() << '\n';
return 2;
}
#ifdef SIGPIPE
std::signal(SIGPIPE, SIG_IGN);
#endif
return vls::run_stdio(std::cin, std::cout, std::cerr);
return vls::run_stdio(std::cin, std::cout, std::cerr, {}, std::move(*launch));
}
+328
View File
@@ -0,0 +1,328 @@
#include <vls/modules/ArtifactCache.hpp>
#include <Void/Crypto/Crypto.hpp>
#include <Void/Text/Hex.hpp>
#include <algorithm>
#include <array>
#include <atomic>
#include <deque>
#include <fcntl.h>
#include <fstream>
#include <mutex>
#include <ranges>
#include <set>
#include <stdexcept>
#include <unistd.h>
namespace vls::modules {
namespace fs = std::filesystem;
namespace {
constexpr std::size_t max_artifact_bytes = 512 * 1024 * 1024;
constexpr std::size_t max_manifest_bytes = 16 * 1024 * 1024;
std::string hex(std::string_view bytes) {
constexpr char digits[] = "0123456789abcdef";
std::string text;
text.reserve(bytes.size() * 2);
for (const unsigned char byte : bytes) {
text += digits[byte >> 4];
text += digits[byte & 0xf];
}
return text;
}
std::string unhex(std::string_view text, std::size_t limit) {
if (text.size() % 2 || text.size() > limit * 2)
throw std::runtime_error("invalid artifact manifest field");
auto value = [](char c) -> int {
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
return -1;
};
std::string bytes;
bytes.reserve(text.size() / 2);
for (std::size_t i = 0; i < text.size(); i += 2) {
const int high = value(text[i]), low = value(text[i + 1]);
if (high < 0 || low < 0)
throw std::runtime_error("invalid artifact manifest field");
bytes += static_cast<char>((high << 4) | low);
}
return bytes;
}
bool digest_text(std::string_view text) {
return text.size() == 64 && std::ranges::all_of(text, [](char c) {
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
});
}
std::string digest(std::string_view bytes) {
auto value = Void::Crypto::sha256(bytes);
if (!value)
throw std::runtime_error("could not hash an artifact");
return Void::Encoding::Hex::encode(*value);
}
std::string read_file(const fs::path &path, std::size_t limit) {
std::ifstream stream{path, std::ios::binary};
if (!stream)
throw std::runtime_error("cannot open " + path.native());
std::string bytes;
char buffer[65536];
while (stream) {
stream.read(buffer, sizeof buffer);
bytes.append(buffer, static_cast<std::size_t>(stream.gcount()));
if (bytes.size() > limit)
throw std::runtime_error("artifact exceeds its size limit");
}
if (!stream.eof())
throw std::runtime_error("cannot read " + path.native());
return bytes;
}
void write_file(const fs::path &path, std::string_view bytes) {
std::ofstream stream{path, std::ios::binary | std::ios::trunc};
stream.write(bytes.data(), static_cast<std::streamsize>(bytes.size()));
stream.flush();
if (!stream)
throw std::runtime_error("cannot write " + path.native());
stream.close();
const int descriptor = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (descriptor < 0 || ::fsync(descriptor) != 0) {
if (descriptor >= 0)
::close(descriptor);
throw std::runtime_error("cannot sync " + path.native());
}
::close(descriptor);
}
void sync_directory(const fs::path &path) {
const int descriptor = ::open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (descriptor < 0)
throw std::runtime_error("cannot open a cache directory");
const bool ok = ::fsync(descriptor) == 0;
::close(descriptor);
if (!ok)
throw std::runtime_error("cannot sync a cache directory");
}
std::string unique_name() {
static std::atomic<unsigned long> sequence{};
return std::to_string(::getpid()) + "-" + std::to_string(sequence.fetch_add(1));
}
struct Cleanup {
fs::path path;
bool armed{true};
~Cleanup() {
if (armed) {
std::error_code error;
fs::remove_all(path, error);
}
}
};
} // namespace
std::string ArtifactKey::identity() const {
return digest(compatibility + '\0' + context + '\0' + inputs + '\0' + kind);
}
std::optional<ArtifactEntry> ArtifactGeneration::find(const ArtifactKey &key) const {
const auto entry = entries_.find(key);
if (entry == entries_.end())
return std::nullopt;
return entry->second;
}
struct ArtifactCache::State {
State(fs::path cache, std::size_t keep) : root(std::move(cache)), retained(keep) {}
fs::path root;
std::size_t retained;
mutable std::mutex mutex;
std::shared_ptr<const ArtifactGeneration> current;
std::map<std::string, std::weak_ptr<const ArtifactGeneration>> known;
std::deque<std::string> order;
};
ArtifactCache::ArtifactCache(fs::path root, std::size_t retained)
: state_(std::make_shared<State>(std::move(root), retained)) {}
ArtifactCache::~ArtifactCache() = default;
std::expected<std::shared_ptr<const ArtifactGeneration>, std::string>
ArtifactCache::publish(const std::map<ArtifactKey, fs::path> &artifacts) {
try {
if (artifacts.empty())
return std::unexpected("no artifacts to publish");
auto &state = *state_;
fs::create_directories(state.root / "generations");
fs::create_directories(state.root / "tmp");
const auto temporary = state.root / "tmp" / unique_name();
fs::create_directory(temporary);
Cleanup cleanup{temporary};
std::map<std::string, std::string> contents;
std::map<ArtifactKey, std::string> digests;
for (const auto &[key, path] : artifacts) {
auto bytes = read_file(path, max_artifact_bytes);
const auto sha = digest(bytes);
contents.emplace(sha, std::move(bytes));
digests.emplace(key, sha);
}
std::string manifest;
for (const auto &[key, sha] : digests)
manifest += hex(key.compatibility) + " " + hex(key.context) + " " + hex(key.inputs) +
" " + hex(key.kind) + " " + sha + " " + sha + "\n";
const auto id = digest(manifest);
const auto target = state.root / "generations" / id;
if (!fs::exists(target)) {
for (const auto &[sha, bytes] : contents)
write_file(temporary / sha, bytes);
write_file(temporary / "manifest", manifest);
sync_directory(temporary);
fs::rename(temporary, target);
cleanup.armed = false;
sync_directory(state.root / "generations");
}
std::map<ArtifactKey, ArtifactEntry> entries;
for (const auto &line :
read_file(target / "manifest", max_manifest_bytes) | std::views::split('\n')) {
std::string_view text{line.begin(), line.end()};
if (text.empty())
continue;
std::array<std::string_view, 6> fields;
std::size_t field{};
while (!text.empty() && field != fields.size()) {
const auto space = text.find(' ');
fields[field++] = text.substr(0, space);
text =
space == std::string_view::npos ? std::string_view{} : text.substr(space + 1);
}
if (field != fields.size() || !text.empty())
throw std::runtime_error("invalid artifact manifest");
ArtifactKey key{unhex(fields[0], 4096), unhex(fields[1], 4096), unhex(fields[2], 4096),
unhex(fields[3], 256)};
const auto sha = std::string{fields[4]};
const auto name = std::string{fields[5]};
if (!digest_text(sha) || name != sha || !fs::is_regular_file(target / name))
throw std::runtime_error("invalid artifact manifest entry");
entries.emplace(key, ArtifactEntry{key, target / name, sha});
}
if (entries.size() != digests.size())
throw std::runtime_error("incomplete artifact manifest");
auto generation = std::shared_ptr<const ArtifactGeneration>(
new ArtifactGeneration{id, target, std::move(entries)});
{
std::lock_guard lock{state.mutex};
state.current = generation;
state.known[id] = generation;
state.order.push_back(id);
while (state.order.size() > 256)
state.order.pop_front();
}
return generation;
} catch (const std::exception &error) {
return std::unexpected(error.what());
}
}
std::shared_ptr<const ArtifactGeneration> ArtifactCache::current() const {
auto &state = *state_;
std::lock_guard lock{state.mutex};
return state.current;
}
std::size_t ArtifactCache::collect() {
auto &state = *state_;
std::vector<fs::path> remove;
{
std::lock_guard lock{state.mutex};
std::set<std::string> keep;
if (state.current)
keep.insert(state.current->id());
std::size_t retained{};
for (auto entry = state.order.rbegin(); entry != state.order.rend(); ++entry) {
const auto known = state.known.find(*entry);
if (known == state.known.end())
continue;
if (known->second.lock() || retained < state.retained) {
keep.insert(*entry);
if (!known->second.lock())
++retained;
}
}
for (auto entry = state.known.begin(); entry != state.known.end();) {
if (keep.contains(entry->first)) {
++entry;
continue;
}
remove.push_back(state.root / "generations" / entry->first);
entry = state.known.erase(entry);
}
std::erase_if(state.order, [&](const auto &id) { return !state.known.contains(id); });
}
std::size_t removed{};
for (const auto &path : remove) {
std::error_code error;
removed += fs::remove_all(path, error);
}
return removed;
}
std::size_t ArtifactCache::generations() const {
auto &state = *state_;
std::lock_guard lock{state.mutex};
std::error_code error;
std::size_t count{};
for (const auto &entry : fs::directory_iterator{state.root / "generations", error})
if (entry.is_directory())
++count;
return count;
}
std::expected<std::shared_ptr<const ArtifactGeneration>, std::string>
produce_module_artifacts(const ModulePlan &plan, ArtifactCache &cache, const fs::path &staging,
ArtifactWork work, std::stop_token stop) {
try {
if (!plan.ready())
return std::unexpected("module plan is not ready");
if (!work)
return std::unexpected("no artifact work");
std::error_code error;
fs::remove_all(staging, error);
fs::create_directories(staging);
Cleanup cleanup{staging};
std::map<ArtifactKey, fs::path> artifacts;
for (const auto &key : plan.order) {
if (stop.stop_requested())
return std::unexpected("artifact production cancelled");
const auto unit = std::ranges::find_if(plan.units, [&](const auto &candidate) {
return candidate.member.context.alternative == key.alternative;
});
if (unit == plan.units.end())
return std::unexpected("planned unit is missing from the census");
const auto output = staging / hex(key.alternative);
auto produced = work(stop, key, output);
if (!produced)
return std::unexpected(produced.error());
if (stop.stop_requested())
return std::unexpected("artifact production cancelled");
if (!fs::is_regular_file(*produced))
return std::unexpected("artifact work produced no regular file");
const auto &inputs = unit->member.inputs;
ArtifactKey artifact{plan.domain.compatibility, key.alternative,
inputs.command + "|" + inputs.source + "|" +
inputs.textual_closure + "|" +
inputs.system_closure.value_or(""),
"cmi"};
artifacts.emplace(std::move(artifact), *produced);
}
return cache.publish(artifacts);
} catch (const std::exception &error) {
return std::unexpected(error.what());
}
}
} // namespace vls::modules
+119
View File
@@ -0,0 +1,119 @@
#include <vls/modules/GccArtifacts.hpp>
#include <Void/System/Process.hpp>
#include <algorithm>
#include <atomic>
#include <fstream>
#include <stdexcept>
#include <unistd.h>
namespace vls::modules {
namespace fs = std::filesystem;
namespace {
constexpr std::size_t max_cache_entries = 4096;
constexpr unsigned max_cache_depth = 8;
constexpr std::size_t max_error_bytes = 1024 * 1024;
std::string unique_name() {
static std::atomic<unsigned long> sequence{};
return std::to_string(::getpid()) + "-" + std::to_string(sequence.fetch_add(1));
}
struct Cleanup {
fs::path path;
~Cleanup() {
std::error_code error;
fs::remove_all(path, error);
}
};
void copy_artifact(const fs::path &from, const fs::path &to) {
std::ifstream input{from, std::ios::binary};
if (!input)
throw std::runtime_error("cannot open the produced module artifact");
fs::create_directories(to.parent_path());
std::ofstream output{to, std::ios::binary | std::ios::trunc};
if (!output)
throw std::runtime_error("cannot create the private module artifact");
output << input.rdbuf();
output.close();
if (!output)
throw std::runtime_error("cannot write the private module artifact");
}
void collect(const fs::path &directory, unsigned depth, std::vector<fs::path> &found) {
if (depth > max_cache_depth || found.size() > max_cache_entries)
throw std::runtime_error("module cache exceeds its bounds");
std::error_code error;
for (const auto &entry : fs::directory_iterator{directory, error}) {
if (error)
throw std::runtime_error("cannot read the module cache");
if (entry.is_directory()) {
collect(entry.path(), depth + 1, found);
} else if (entry.is_regular_file() && entry.path().extension() == ".gcm") {
found.push_back(entry.path());
if (found.size() > max_cache_entries)
throw std::runtime_error("module cache exceeds its bounds");
}
}
}
} // namespace
ArtifactWork gcc_module_artifact_work(ModuleCommandLookup lookup, GccArtifactOptions options) {
return [lookup = std::move(lookup),
options](std::stop_token stop, const Build::ContextKey &context,
const fs::path &output) -> std::expected<fs::path, std::string> {
try {
if (!lookup)
return std::unexpected("no module command lookup");
const auto command = lookup(context);
if (!command || command->arguments.empty())
return std::unexpected("no checked module command for the planned unit");
if (!command->working_directory.is_absolute())
return std::unexpected("module command working directory must be absolute");
const auto work = output.parent_path() / ("module-" + unique_name());
fs::create_directories(work);
Cleanup cleanup{work};
Void::Process::SpawnOptions spawn;
spawn.executable = command->arguments.front();
spawn.arguments.assign(command->arguments.begin() + 1, command->arguments.end());
spawn.working_directory = work;
spawn.search_path = false;
spawn.environment.set_vars = {{"LC_ALL", "C"}};
auto child = Void::Process::spawn(spawn);
if (!child)
return std::unexpected("could not start the module compiler");
auto received =
Void::Process::communicate_blocking(*child, {},
{.max_stdout_bytes = options.max_output_bytes,
.max_stderr_bytes = max_error_bytes,
.max_line_bytes = max_error_bytes},
options.deadline, stop);
if (!received)
return std::unexpected("module compiler communication failed");
if (received->cancelled || stop.stop_requested())
return std::unexpected("module compilation cancelled");
if (received->timed_out)
return std::unexpected("module compilation timed out");
if (!received->status.exited || received->status.code != 0)
return std::unexpected("module compiler failed: " + received->err.substr(0, 512));
std::vector<fs::path> artifacts;
const auto cache = work / "gcm.cache";
std::error_code error;
if (fs::is_directory(cache, error))
collect(cache, 0, artifacts);
if (artifacts.size() != 1)
return std::unexpected("expected exactly one module interface artifact");
const auto size = fs::file_size(artifacts.front(), error);
if (error || size == 0 || size > options.max_artifact_bytes)
return std::unexpected("module interface artifact has an invalid size");
copy_artifact(artifacts.front(), output);
return output;
} catch (const std::exception &error) {
return std::unexpected(error.what());
}
};
}
} // namespace vls::modules
+121
View File
@@ -0,0 +1,121 @@
#include <vls/modules/GccScan.hpp>
#include <Void/System/Process.hpp>
#include <algorithm>
#include <atomic>
#include <fstream>
#include <stdexcept>
#include <unistd.h>
namespace vls::modules {
namespace fs = std::filesystem;
namespace {
constexpr std::size_t max_error_bytes = 1024 * 1024;
std::string unique_name() {
static std::atomic<unsigned long> sequence{};
return std::to_string(::getpid()) + "-" + std::to_string(sequence.fetch_add(1));
}
struct Cleanup {
fs::path path;
~Cleanup() {
std::error_code error;
fs::remove_all(path, error);
}
};
std::string read_file(const fs::path &path, std::size_t limit) {
std::ifstream stream{path, std::ios::binary};
if (!stream)
throw std::runtime_error("cannot open the scan dependency file");
std::string bytes;
char buffer[65536];
while (stream) {
stream.read(buffer, sizeof buffer);
bytes.append(buffer, static_cast<std::size_t>(stream.gcount()));
if (bytes.size() > limit)
throw std::runtime_error("scan dependency file exceeds its limit");
}
if (!stream.eof())
throw std::runtime_error("cannot read the scan dependency file");
return bytes;
}
} // namespace
std::function<std::string(std::stop_token)>
gcc_module_scan_work(ScanCommandLookup lookup, Build::ContextKey context,
std::shared_ptr<ScanProduct> product, ScanOptions options) {
return [lookup = std::move(lookup), context = std::move(context), product,
options](std::stop_token stop) -> std::string {
if (!product)
throw std::runtime_error("no scan product owner");
if (!lookup)
throw std::runtime_error("no scan command lookup");
const auto command = lookup(context);
if (!command || command->arguments.empty())
throw std::runtime_error("no checked scan command for the planned unit");
if (!command->working_directory.is_absolute() || !options.directory.is_absolute())
throw std::runtime_error("scan paths must be absolute");
std::vector<std::string> arguments = command->arguments;
std::optional<fs::path> dependency;
for (const auto &argument : arguments) {
if (!argument.starts_with("-fdeps-file="))
continue;
if (dependency)
throw std::runtime_error("duplicate scan dependency file");
const fs::path value = argument.substr(std::string_view{"-fdeps-file="}.size());
if (!value.is_absolute())
throw std::runtime_error("scan dependency file must be absolute");
dependency = value;
}
if (!dependency)
throw std::runtime_error("scan command has no dependency file");
std::error_code error;
fs::create_directories(options.directory, error);
if (error)
throw std::runtime_error("cannot create the private scan directory");
const auto directory = options.directory / ("scan-" + unique_name());
fs::create_directory(directory, error);
if (error)
throw std::runtime_error("cannot create the private scan directory");
Cleanup cleanup{directory};
const auto selected = directory / "deps.json";
for (auto &argument : arguments)
if (argument.starts_with("-fdeps-file="))
argument = "-fdeps-file=" + selected.native();
Void::Process::SpawnOptions spawn;
spawn.executable = arguments.front();
spawn.arguments.assign(arguments.begin() + 1, arguments.end());
spawn.working_directory = command->working_directory;
spawn.search_path = false;
spawn.environment.set_vars = {{"LC_ALL", "C"}};
auto child = Void::Process::spawn(spawn);
if (!child)
throw std::runtime_error("could not start the module scanner");
auto received = Void::Process::communicate_blocking(*child, {},
{.max_stdout_bytes = options.max_bytes,
.max_stderr_bytes = max_error_bytes,
.max_line_bytes = max_error_bytes},
options.deadline, stop);
if (!received)
throw std::runtime_error("module scanner communication failed");
if (received->cancelled || stop.stop_requested())
throw std::runtime_error("module scan cancelled");
if (received->timed_out)
throw std::runtime_error("module scan timed out");
if (!received->status.exited || received->status.code != 0)
throw std::runtime_error("module scanner failed: " + received->err.substr(0, 512));
auto bytes = read_file(selected, options.max_bytes);
auto decoded = decode_scan(bytes, command->output);
if (!decoded)
throw std::runtime_error("module scan rule could not be verified");
product->p1689 = std::move(bytes);
product->rule = std::move(*decoded);
return command->output.spelling;
};
}
} // namespace vls::modules
+672
View File
@@ -0,0 +1,672 @@
#include <vls/modules/ModuleGraph.hpp>
#include <Void/LanguageServer/Protocol/Json.hpp>
#include <algorithm>
#include <initializer_list>
#include <map>
#include <set>
#include <type_traits>
#include <utility>
#include <variant>
namespace vls::modules {
namespace {
namespace P = Void::LanguageServer::Protocol;
using Object = P::Json::Object;
bool identifier(std::string_view value) { return !value.empty() && value.find('\0') == value.npos; }
bool valid_output(const ExpectedOutput &output) {
return output.working_directory.is_absolute() &&
!output.working_directory.native().contains(std::filesystem::path::value_type{}) &&
identifier(output.spelling);
}
// The helpers unwind only a typed wire error; the public decoder returns an expected.
const Object &object(const P::Json &value) {
if (const auto *fields = P::as_object(&value))
return *fields;
throw ScanError::invalid_shape;
}
// The parser first bounds raw bytes and nesting. Bound the decoded tree, including ignored
// vendor extensions, before constructing indices or copying module descriptions.
void check_tree(const P::Json &value, std::size_t &remaining) {
if (remaining == 0)
throw ScanError::limit;
--remaining;
if (const auto *string = P::as_string(&value)) {
if (string->size() > max_field_bytes)
throw ScanError::limit;
} else if (const auto *items = P::as_array(&value)) {
if (items->size() > max_rule_items)
throw ScanError::limit;
for (const auto &item : *items)
check_tree(item, remaining);
} else if (const auto *fields = P::as_object(&value)) {
if (fields->size() > max_rule_items)
throw ScanError::limit;
for (const auto &[key, item] : *fields) {
if (key.size() > max_field_bytes)
throw ScanError::limit;
check_tree(item, remaining);
}
}
}
void check_fields(const Object &fields, std::initializer_list<std::string_view> allowed) {
for (const auto &[key, value] : fields) {
if (!key.starts_with('_') && !std::ranges::contains(allowed, key))
throw ScanError::unsupported_field;
}
}
std::string_view text_field(const P::Json *field) {
const auto *value = P::as_string(field);
if (!value)
throw ScanError::invalid_shape;
if (!identifier(*value))
throw ScanError::invalid_shape;
return *value;
}
std::optional<std::string> optional_text(const Object &entry, std::string_view key) {
if (const auto *field = P::find_member(entry, key))
return std::string(text_field(field));
return {};
}
bool bool_field(const Object &entry, std::string_view key, bool fallback) {
const auto *field = P::find_member(entry, key);
if (!field)
return fallback;
if (const auto flag = P::as_bool(field))
return *flag;
throw ScanError::invalid_shape;
}
void zero_version(const Object &fields, std::string_view key, bool required) {
const auto *field = P::find_member(fields, key);
if (!field && !required)
return;
const auto *number = field ? std::get_if<std::int64_t>(&field->value) : nullptr;
if (!number)
throw ScanError::invalid_shape;
if (*number != 0)
throw ScanError::unsupported_version;
}
std::span<const P::Json> array_field(const Object &fields, std::string_view key) {
const auto *value = P::find_member(fields, key);
if (!value)
return {};
const auto *items = P::as_array(value);
if (!items)
throw ScanError::invalid_shape;
return *items;
}
template <class Entry> std::vector<Entry> descriptions(std::span<const P::Json> array) {
std::vector<Entry> result;
result.reserve(array.size());
for (const auto &item : array) {
const auto &fields = object(item);
constexpr bool providing = std::is_same_v<Entry, ProvidedModule>;
check_fields(fields,
{"logical-name", "unique-on-source-path", "source-path",
"compiled-module-path", providing ? "is-interface" : "lookup-method"});
Entry entry;
entry.logical_name = text_field(P::find_member(fields, "logical-name"));
entry.source_path = optional_text(fields, "source-path");
entry.compiled_module_path = optional_text(fields, "compiled-module-path");
entry.unique_on_source_path = bool_field(fields, "unique-on-source-path", false);
if (entry.unique_on_source_path && !entry.source_path)
throw ScanError::invalid_shape;
if constexpr (providing) {
entry.is_interface = bool_field(fields, "is-interface", true);
} else if (const auto *field = P::find_member(fields, "lookup-method")) {
const auto method = text_field(field);
if (method == "include-angle")
entry.lookup = LookupMethod::include_angle;
else if (method == "include-quote")
entry.lookup = LookupMethod::include_quote;
else if (method != "by-name")
throw ScanError::unsupported_field;
}
result.push_back(std::move(entry));
}
// Keep scanner order for external occurrence bindings. Compare through indices.
std::set<const Entry *, decltype([](const Entry *a, const Entry *b) { return *a < *b; })> seen;
for (const auto &entry : result)
if (!seen.insert(&entry).second)
throw ScanError::invalid_shape;
return result;
}
// Keep non-ASCII bytes of the compiler's UTF-8 name opaque. This check excludes path-like
// spellings from named lookup. The owner separately certifies all header provisions and uses,
// including headers whose spelling could also be a valid module name.
bool named_module(std::string_view name) {
bool start = true, partition = false;
for (const unsigned char ch : name) {
if (ch == '.' || ch == ':') {
if (start || (ch == ':' && partition))
return false;
partition |= ch == ':';
start = true;
} else {
const bool name_byte =
(ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == '_' || ch >= 0x80;
if (!name_byte && (start || ch < '0' || ch > '9'))
return false;
start = false;
}
}
return !start;
}
// Account caller-owned evidence before copying or indexing any of it. Wire objects have
// already passed the decoder's per-array and field bounds.
struct GraphLimit {};
struct Budget {
std::size_t bytes{}, items{};
void add_bytes(std::size_t n) {
if (n > max_graph_bytes - bytes)
throw GraphLimit{};
bytes += n;
}
void add_items(std::size_t n) {
if (n > max_graph_items - items)
throw GraphLimit{};
items += n;
}
void field(std::size_t n) {
if (n > max_field_bytes)
throw GraphLimit{};
add_bytes(n);
}
void optional(const std::optional<std::string> &value) {
if (value)
field(value->size());
}
void domain(const ModuleDomain &value) {
field(value.compatibility.size());
field(value.lookup.size());
}
void context(const Build::ContextKey &key) {
optional(key.profile);
optional(key.target);
field(key.alternative.size());
field(key.owning_tu.native().size());
}
void inputs(const UnitInputs &value) {
field(value.command.size());
field(value.source.size());
field(value.textual_closure.size());
optional(value.system_closure);
}
void member(const CensusMember &value) {
context(value.context);
inputs(value.inputs);
field(value.output.working_directory.native().size());
field(value.output.spelling.size());
field(value.scan_revision.size());
if (const auto &header = value.staged_header) {
field(header->generation.size());
field(header->source_identity.size());
domain(header->domain);
context(header->producer);
inputs(header->inputs);
}
}
void scan(const ScanEvidence &value) {
domain(value.domain);
context(value.context);
inputs(value.inputs);
field(value.scan_revision.size());
if (value.rule && *value.rule) {
const auto &rule = **value.rule;
add_bytes(rule.wire_bytes());
add_items(rule.additional_outputs().size() + rule.provides().size() +
rule.requirements().size());
}
if (value.provided_headers.size() > max_rule_items ||
value.writers.size() > max_rule_items + 1 ||
(value.header_uses && value.header_uses->size() > max_rule_items))
throw GraphLimit{};
add_items(value.provided_headers.size());
add_items(value.writers.size());
for (const auto &provision : value.provided_headers)
field(provision.source_identity.size());
for (const auto &writer : value.writers)
field(writer.size());
if (value.header_uses) {
add_items(value.header_uses->size());
for (const auto &use : *value.header_uses) {
field(use.source_identity.size());
optional(use.loaded_generation);
}
}
}
};
using Index = std::size_t;
using Context = Build::ContextKey;
using Claim = std::pair<bool, std::string_view>; // Resolved header identity, or named module.
struct Provider {
Index first;
bool ambiguous{};
};
struct Node {
const ScanEvidence *scan{};
bool foreign{}, duplicate{};
std::vector<const HeaderProvision *> provisions;
std::vector<const HeaderUse *> imports;
std::vector<Index> dependencies;
std::vector<Blocker> issues;
};
class Planner {
public:
ModulePlan plan;
void collect(const ModuleCensus &, std::span<const ScanEvidence>, const Context &);
private:
std::vector<Node> nodes_;
std::map<Claim, Provider> providers_;
std::map<std::string_view, Index> writers_;
void block(PlanIssue code, std::optional<Index> unit = {}, std::string_view detail = {},
std::optional<ScanError> error = {}) {
plan.blockers.push_back({code, unit, std::string(detail), error});
}
void local(Index unit, PlanIssue issue, std::string_view detail) {
nodes_[unit].issues.push_back({issue, unit, std::string(detail), {}});
}
void index_scan(Index);
void index_claims(Index, const ScanRule &);
void link_imports(Index);
void order_from(Index);
};
// Bind using the exact positions in this (owned, decoded) rule. Multiple spellings of one
// resolved header may occupy distinct positions, but a position may have only one binding.
template <class Binding>
bool bind_indices(const std::vector<Binding> &bindings, std::vector<const Binding *> &slots,
std::size_t count) {
slots.assign(count, nullptr);
for (const auto &entry : bindings) {
if (entry.index >= count || slots[entry.index] || !identifier(entry.source_identity))
return false;
slots[entry.index] = &entry;
}
return true;
}
void Planner::index_scan(Index i) {
const auto &member = plan.units[i].member;
const auto &node = nodes_[i];
if (member.inputs.source.empty())
block(PlanIssue::missing_source, i);
if (!identifier(member.inputs.source) || !identifier(member.inputs.command) ||
!identifier(member.inputs.textual_closure) || !identifier(member.scan_revision) ||
(member.inputs.system_closure && !identifier(*member.inputs.system_closure)))
block(PlanIssue::incomplete_inputs, i);
if (!node.scan) {
block(node.foreign ? PlanIssue::wrong_domain : PlanIssue::missing_scan, i);
return;
}
if (node.duplicate) {
block(PlanIssue::duplicate_scan, i);
return;
}
const auto &scan = *node.scan;
if (scan.inputs != member.inputs || scan.scan_revision != member.scan_revision)
block(PlanIssue::stale_scan, i);
if (!scan.exit_status)
block(PlanIssue::incomplete_scan, i, "unobserved compiler exit");
else if (*scan.exit_status != 0)
block(PlanIssue::scan_failed, i);
if (!scan.rule) {
block(PlanIssue::missing_rule, i);
return;
}
if (!*scan.rule) {
block(PlanIssue::invalid_rule, i, {}, scan.rule->error());
return;
}
const auto &rule = **scan.rule;
if (rule.output() != member.output || !valid_output(member.output))
block(PlanIssue::stale_scan, i);
if (!scan.complete || !scan.header_uses ||
(scan.method != ScanMethod::preprocess_md && scan.method != ScanMethod::preprocess_mmd &&
scan.method != ScanMethod::missing_allowed))
block(PlanIssue::incomplete_scan, i);
if (scan.method == ScanMethod::preprocess_mmd && !member.inputs.system_closure)
block(PlanIssue::incomplete_inputs, i);
if (!bind_indices(scan.provided_headers, nodes_[i].provisions, rule.provides().size()) ||
!scan.header_uses ||
!bind_indices(*scan.header_uses, nodes_[i].imports, rule.requirements().size())) {
block(PlanIssue::unproven_mapping, i);
return;
}
// One invocation has one immutable filesystem view. Two identical source-path spellings
// in that invocation cannot bind to different header sources. Other invocations may have
// different views even when their printed paths match.
std::map<std::string_view, std::string_view> header_paths;
auto bind_source = [&](const ModuleDescription &entry, std::string_view identity) {
if (!entry.source_path)
return;
const auto [it, inserted] = header_paths.emplace(*entry.source_path, identity);
if (!inserted && it->second != identity)
block(PlanIssue::unproven_mapping, i, *entry.source_path);
};
for (const auto &header : scan.provided_headers)
bind_source(rule.provides()[header.index], header.source_identity);
for (const auto &use : *scan.header_uses)
bind_source(rule.requirements()[use.index], use.source_identity);
if (scan.writers.size() != rule.additional_outputs().size() + 1) {
block(PlanIssue::unproven_mapping, i, "output identities");
} else {
for (const auto &writer : scan.writers) {
if (!identifier(writer)) {
block(PlanIssue::unproven_mapping, i, "output identity");
continue;
}
const auto [it, inserted] = writers_.emplace(writer, i);
if (!inserted) {
local(i, PlanIssue::writer_collision, writer);
local(it->second, PlanIssue::writer_collision, writer);
}
}
}
index_claims(i, rule);
}
void Planner::index_claims(Index i, const ScanRule &rule) {
const auto &node = nodes_[i];
auto &kind = plan.units[i].kind;
const auto explicit_kind = node.scan->import_only_kind;
if (explicit_kind != UnitKind::unknown) {
if (rule.provides().empty() &&
(explicit_kind == UnitKind::ordinary || explicit_kind == UnitKind::implementation))
kind = explicit_kind;
else
block(PlanIssue::unproven_mapping, i, "unit kind");
}
for (Index j = 0; j < rule.provides().size(); ++j) {
const auto &entry = rule.provides()[j];
const auto *header = node.provisions[j];
if (entry.compiled_module_path ||
(!header && (entry.source_path || !named_module(entry.logical_name) ||
(!entry.is_interface && !entry.logical_name.contains(':'))))) {
block(PlanIssue::unproven_mapping, i, entry.logical_name);
continue;
}
const Claim key{header != nullptr, header ? header->source_identity : entry.logical_name};
const auto [it, inserted] = providers_.emplace(key, Provider{i});
if (!inserted && (it->second.first != i || !header)) {
it->second.ambiguous = true;
local(i, PlanIssue::duplicate_provider, key.second);
local(it->second.first, PlanIssue::duplicate_provider, key.second);
}
if (rule.provides().size() == 1) {
if (header)
kind = UnitKind::header_unit;
else if (entry.logical_name.contains(':'))
kind = entry.is_interface ? UnitKind::interface_partition
: UnitKind::internal_partition;
else if (entry.is_interface)
kind = UnitKind::primary_interface;
}
}
}
void Planner::link_imports(Index i) {
auto &node = nodes_[i];
const auto &requirements = (**node.scan->rule).requirements();
for (Index j = 0; j < requirements.size(); ++j) {
const auto &entry = requirements[j];
const auto *use = node.imports[j];
if (entry.compiled_module_path ||
(!use && (entry.source_path || entry.lookup != LookupMethod::by_name ||
!named_module(entry.logical_name)))) {
// An unbound header lookup may have hidden macro-dependent claims in this scan.
block(PlanIssue::unproven_mapping, i, entry.logical_name);
continue;
}
const Claim key{use != nullptr, use ? use->source_identity : entry.logical_name};
const auto provider = providers_.find(key);
if (provider == providers_.end()) {
local(i, PlanIssue::missing_provider, key.second);
if (use)
block(PlanIssue::incomplete_scan, i, key.second);
continue;
}
if (provider->second.ambiguous) {
local(i, PlanIssue::duplicate_provider, key.second);
if (use)
block(PlanIssue::incomplete_scan, i, key.second);
continue;
}
const auto dependency = provider->second.first;
node.dependencies.push_back(dependency);
if (use) {
const auto &member = plan.units[dependency].member;
const auto &staged = member.staged_header;
if (!use->loaded_generation || !identifier(*use->loaded_generation) || !staged ||
staged->generation != *use->loaded_generation ||
staged->source_identity != use->source_identity || staged->domain != plan.domain ||
staged->producer != member.context || staged->inputs != member.inputs)
block(PlanIssue::stale_header, i, key.second);
}
}
auto &dependencies = node.dependencies;
std::ranges::sort(dependencies);
dependencies.erase(std::unique(dependencies.begin(), dependencies.end()), dependencies.end());
for (const auto dependency : dependencies)
plan.units[dependency].consumers.push_back(i);
}
void Planner::order_from(Index requested) {
enum class Mark { unseen, visiting, finished };
struct Frame {
Index unit, next{};
};
std::vector<Mark> marks(nodes_.size(), Mark::unseen);
std::vector<Frame> stack;
auto enter = [&](Index unit) {
marks[unit] = Mark::visiting;
stack.push_back({unit});
const auto &issues = nodes_[unit].issues;
plan.blockers.insert(plan.blockers.end(), issues.begin(), issues.end());
};
enter(requested);
while (!stack.empty()) {
auto &frame = stack.back();
const auto &dependencies = nodes_[frame.unit].dependencies;
if (frame.next == dependencies.size()) {
marks[frame.unit] = Mark::finished;
plan.order.push_back(plan.units[frame.unit].member.context);
stack.pop_back();
continue;
}
const auto next = dependencies[frame.next++];
if (marks[next] == Mark::unseen)
enter(next);
else if (marks[next] == Mark::visiting)
block(PlanIssue::cycle, next);
}
if (!plan.blockers.empty())
plan.order.clear();
}
void Planner::collect(const ModuleCensus &census, std::span<const ScanEvidence> scans,
const Context &requested) {
if (census.members.size() > max_units || scans.size() > max_units)
throw GraphLimit{};
Budget budget;
budget.domain(census.domain);
budget.field(census.revision.size());
budget.context(requested);
for (const auto &member : census.members)
budget.member(member);
for (const auto &scan : scans)
budget.scan(scan);
if (!census.closed || !identifier(census.revision) || !census.domain.generation ||
!identifier(census.domain.compatibility) || !identifier(census.domain.lookup)) {
block(PlanIssue::incomplete_census);
return;
}
plan.domain = census.domain;
plan.census_revision = census.revision;
plan.units.reserve(census.members.size());
for (const auto &member : census.members)
plan.units.push_back({member, UnitKind::unknown, {}});
std::ranges::sort(plan.units, {},
[](const auto &unit) -> const Context & { return unit.member.context; });
std::map<Context, Index> ids;
for (Index i = 0; i < plan.units.size(); ++i) {
const auto &member = plan.units[i].member;
if (!ids.emplace(member.context, i).second)
block(PlanIssue::duplicate_member, i);
if (!plan.domain.generation->find(member.context))
block(PlanIssue::invalid_context, i);
}
const auto request = ids.find(requested);
if (request == ids.end())
block(PlanIssue::invalid_context);
if (!plan.blockers.empty())
return;
nodes_.resize(plan.units.size());
for (const auto &scan : scans) {
const auto id = ids.find(scan.context);
if (id == ids.end())
continue;
auto &node = nodes_[id->second];
if (scan.domain != census.domain)
node.foreign = true;
else if (node.scan)
node.duplicate = true;
else
node.scan = &scan;
}
// A failed or incomplete member may be another provider even if no positive edge leads
// to it. Check all claims before resolving the requested component.
for (Index i = 0; i < nodes_.size(); ++i)
index_scan(i);
if (plan.blockers.empty()) {
for (Index i = 0; i < nodes_.size(); ++i)
link_imports(i);
plan.claims_complete = plan.blockers.empty();
order_from(request->second);
}
if (!plan.claims_complete) {
for (auto &unit : plan.units) {
unit.kind = UnitKind::unknown;
unit.consumers.clear();
}
}
}
} // namespace
ScanResult decode_scan(std::string_view bytes, const ExpectedOutput &expected) {
if (bytes.size() > max_scan_bytes || expected.spelling.size() > max_field_bytes ||
expected.working_directory.native().size() > max_field_bytes)
return std::unexpected(ScanError::limit);
if (!valid_output(expected))
return std::unexpected(ScanError::invalid_invocation);
auto parsed = P::parse_json(bytes, max_scan_depth);
if (!parsed)
return std::unexpected(parsed.error() == "JSON nesting exceeds depth limit"
? ScanError::limit
: ScanError::invalid_json);
try {
std::size_t remaining = 16 * max_rule_items;
check_tree(*parsed, remaining);
const auto &envelope = object(*parsed);
zero_version(envelope, "version", true);
zero_version(envelope, "revision", false);
check_fields(envelope, {"version", "revision", "rules"});
const auto rules = array_field(envelope, "rules");
if (rules.size() != 1)
throw ScanError::invalid_shape;
const auto &fields = object(rules.front());
check_fields(fields,
{"work-directory", "primary-output", "outputs", "provides", "requires"});
if (const auto cwd = optional_text(fields, "work-directory");
cwd && *cwd != expected.working_directory.string())
throw ScanError::wrong_directory;
if (text_field(P::find_member(fields, "primary-output")) != expected.spelling)
throw ScanError::wrong_output;
const auto outputs = array_field(fields, "outputs");
const auto provides = array_field(fields, "provides");
const auto requirements = array_field(fields, "requires");
if (outputs.size() + provides.size() + requirements.size() > max_rule_items)
throw ScanError::limit;
ScanRule rule;
rule.output_ = expected;
rule.wire_bytes_ = bytes.size();
std::set<std::string_view> seen{expected.spelling};
for (const auto &output : outputs) {
const auto path = text_field(&output);
if (!seen.insert(path).second)
throw ScanError::invalid_shape;
rule.additional_outputs_.emplace_back(path);
}
rule.provides_ = descriptions<ProvidedModule>(provides);
rule.requirements_ = descriptions<RequiredModule>(requirements);
return rule;
} catch (ScanError error) {
return std::unexpected(error);
}
}
ModulePlan build_module_plan(const ModuleCensus &census, std::span<const ScanEvidence> scans,
const Context &requested) {
Planner planner;
try {
planner.collect(census, scans, requested);
} catch (const GraphLimit &) {
planner.plan = {};
planner.plan.blockers.push_back({PlanIssue::limit, {}, {}, {}});
}
auto &issues = planner.plan.blockers;
std::ranges::sort(issues);
issues.erase(std::unique(issues.begin(), issues.end()), issues.end());
return std::move(planner.plan);
}
bool ModulePlan::matches_census(const ModuleCensus &current) const {
if (!current.closed || units.empty() || units.size() > max_units ||
units.size() != current.members.size() || domain != current.domain ||
census_revision != current.revision)
return false;
Budget budget;
std::vector<bool> seen(units.size());
for (const auto &member : current.members) {
try {
budget.member(member);
} catch (const GraphLimit &) {
return false;
}
const auto it = std::ranges::lower_bound(
units, member.context, {},
[](const auto &unit) -> const Context & { return unit.member.context; });
if (it == units.end() || it->member != member)
return false;
const auto index = static_cast<Index>(it - units.begin());
if (seen[index])
return false;
seen[index] = true;
}
return true;
}
} // namespace vls::modules
+86
View File
@@ -0,0 +1,86 @@
#include <vls/modules/ModuleWorkQueue.hpp>
#include <utility>
namespace vls::modules {
namespace {
std::size_t slot(ModuleWorkKind kind) { return kind == ModuleWorkKind::scan ? 0 : 1; }
scheduler::Priority priority(ModuleWorkKind kind) {
return kind == ModuleWorkKind::scan ? scheduler::Priority::background
: scheduler::Priority::artifact;
}
} // namespace
ModuleWorkQueue::ModuleWorkQueue(scheduler::Scheduler &scheduler) : scheduler_(scheduler) {}
std::string ModuleWorkQueue::key(std::string_view document, ModuleWorkKind kind) {
return (kind == ModuleWorkKind::scan ? "scan:" : "artifact:") + std::string{document};
}
bool ModuleWorkQueue::submit(std::string document, ModuleWorkKind kind, std::uint64_t revision,
ModuleWork work, std::function<void(ModuleTaskResult)> completion) {
if (document.empty() || document.size() > 4096 || !work || revision == 0)
return false;
{
std::lock_guard lock{mutex_};
auto &latest = revisions_[slot(kind)][document];
if (revision <= latest)
return false;
latest = revision;
++counts_.submitted;
}
const auto task_key = key(document, kind);
const bool accepted = scheduler_.submit(
{.priority = priority(kind), .key = task_key, .revision = revision, .memory_mib = 1},
[work = std::move(work)](std::stop_token stop) { return work(stop); },
[this, document, kind, revision,
completion = std::move(completion)](scheduler::Result result) {
{
std::lock_guard lock{mutex_};
if (result.outcome == scheduler::Outcome::completed)
++counts_.completed;
else if (result.outcome == scheduler::Outcome::cancelled ||
result.outcome == scheduler::Outcome::timed_out)
++counts_.cancelled;
else
++counts_.failed;
}
if (completion)
completion(ModuleTaskResult{document, kind, revision, result.outcome,
std::move(result.detail)});
});
if (!accepted) {
std::lock_guard lock{mutex_};
if (revisions_[slot(kind)][document] == revision)
revisions_[slot(kind)].erase(document);
return false;
}
return true;
}
void ModuleWorkQueue::cancel(std::string_view document) {
if (document.empty())
return;
scheduler_.cancel(key(document, ModuleWorkKind::scan));
scheduler_.cancel(key(document, ModuleWorkKind::artifact));
}
void ModuleWorkQueue::cancel_all() {
std::map<std::string, std::uint64_t> revisions[2];
{
std::lock_guard lock{mutex_};
revisions[0] = revisions_[0];
revisions[1] = revisions_[1];
}
for (const auto &[document, revision] : revisions[0])
scheduler_.cancel(key(document, ModuleWorkKind::scan));
for (const auto &[document, revision] : revisions[1])
scheduler_.cancel(key(document, ModuleWorkKind::artifact));
}
ModuleWorkQueue::Counts ModuleWorkQueue::counts() const {
std::lock_guard lock{mutex_};
return counts_;
}
} // namespace vls::modules
+65
View File
@@ -0,0 +1,65 @@
#include <vls/modules/ScanCommand.hpp>
#include <string_view>
namespace vls::modules {
namespace {
bool takes_value(std::string_view option) {
return option == "-o" || option == "-MF" || option == "-MT" || option == "-MQ" ||
option == "-x";
}
bool removed(std::string_view option) {
return option == "-c" || option == "-E" || option == "-MD" || option == "-MMD" ||
option == "-M" || option == "-MM" || option == "-MG" || option == "-fsyntax-only" ||
option.starts_with("-fdiagnostics-") || option.starts_with("-fdeps-") ||
option.starts_with("-fmodule-");
}
} // namespace
std::expected<ScanInvocation, ScanCommandError>
build_scan_invocation(const Build::BuildContext &context, const ExpectedOutput &output,
const std::filesystem::path &dependency_file) {
if (!context.semantic_arguments || context.semantic_arguments->empty())
return std::unexpected{ScanCommandError::invalid_context};
if (!dependency_file.is_absolute())
return std::unexpected{ScanCommandError::relative_dependency_file};
const auto &source = context.key.owning_tu.native();
const auto &original = *context.semantic_arguments;
std::vector<std::string> arguments;
arguments.reserve(original.size() + 8);
arguments.push_back(original.front());
std::size_t sources{};
for (std::size_t index = 1; index < original.size(); ++index) {
const std::string_view argument = original[index];
if (argument == source) {
++sources;
continue;
}
if (removed(argument))
continue;
if (takes_value(argument)) {
if (index + 1 == original.size())
return std::unexpected{ScanCommandError::invalid_context};
++index;
continue;
}
if (argument.starts_with("-o") && argument.size() > 2)
continue;
if (argument.starts_with("-fdeps-") || argument.starts_with("-fmodule-"))
continue;
arguments.push_back(original[index]);
}
if (sources == 0)
return std::unexpected{ScanCommandError::missing_source};
if (sources != 1)
return std::unexpected{ScanCommandError::duplicate_source};
if (arguments.size() > 1000)
return std::unexpected{ScanCommandError::limit};
arguments.insert(arguments.end(),
{"-E", "-MD", "-fdeps-format=p1689r5",
"-fdeps-file=" + dependency_file.native(), "-fdeps-target=" + output.spelling,
"-o", "/dev/null", source});
return ScanInvocation{std::move(arguments)};
}
} // namespace vls::modules
+119
View File
@@ -0,0 +1,119 @@
#include <vls/modules/ScheduledArtifacts.hpp>
#include <algorithm>
#include <condition_variable>
#include <map>
#include <mutex>
#include <stdexcept>
#include <thread>
namespace vls::modules {
namespace fs = std::filesystem;
namespace {
using namespace std::chrono_literals;
struct Completion {
std::mutex mutex;
std::condition_variable changed;
bool done{};
scheduler::Outcome outcome{scheduler::Outcome::failed};
std::string detail;
};
std::string hex(std::string_view bytes) {
constexpr char digits[] = "0123456789abcdef";
std::string text;
for (const unsigned char byte : bytes) {
text += digits[byte >> 4];
text += digits[byte & 0xf];
}
return text;
}
struct Cleanup {
fs::path path;
~Cleanup() {
std::error_code error;
fs::remove_all(path, error);
}
};
} // namespace
std::expected<std::shared_ptr<const ArtifactGeneration>, std::string>
produce_module_artifacts_scheduled(const ModulePlan &plan, ArtifactCache &cache,
const fs::path &staging, ArtifactWork work,
scheduler::Scheduler &scheduler, std::stop_token stop) {
try {
if (!plan.ready())
return std::unexpected("module plan is not ready");
if (!work)
return std::unexpected("no artifact work");
std::error_code error;
fs::remove_all(staging, error);
fs::create_directories(staging);
Cleanup cleanup{staging};
std::map<ArtifactKey, fs::path> artifacts;
std::uint64_t revision{};
for (const auto &key : plan.order) {
if (stop.stop_requested())
return std::unexpected("artifact production cancelled");
const auto unit = std::ranges::find_if(plan.units, [&](const auto &candidate) {
return candidate.member.context.alternative == key.alternative;
});
if (unit == plan.units.end())
return std::unexpected("planned unit is missing from the census");
const auto output = staging / hex(key.alternative);
auto completion = std::make_shared<Completion>();
const bool accepted = scheduler.submit(
{.priority = scheduler::Priority::artifact,
.key = key.alternative,
.revision = ++revision,
.memory_mib = 1},
[&work, key, output](std::stop_token token) {
auto produced = work(token, key, output);
if (!produced)
throw std::runtime_error(produced.error());
return produced->native();
},
[completion](scheduler::Result result) {
std::lock_guard lock{completion->mutex};
completion->done = true;
completion->outcome = result.outcome;
completion->detail = std::move(result.detail);
completion->changed.notify_all();
});
if (!accepted)
return std::unexpected("module artifact admission was refused");
std::unique_lock lock{completion->mutex};
while (!completion->done && !stop.stop_requested())
completion->changed.wait_for(lock, 50ms);
const bool done = completion->done;
const auto outcome = completion->outcome;
const auto detail = completion->detail;
lock.unlock();
if (!done || stop.stop_requested()) {
scheduler.cancel(key.alternative);
return std::unexpected("artifact production cancelled");
}
if (outcome == scheduler::Outcome::cancelled ||
outcome == scheduler::Outcome::timed_out)
return std::unexpected("artifact production cancelled");
if (outcome != scheduler::Outcome::completed)
return std::unexpected("module artifact failed: " + detail);
if (!fs::is_regular_file(output, error) || error)
return std::unexpected("artifact work produced no regular file");
const auto &inputs = unit->member.inputs;
ArtifactKey artifact{plan.domain.compatibility, key.alternative,
inputs.command + "|" + inputs.source + "|" +
inputs.textual_closure + "|" +
inputs.system_closure.value_or(""),
"cmi"};
artifacts.emplace(std::move(artifact), output);
}
return cache.publish(artifacts);
} catch (const std::exception &error) {
return std::unexpected(error.what());
}
}
} // namespace vls::modules
+132
View File
@@ -0,0 +1,132 @@
#include <vls/navigation/Navigation.hpp>
#include <algorithm>
#include <set>
#include <tuple>
namespace vls::navigation {
namespace {
bool contains(const Range &range, Position position) {
return range.start <= position && position <= range.end;
}
bool identifier(std::string_view name) {
if (name.empty() || name.size() > 256)
return false;
for (std::size_t index = 0; index != name.size(); ++index) {
const char c = name[index];
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' ||
(index && c >= '0' && c <= '9')))
return false;
}
return true;
}
bool generated(std::string_view name) {
return name.contains('$') || name.starts_with("_GLOBAL__") || name.contains('<');
}
} // namespace
std::expected<Binding, Refusal> binding_at(const FactSet &set, std::string_view path,
Position position) {
std::set<Binding> candidates;
for (const auto &fact : set.facts)
if (fact.source == path && contains(fact.use, position))
candidates.insert(fact.binding);
if (candidates.empty())
return std::unexpected{Refusal::unknown_binding};
if (candidates.size() != 1)
return std::unexpected{Refusal::ambiguous_binding};
return *candidates.begin();
}
References references(const FactSet &set, const Binding &binding, std::size_t limit) {
References result;
std::set<Location> unique;
for (const auto &fact : set.facts)
if (fact.binding == binding)
unique.insert(Location{fact.source, fact.use});
for (const auto &location : unique) {
if (result.locations.size() == limit) {
result.truncated = true;
break;
}
result.locations.push_back(location);
}
for (const auto &context : set.contexts)
if (!context.complete)
result.incomplete_contexts.push_back(context.context);
std::ranges::sort(result.incomplete_contexts);
result.coverage_complete = result.incomplete_contexts.empty();
return result;
}
RenamePlan prepare_rename(const FactSet &set, std::string_view path, Position position,
std::string_view replacement, bool transactional_client) {
RenamePlan plan;
const auto binding = binding_at(set, path, position);
if (!binding) {
plan.refusal = binding.error();
plan.detail = "no unique binding at the requested position";
return plan;
}
if (!identifier(replacement)) {
plan.refusal = Refusal::invalid_name;
plan.detail = "the replacement is not a plain identifier";
return plan;
}
if (generated(replacement)) {
plan.refusal = Refusal::generated_name;
plan.detail = "the replacement looks like a generated name";
return plan;
}
if (replacement == binding->name) {
plan.refusal = Refusal::unchanged_name;
plan.detail = "the replacement equals the current spelling";
return plan;
}
for (const auto &context : set.contexts)
if (!context.complete) {
plan.refusal = Refusal::incomplete_coverage;
plan.detail = "incomplete analysis coverage in " + context.context +
(context.reason.empty() ? "" : ": " + context.reason);
return plan;
}
std::set<std::pair<std::string, Range>> seen;
std::set<std::string> files;
for (const auto &fact : set.facts) {
if (fact.binding != *binding)
continue;
if (const auto current = set.current_sources.find(fact.source);
current != set.current_sources.end() && current->second != fact.content) {
plan.refusal = Refusal::stale_source;
plan.detail = "the source changed after analysis: " + fact.source;
return plan;
}
if (!fact.editable) {
plan.refusal = Refusal::non_editable_origin;
plan.detail = "the binding has a non-editable origin: " + fact.source;
return plan;
}
if (seen.emplace(fact.source, fact.use).second) {
files.insert(fact.source);
plan.edits.push_back({fact.source, fact.use, std::string{replacement}, fact.content});
}
}
if (plan.edits.empty()) {
plan.refusal = Refusal::unknown_binding;
plan.detail = "the binding has no proven occurrence";
return plan;
}
if (files.size() > 1 && !transactional_client) {
plan.refusal = Refusal::multi_file_without_transaction;
plan.detail = "multi-file rename requires a transactional client";
return plan;
}
std::ranges::sort(plan.edits, [](const auto &left, const auto &right) {
return std::tie(left.path, left.range) < std::tie(right.path, right.range);
});
return plan;
}
} // namespace vls::navigation
+541
View File
@@ -0,0 +1,541 @@
#include <vls/reflection/Provenance.hpp>
#include <Void/LanguageServer/Protocol/Json.hpp>
#include <algorithm>
#include <ranges>
#include <set>
#include <utility>
namespace vls::reflection {
namespace P = Void::LanguageServer::Protocol;
using Json = P::Json;
namespace {
std::string_view origin_name(OriginKind kind) {
switch (kind) {
case OriginKind::spelling:
return "spelling";
case OriginKind::expansion:
return "expansion";
case OriginKind::splice:
return "splice";
case OriginKind::reflected_declaration:
return "reflectedDeclaration";
case OriginKind::synthesized:
return "synthesized";
}
return "synthesized";
}
std::optional<OriginKind> origin_kind(std::string_view name) {
for (const auto kind : {OriginKind::spelling, OriginKind::expansion, OriginKind::splice,
OriginKind::reflected_declaration, OriginKind::synthesized})
if (origin_name(kind) == name)
return kind;
return std::nullopt;
}
std::string_view value_name(ValueKind kind) {
switch (kind) {
case ValueKind::integral:
return "integral";
case ValueKind::text:
return "text";
case ValueKind::boolean:
return "boolean";
case ValueKind::entity:
return "entity";
case ValueKind::opaque:
return "opaque";
case ValueKind::unavailable:
return "unavailable";
}
return "unavailable";
}
std::optional<ValueKind> value_kind(std::string_view name) {
for (const auto kind : {ValueKind::integral, ValueKind::text, ValueKind::boolean,
ValueKind::entity, ValueKind::opaque, ValueKind::unavailable})
if (value_name(kind) == name)
return kind;
return std::nullopt;
}
std::optional<Range> source_link(const Provenance &provenance) {
for (const auto &origin : provenance.origins)
if (origin.range)
return origin.range;
return std::nullopt;
}
Json range_json(const Range &range) {
return Json{Json::Object{{"path", Json{range.path}},
{"line", Json{std::int64_t{range.line}}},
{"character", Json{std::int64_t{range.character}}},
{"endLine", Json{std::int64_t{range.endLine}}},
{"endCharacter", Json{std::int64_t{range.endCharacter}}}}};
}
std::expected<Range, std::string> parse_range(const Json *value) {
const auto *fields = P::as_object(value);
if (!fields)
return std::unexpected("reflection range is not an object");
const auto *path = P::as_string(P::find_member(*fields, "path"));
const auto line = P::as_uint32(P::find_member(*fields, "line"));
const auto character = P::as_uint32(P::find_member(*fields, "character"));
const auto end_line = P::as_uint32(P::find_member(*fields, "endLine"));
const auto end_character = P::as_uint32(P::find_member(*fields, "endCharacter"));
if (!path || !line || !character || !end_line || !end_character)
return std::unexpected("reflection range is incomplete");
return Range{*path, *line, *character, *end_line, *end_character};
}
Json provenance_json(const Provenance &provenance) {
Json::Array origins;
for (const auto &origin : provenance.origins) {
Json::Object fields{{"kind", Json{std::string{origin_name(origin.kind)}}},
{"note", Json{origin.note}},
{"range", origin.range ? range_json(*origin.range) : Json{}},
{"entity", origin.entity ? Json{*origin.entity} : Json{}}};
origins.push_back(Json{std::move(fields)});
}
return Json{Json::Object{{"origins", Json{std::move(origins)}},
{"gap", Json{provenance.gap}},
{"context", Json{provenance.context}}}};
}
Json value_json(const Value &value) {
return Json{Json::Object{{"kind", Json{std::string{value_name(value.kind)}}},
{"integral", Json{value.integral}},
{"boolean", Json{value.boolean}},
{"text", Json{value.text}},
{"type", Json{value.type}},
{"entity", Json{value.entity}}}};
}
Json entity_json(const Entity &entity) {
Json::Array members;
for (const auto &member : entity.members)
members.push_back(
Json{Json::Object{{"name", Json{member.name}}, {"value", value_json(member.value)}}});
return Json{Json::Object{{"id", Json{entity.id}},
{"name", Json{entity.name}},
{"type", Json{entity.type}},
{"synthesized", Json{entity.synthesized}},
{"provenance", provenance_json(entity.provenance)},
{"members", Json{std::move(members)}}}};
}
} // namespace
bool Provenance::navigable() const {
return std::ranges::any_of(origins,
[](const Origin &origin) { return origin.range.has_value(); });
}
bool Provenance::editable() const {
if (gap || origins.empty())
return false;
if (origins.front().kind != OriginKind::spelling || !origins.front().range)
return false;
return std::ranges::none_of(
origins, [](const Origin &origin) { return origin.kind == OriginKind::synthesized; });
}
Snapshot::Snapshot(Limits limits) : limits_(limits) {}
bool Snapshot::add(Entity entity) {
if (entities_.size() >= limits_.entities || entity.id.empty())
return false;
if (entity.id.size() > limits_.nameBytes || entity.name.size() > limits_.nameBytes ||
entity.type.size() > limits_.typeBytes ||
entity.provenance.context.size() > limits_.contextBytes ||
entity.provenance.origins.size() > limits_.originsPerProvenance ||
entity.members.size() > limits_.membersPerEntity)
return false;
for (const auto &origin : entity.provenance.origins)
if (origin.note.size() > limits_.textBytes ||
(origin.range && origin.range->path.size() > limits_.nameBytes))
return false;
for (const auto &member : entity.members) {
if (member.name.size() > limits_.nameBytes ||
member.value.type.size() > limits_.typeBytes ||
member.value.text.size() > limits_.textBytes ||
member.value.entity.size() > limits_.nameBytes)
return false;
}
if (contains(entity.id))
return false;
entities_.push_back(std::move(entity));
return true;
}
bool Snapshot::contains(const EntityId &id) const {
return std::ranges::any_of(entities_, [&id](const Entity &entity) { return entity.id == id; });
}
const Entity *Snapshot::find(const EntityId &id) const {
const auto found =
std::ranges::find_if(entities_, [&id](const Entity &entity) { return entity.id == id; });
return found == entities_.end() ? nullptr : &*found;
}
const std::vector<Entity> &Snapshot::entities() const noexcept { return entities_; }
std::size_t Snapshot::size() const { return entities_.size(); }
const Limits &Snapshot::limits() const noexcept { return limits_; }
std::expected<Expansion, std::string> Snapshot::expand(const EntityId &root,
std::optional<std::size_t> depth) const {
const auto *entity = find(root);
if (!entity)
return std::unexpected("unknown reflection entity");
const std::size_t max_depth = depth.value_or(limits_.expansionDepth);
Expansion result;
std::vector<EntityId> path{root};
bool stopped{};
const auto walk = [&](const auto &self, const Entity &current, const std::string &prefix,
std::size_t level) -> void {
for (const auto &member : current.members) {
if (stopped)
return;
const std::string member_path =
prefix.empty() ? member.name : prefix + "." + member.name;
if (result.entries.size() >= limits_.expansionValues) {
result.truncated.push_back(member_path);
stopped = true;
return;
}
Expansion::Entry entry;
entry.path = member_path;
entry.depth = level;
entry.kind = member.value.kind;
entry.type = member.value.type;
entry.entity = member.value.entity;
switch (member.value.kind) {
case ValueKind::integral:
entry.text = std::to_string(member.value.integral);
break;
case ValueKind::boolean:
entry.text = member.value.boolean ? "true" : "false";
break;
default:
entry.text = member.value.text;
break;
}
result.entries.push_back(std::move(entry));
if (member.value.kind != ValueKind::entity)
continue;
if (std::ranges::find(path, member.value.entity) != path.end()) {
result.cycles.push_back(member_path);
continue;
}
const auto *next = find(member.value.entity);
if (!next) {
result.entries.back().kind = ValueKind::unavailable;
result.entries.back().text = "entity is not in this snapshot";
continue;
}
result.entries.back().link = source_link(next->provenance);
if (level >= max_depth) {
result.truncated.push_back(member_path);
continue;
}
path.push_back(member.value.entity);
self(self, *next, member_path, level + 1);
path.pop_back();
}
};
walk(walk, *entity, {}, 1);
return result;
}
VirtualView render(const Entity &entity, const Expansion &expansion, const Limits &limits) {
VirtualView view;
const std::size_t max_lines = limits.expansionValues + 1;
std::string header = entity.name.empty() ? std::string{"<unnamed>"} : entity.name;
header += " : ";
header += entity.type.empty() ? std::string{"<unknown>"} : entity.type;
if (entity.synthesized)
header += " [generated]";
if (entity.provenance.gap)
header += " [origin unavailable]";
if (header.size() > limits.textBytes)
header.resize(limits.textBytes);
view.lines.push_back(
VirtualLine{.text = std::move(header), .depth = 0, .link = source_link(entity.provenance)});
for (const auto &entry : expansion.entries) {
if (view.lines.size() >= max_lines) {
view.truncated = true;
break;
}
const auto separator = entry.path.rfind('.');
const auto name =
separator == std::string::npos ? entry.path : entry.path.substr(separator + 1);
std::string text(2 * std::min<std::size_t>(entry.depth, 32), ' ');
text += name;
if (!entry.type.empty())
text += " : " + entry.type;
if (entry.kind == ValueKind::entity)
text += " = <entity " + entry.entity + ">";
else if (!entry.text.empty())
text += " = " + entry.text;
else if (entry.kind == ValueKind::opaque || entry.kind == ValueKind::unavailable)
text += " = <unavailable>";
if (text.size() > limits.textBytes)
text.resize(limits.textBytes);
view.lines.push_back(
VirtualLine{.text = std::move(text), .depth = entry.depth, .link = entry.link});
}
for (const auto &path : expansion.cycles) {
if (view.lines.size() >= max_lines) {
view.truncated = true;
break;
}
view.lines.push_back(VirtualLine{.text = "! cycle: " + path + " repeats on this path",
.depth = 0,
.link = std::nullopt});
}
for (const auto &path : expansion.truncated) {
if (view.lines.size() >= max_lines) {
view.truncated = true;
break;
}
view.lines.push_back(
VirtualLine{.text = "! truncated: " + path, .depth = 0, .link = std::nullopt});
}
return view;
}
std::vector<Range> locations(const Provenance &provenance, std::size_t limit) {
std::vector<Range> result;
for (const auto &origin : provenance.origins) {
if (!origin.range || result.size() >= limit)
continue;
if (std::ranges::find(result, *origin.range) == result.end())
result.push_back(*origin.range);
}
return result;
}
Hover hover(const Entity &entity, const Expansion &expansion, const Limits &limits) {
const auto view = render(entity, expansion, limits);
Hover result;
result.markup = "```text\n";
for (const auto &line : view.lines) {
result.markup += line.text;
result.markup += "\n";
}
result.markup += "```\n";
const auto links = locations(entity.provenance, 8);
if (!links.empty()) {
result.markup += "\nSources:\n";
for (const auto &link : links)
result.markup += "- `" + link.path + ":" + std::to_string(link.line) + ":" +
std::to_string(link.character) + "`\n";
}
if (!entity.provenance.origins.empty() && entity.provenance.origins.front().range)
result.range = entity.provenance.origins.front().range;
return result;
}
Snapshot snapshot_from_splices(std::span<const SpliceOrigin> splices, Limits limits) {
Snapshot snapshot{limits};
const auto range_at = [](std::string_view path, std::uint32_t line, std::uint32_t column) {
return Range{std::string{path}, line, column, line, column};
};
for (const auto &splice : splices) {
if (splice.source.empty() || splice.line == 0 || splice.byteColumn == 0)
continue;
const bool located =
!splice.targetSource.empty() && splice.targetLine && splice.targetByteColumn;
std::string id = "gcc:";
id += splice.targetKind.empty() ? "value" : splice.targetKind;
id += ":";
id += splice.targetName.empty() ? "<anonymous>" : splice.targetName;
id += "@";
if (located)
id += splice.targetSource + ":" + std::to_string(*splice.targetLine) + ":" +
std::to_string(*splice.targetByteColumn);
else
id += splice.source + ":" + std::to_string(splice.line) + ":" +
std::to_string(splice.byteColumn);
if (snapshot.contains(id))
continue;
Entity entity;
entity.id = id;
entity.name = splice.targetName.empty() ? "<value>" : splice.targetName;
entity.synthesized = !located;
entity.provenance.context = "gcc-splice";
entity.provenance.origins.push_back(
Origin{.kind = OriginKind::splice,
.range = range_at(splice.source, splice.line, splice.byteColumn),
.entity = id,
.note = "splice site"});
if (located)
entity.provenance.origins.push_back(
Origin{.kind = OriginKind::reflected_declaration,
.range = range_at(splice.targetSource, *splice.targetLine,
*splice.targetByteColumn),
.entity = id,
.note = splice.targetKind});
else
entity.provenance.gap = true;
if (!snapshot.add(std::move(entity)))
break;
}
return snapshot;
}
std::expected<std::string, std::string> Snapshot::serialize() const {
std::vector<const Entity *> ordered;
ordered.reserve(entities_.size());
for (const auto &entity : entities_)
ordered.push_back(&entity);
std::ranges::sort(ordered,
[](const Entity *left, const Entity *right) { return left->id < right->id; });
Json::Array entities;
for (const auto *entity : ordered)
entities.push_back(entity_json(*entity));
const Json root{Json::Object{{"schema", Json{std::int64_t{schema_version}}},
{"entities", Json{std::move(entities)}}}};
auto encoded = P::serialize_json(root);
if (!encoded)
return std::unexpected(encoded.error());
if (encoded->size() > limits_.snapshotBytes)
return std::unexpected("reflection snapshot exceeds its byte bound");
return encoded;
}
std::expected<Snapshot, std::string> Snapshot::parse(std::string_view bytes, Limits limits) {
if (bytes.size() > limits.snapshotBytes)
return std::unexpected("reflection snapshot exceeds its byte bound");
auto parsed = P::parse_json(bytes, 16);
if (!parsed)
return std::unexpected("reflection snapshot is not valid JSON");
const auto *fields = P::as_object(&*parsed);
if (!fields)
return std::unexpected("reflection snapshot is not an object");
const auto schema = P::as_int64(P::find_member(*fields, "schema"));
if (!schema || *schema != schema_version)
return std::unexpected("unsupported reflection schema version");
const auto *entities = P::as_array(P::find_member(*fields, "entities"));
if (!entities)
return std::unexpected("reflection snapshot lacks an entity list");
Snapshot snapshot{limits};
std::set<EntityId> seen;
for (const auto &item : *entities) {
const auto *entity_fields = P::as_object(&item);
if (!entity_fields)
return std::unexpected("reflection entity is not an object");
const auto *id = P::as_string(P::find_member(*entity_fields, "id"));
const auto *name = P::as_string(P::find_member(*entity_fields, "name"));
const auto *type = P::as_string(P::find_member(*entity_fields, "type"));
const auto synthesized = P::as_bool(P::find_member(*entity_fields, "synthesized"));
const auto *provenance = P::as_object(P::find_member(*entity_fields, "provenance"));
const auto *members = P::as_array(P::find_member(*entity_fields, "members"));
if (!id || !name || !type || !synthesized || !provenance || !members)
return std::unexpected("reflection entity is incomplete");
if (!seen.insert(*id).second)
return std::unexpected("duplicate reflection entity identity");
Entity entity;
entity.id = *id;
entity.name = *name;
entity.type = *type;
entity.synthesized = *synthesized;
const auto *context = P::as_string(P::find_member(*provenance, "context"));
const auto gap = P::as_bool(P::find_member(*provenance, "gap"));
const auto *origins = P::as_array(P::find_member(*provenance, "origins"));
if (!context || !gap || !origins)
return std::unexpected("reflection provenance is incomplete");
entity.provenance.context = *context;
entity.provenance.gap = *gap;
for (const auto &origin_item : *origins) {
const auto *origin_fields = P::as_object(&origin_item);
if (!origin_fields)
return std::unexpected("reflection origin is not an object");
const auto *kind_name = P::as_string(P::find_member(*origin_fields, "kind"));
const auto *note = P::as_string(P::find_member(*origin_fields, "note"));
const auto kind = kind_name ? origin_kind(*kind_name) : std::nullopt;
if (!kind || !note)
return std::unexpected("reflection origin is invalid");
Origin origin;
origin.kind = *kind;
origin.note = *note;
const auto *range = P::find_member(*origin_fields, "range");
if (range && !std::holds_alternative<std::nullptr_t>(range->value)) {
auto parsed_range = parse_range(range);
if (!parsed_range)
return std::unexpected(parsed_range.error());
origin.range = std::move(*parsed_range);
}
const auto *target = P::find_member(*origin_fields, "entity");
if (target && !std::holds_alternative<std::nullptr_t>(target->value)) {
const auto *value = P::as_string(target);
if (!value)
return std::unexpected("reflection origin entity is invalid");
origin.entity = *value;
}
entity.provenance.origins.push_back(std::move(origin));
}
for (const auto &member_item : *members) {
const auto *member_fields = P::as_object(&member_item);
if (!member_fields)
return std::unexpected("reflection member is not an object");
const auto *member_name = P::as_string(P::find_member(*member_fields, "name"));
const auto *value_fields = P::as_object(P::find_member(*member_fields, "value"));
if (!member_name || !value_fields)
return std::unexpected("reflection member is incomplete");
const auto *kind_name = P::as_string(P::find_member(*value_fields, "kind"));
const auto kind = kind_name ? value_kind(*kind_name) : std::nullopt;
const auto integral = P::as_int64(P::find_member(*value_fields, "integral"));
const auto boolean = P::as_bool(P::find_member(*value_fields, "boolean"));
const auto *text = P::as_string(P::find_member(*value_fields, "text"));
const auto *value_type = P::as_string(P::find_member(*value_fields, "type"));
const auto *target = P::as_string(P::find_member(*value_fields, "entity"));
if (!kind || !integral || !boolean || !text || !value_type || !target)
return std::unexpected("reflection member value is invalid");
entity.members.push_back(Member{*member_name, Value{.kind = *kind,
.integral = *integral,
.boolean = *boolean,
.text = *text,
.type = *value_type,
.entity = *target}});
}
if (!snapshot.add(std::move(entity)))
return std::unexpected("reflection entity exceeds the snapshot limits");
}
return snapshot;
}
Capabilities::Capabilities(Limits limits) : limits_(limits) {}
bool Capabilities::add(Capability capability) {
if (entries_.size() >= limits_.capabilities)
return false;
if (capability.proposal.empty() || capability.facility.empty() ||
capability.proposal.size() > limits_.nameBytes ||
capability.facility.size() > limits_.nameBytes ||
capability.reason.size() > limits_.textBytes)
return false;
if (!capability.supported && capability.reason.empty())
return false;
if (query(capability.proposal, capability.facility))
return false;
entries_.push_back(std::move(capability));
return true;
}
std::expected<Capability, std::string> Capabilities::query(std::string_view proposal,
std::string_view facility) const {
const auto found = std::ranges::find_if(entries_, [&](const Capability &entry) {
return entry.proposal == proposal && entry.facility == facility;
});
if (found == entries_.end())
return std::unexpected("unknown reflection capability: " + std::string{proposal} + "/" +
std::string{facility});
return *found;
}
std::size_t Capabilities::size() const { return entries_.size(); }
} // namespace vls::reflection
+315
View File
@@ -0,0 +1,315 @@
#include <vls/scheduler/Scheduler.hpp>
#include <algorithm>
#include <array>
#include <condition_variable>
#include <deque>
#include <mutex>
#include <optional>
#include <stdexcept>
#include <thread>
#include <unordered_map>
#include <vector>
namespace vls::scheduler {
namespace {
using Clock = std::chrono::steady_clock;
std::uint64_t nanoseconds(Clock::time_point from, Clock::time_point to) {
return static_cast<std::uint64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(to - from).count());
}
std::size_t pool_index(Priority priority) { return static_cast<std::size_t>(priority); }
} // namespace
bool Budget::valid() const noexcept {
return foreground >= 1 && background >= 1 && artifact >= 1 && queued >= 1 && memory_mib >= 1 &&
watchdog.count() > 0;
}
struct Scheduler::State {
struct Task {
Estimate estimate;
Work work;
Completion completion;
std::stop_source stop;
Clock::time_point queued_at{Clock::now()};
Clock::time_point started_at{};
std::size_t pool{};
bool started{};
bool watchdog{};
bool terminal{};
};
struct Pool {
std::deque<std::shared_ptr<Task>> queue;
std::size_t running{};
std::size_t limit{};
};
struct Terminal {
Completion completion;
Result result;
};
Budget budget;
mutable std::mutex mutex;
std::condition_variable changed, idle;
std::array<Pool, 3> pools;
std::unordered_map<std::string, std::shared_ptr<Task>> active;
Metrics counters;
std::size_t running_memory{};
// Terminal results whose completion callback has not returned yet.
std::size_t finishing{};
bool stopping{};
// Declared last so workers are joined before the state they read is destroyed.
std::vector<std::jthread> workers;
std::jthread monitor;
explicit State(Budget value) : budget(value) {
if (!budget.valid())
throw std::invalid_argument("invalid scheduler budget");
for (std::size_t index = 0; index != pools.size(); ++index)
pools[index].limit = index == pool_index(Priority::foreground) ? budget.foreground
: index == pool_index(Priority::background) ? budget.background
: budget.artifact;
for (std::size_t pool = 0; pool != pools.size(); ++pool)
for (std::size_t worker = 0; worker != pools[pool].limit; ++worker)
workers.emplace_back([this, pool] { work(pool); });
monitor = std::jthread([this](std::stop_token token) { watch(token); });
}
~State() {
std::vector<Terminal> terminals;
{
std::lock_guard lock{mutex};
stopping = true;
for (auto &pool : pools) {
for (auto &task : pool.queue)
if (auto terminal =
finish(*this, task, Outcome::cancelled, "scheduler shutdown"))
terminals.push_back(std::move(*terminal));
pool.queue.clear();
}
for (auto &[key, task] : active)
if (task->started)
task->stop.request_stop();
changed.notify_all();
}
for (auto &terminal : terminals)
terminal.completion(terminal.result);
}
std::size_t total_running() const {
std::size_t count{};
for (auto &pool : pools)
count += pool.running;
return count;
}
static std::optional<Terminal> finish(State &state, const std::shared_ptr<Task> &task,
Outcome outcome, std::string detail) {
if (task->terminal)
return std::nullopt;
task->terminal = true;
const auto now = Clock::now();
state.counters.queue_nanoseconds +=
nanoseconds(task->queued_at, task->started ? task->started_at : now);
if (task->started) {
state.counters.run_nanoseconds += nanoseconds(task->started_at, now);
--state.pools[task->pool].running;
state.running_memory -= task->estimate.memory_mib;
}
switch (outcome) {
case Outcome::completed:
++state.counters.completed;
break;
case Outcome::failed:
++state.counters.failed;
break;
case Outcome::cancelled:
++state.counters.cancelled;
break;
case Outcome::timed_out:
++state.counters.timed_out;
break;
}
const auto entry = state.active.find(task->estimate.key);
if (entry != state.active.end() && entry->second == task)
state.active.erase(entry);
state.changed.notify_all();
state.idle.notify_all();
++state.finishing;
return Terminal{task->completion, Result{task->estimate.key, task->estimate.revision,
outcome, std::move(detail)}};
}
// Invokes a terminal completion outside the lock, then makes drain observe it.
void deliver(Terminal terminal) {
terminal.completion(terminal.result);
std::lock_guard lock{mutex};
--finishing;
idle.notify_all();
}
void work(std::size_t pool) {
std::unique_lock lock{mutex};
for (;;) {
changed.wait(lock, [&] {
if (stopping)
return true;
const auto &queue = pools[pool].queue;
return std::ranges::any_of(queue, [&](const auto &task) {
return running_memory + task->estimate.memory_mib <= budget.memory_mib;
});
});
if (stopping)
return;
auto &queue = pools[pool].queue;
const auto selected = std::ranges::find_if(queue, [&](const auto &task) {
return running_memory + task->estimate.memory_mib <= budget.memory_mib;
});
auto task = *selected;
queue.erase(selected);
++pools[pool].running;
running_memory += task->estimate.memory_mib;
counters.running_peak = std::max(counters.running_peak, total_running());
counters.running_memory_peak = std::max(counters.running_memory_peak, running_memory);
task->started = true;
task->started_at = Clock::now();
lock.unlock();
std::string detail;
Outcome outcome = Outcome::completed;
try {
detail = task->work(task->stop.get_token());
} catch (const std::exception &error) {
detail = error.what();
outcome = Outcome::failed;
} catch (...) {
detail = "unknown failure";
outcome = Outcome::failed;
}
lock.lock();
// A stopped task never reports success or failure: its result must not
// satisfy a publication promise.
if (task->stop.stop_requested())
outcome = task->watchdog ? Outcome::timed_out : Outcome::cancelled;
auto terminal = finish(*this, task, outcome, std::move(detail));
lock.unlock();
if (terminal)
deliver(std::move(*terminal));
lock.lock();
}
}
void watch(std::stop_token shutdown) {
std::unique_lock lock{mutex};
while (!shutdown.stop_requested() && !stopping) {
changed.wait_for(lock, std::chrono::milliseconds(5));
if (stopping)
return;
const auto now = Clock::now();
for (auto &[key, task] : active)
if (task->started && !task->stop.stop_requested() &&
now - task->started_at >= budget.watchdog) {
task->watchdog = true;
task->stop.request_stop();
}
}
}
bool submit(Estimate estimate, Work work, Completion completion) {
std::optional<Terminal> superseded;
{
std::lock_guard lock{mutex};
if (stopping || !work || !completion || estimate.key.empty() ||
estimate.key.size() > 512 || estimate.memory_mib > budget.memory_mib)
return false;
std::size_t queued{};
for (auto &pool : pools)
queued += pool.queue.size();
if (queued >= budget.queued) {
++counters.rejected;
return false;
}
if (const auto entry = active.find(estimate.key); entry != active.end()) {
auto old = entry->second;
if (!old->started) {
auto &queue = pools[old->pool].queue;
const auto position = std::ranges::find(queue, old);
if (position != queue.end())
queue.erase(position);
superseded = finish(*this, old, Outcome::cancelled, "superseded");
} else
old->stop.request_stop();
}
auto task = std::make_shared<Task>();
task->estimate = std::move(estimate);
task->work = std::move(work);
task->completion = std::move(completion);
task->pool = pool_index(task->estimate.priority);
active[task->estimate.key] = task;
pools[task->pool].queue.push_back(task);
++counters.accepted;
counters.queued_peak = std::max(counters.queued_peak, queued + 1);
changed.notify_all();
}
if (superseded)
deliver(std::move(*superseded));
return true;
}
void cancel(std::string_view key) {
std::optional<Terminal> terminal;
{
std::lock_guard lock{mutex};
const auto entry = active.find(std::string{key});
if (entry == active.end())
return;
auto task = entry->second;
if (!task->started) {
auto &queue = pools[task->pool].queue;
const auto position = std::ranges::find(queue, task);
if (position != queue.end())
queue.erase(position);
terminal = finish(*this, task, Outcome::cancelled, "cancelled");
} else
task->stop.request_stop();
}
if (terminal)
deliver(std::move(*terminal));
}
void cancel_all() {
std::vector<std::string> keys;
{
std::lock_guard lock{mutex};
keys.reserve(active.size());
for (auto &[key, task] : active)
keys.push_back(key);
}
for (auto &key : keys)
cancel(key);
}
void drain() {
std::unique_lock lock{mutex};
idle.wait(lock, [&] { return active.empty() && finishing == 0; });
}
Metrics metrics() const {
std::lock_guard lock{mutex};
return counters;
}
};
Scheduler::Scheduler(Budget budget) : state_(std::make_unique<State>(budget)) {}
Scheduler::~Scheduler() = default;
bool Scheduler::submit(Estimate estimate, Work work, Completion completion) {
return state_->submit(std::move(estimate), std::move(work), std::move(completion));
}
void Scheduler::cancel(std::string_view key) { state_->cancel(key); }
void Scheduler::cancel_all() { state_->cancel_all(); }
void Scheduler::drain() { state_->drain(); }
Metrics Scheduler::metrics() const { return state_->metrics(); }
const Budget &Scheduler::budget() const noexcept { return state_->budget; }
} // namespace vls::scheduler
+399
View File
@@ -0,0 +1,399 @@
#include <vls/semantic/Diagnostics.hpp>
#include <Void/LanguageServer/Protocol/Json.hpp>
#include <algorithm>
#include <limits>
#include <map>
namespace vls::semantic {
namespace {
namespace P = Void::LanguageServer::Protocol;
using Json = P::Json;
using Object = Json::Object;
using Error = DiagnosticError;
template <class T> using Result = std::expected<T, Error>;
constexpr std::size_t max_report_bytes = 4 * 1024 * 1024;
constexpr std::size_t max_artifacts = 2048, max_results = 4096, max_locations = 16384;
constexpr std::size_t max_name = 16384, max_message = 65536;
constexpr std::string_view bom = "\xef\xbb\xbf";
// Cap container allocation in Void's JSON value tree before parsing. Brackets
// and commas in embedded source/diagnostic strings are ordinary content.
bool within_structure_limit(std::string_view bytes) {
std::size_t remaining = 128 * 1024;
bool quoted = false, escaped = false;
for (const char c : bytes) {
if (quoted) {
if (escaped)
escaped = false;
else if (c == '\\')
escaped = true;
else if (c == '"')
quoted = false;
} else if (c == '"') {
quoted = true;
} else if (c == '[' || c == '{' || c == ',' || c == ':') {
if (remaining == 0)
return false;
--remaining;
}
}
return true;
}
const Json *member(const Object *obj, std::string_view key) {
return obj ? P::find_member(*obj, key) : nullptr;
}
const std::string *string(const Object *obj, std::string_view key) {
return P::as_string(member(obj, key));
}
const Object *object(const Object *obj, std::string_view key) {
return P::as_object(member(obj, key));
}
const Object *only_object(const Object *obj, std::string_view key) {
const auto *list = P::as_array(member(obj, key));
return list && list->size() == 1 ? P::as_object(&list->front()) : nullptr;
}
bool equals(const Object *obj, std::string_view key, std::string_view value) {
const auto *text = string(obj, key);
return text && *text == value;
}
std::optional<std::uint32_t> natural(const Json *value) {
if (!value)
return {};
const auto *integer = std::get_if<std::int64_t>(&value->value);
if (!integer || *integer < 0 || *integer > std::numeric_limits<std::int32_t>::max())
return {};
return static_cast<std::uint32_t>(*integer);
}
std::optional<ArtifactName> artifact_name(const Object *record, const Object *bases) {
const auto *uri = string(record, "uri");
if (!uri || uri->empty() || uri->size() > max_name)
return {};
const auto *base_id = member(record, "uriBaseId");
if (!base_id)
return ArtifactName{*uri, {}};
const auto *id = P::as_string(base_id);
const auto *base = id ? object(bases, *id) : nullptr;
const auto *base_uri = string(base, "uri");
if (!base_uri || base_uri->empty() || base_uri->size() > max_name || member(base, "uriBaseId"))
return {};
return ArtifactName{*uri, *base_uri};
}
struct BoundArtifact {
const DiagnosticArtifact *file{};
bool contents_match{};
};
struct Reader {
explicit Reader(const DiagnosticJob &source_job) : job(source_job) {}
const DiagnosticJob &job;
const Object *bases{};
std::map<ArtifactName, const DiagnosticArtifact *> bindings;
std::map<ArtifactName, std::size_t> listed;
std::vector<BoundArtifact> by_index;
std::size_t positions_left{max_locations}, column_work{32 * 1024 * 1024};
Result<bool> bind(const Object *run) {
if (job.artifacts.size() > max_artifacts)
return std::unexpected(Error::resource_limit);
std::size_t names_left = 2 * 1024 * 1024;
for (const auto &file : job.artifacts) {
if (!file.snapshot || file.name.uri.empty() || file.name.uri.size() > max_name ||
file.name.base_uri.size() > max_name)
return std::unexpected(Error::invalid_job);
const auto cost = file.name.uri.size() + file.name.base_uri.size();
if (cost > names_left)
return std::unexpected(Error::resource_limit);
names_left -= cost;
if (!bindings.emplace(file.name, &file).second)
return std::unexpected(Error::invalid_job);
}
bases = object(run, "originalUriBaseIds");
if (member(run, "originalUriBaseIds") && !bases)
return std::unexpected(Error::malformed_report);
const auto *files = P::as_array(member(run, "artifacts"));
if (!files) {
if (member(run, "artifacts"))
return std::unexpected(Error::malformed_report);
return false;
}
if (files->size() > max_artifacts)
return std::unexpected(Error::resource_limit);
bool found_owner = false;
for (const auto &item : *files) {
const auto *record = P::as_object(&item);
const auto *location = object(record, "location");
if (const auto *self_index = member(location, "index")) {
const auto index = natural(self_index);
if (!index || *index != by_index.size())
return std::unexpected(Error::malformed_report);
}
const auto name = artifact_name(location, bases);
if (!name || !listed.emplace(*name, by_index.size()).second)
return std::unexpected(Error::malformed_report);
auto binding = bindings.find(*name);
auto *file = binding == bindings.end() ? nullptr : binding->second;
bool matches = true;
if (member(record, "contents")) {
const auto *bytes = string(object(record, "contents"), "text");
if (file) {
const std::string_view input = file->snapshot->text;
matches = bytes && (*bytes == input ||
(input.starts_with(bom) && *bytes == input.substr(3)));
}
}
by_index.push_back({file, matches});
if (!member(record, "roles"))
continue;
const auto *roles = P::as_array(member(record, "roles"));
if (!roles)
return std::unexpected(Error::malformed_report);
for (const auto &role : *roles) {
const auto *text = P::as_string(&role);
if (!text)
return std::unexpected(Error::malformed_report);
if (*text == "analysisTarget") {
if (found_owner || !file || file->snapshot != job.owner || !matches)
return std::unexpected(Error::wrong_owner);
found_owner = true;
}
}
}
return found_owner;
}
std::optional<BoundArtifact> binding(const Object *location) const {
const auto *index = member(location, "index");
std::optional<std::uint32_t> reference;
if (index) {
reference = natural(index);
if (!reference || *reference >= by_index.size())
return {};
}
if (member(location, "uri")) {
auto name = artifact_name(location, bases);
if (!name)
return {};
const auto found = listed.find(*name);
if (found == listed.end() || (reference && *reference != found->second))
return {};
return by_index[found->second];
}
if (member(location, "uriBaseId") || !reference)
return {};
return by_index[*reference];
}
Result<std::optional<Documents::Position>> position(const Documents::DocumentSnapshot &snapshot,
std::uint32_t line, std::uint32_t column,
CoordinatePolicy policy) {
const auto start = snapshot.line_index.line_start_offset(line - 1);
const auto end = snapshot.line_index.line_content_end_offset(snapshot.text, line - 1);
if (!start || !end || *end < *start || *end > snapshot.text.size())
return {};
auto text = std::string_view{snapshot.text}.substr(*start, *end - *start);
std::size_t offset = 0;
if (line == 1 && text.starts_with(bom)) {
if (policy.bom == FirstLineBom::unknown)
return {};
if (policy.bom == FirstLineBom::skipped)
offset = bom.size();
}
const std::size_t target = column - 1;
// Also charge the subsequent UTF-16 conversion, which can scan the line prefix.
const auto charge = 2 * (std::min(target, text.size()) + offset + 1);
if (charge > column_work)
return std::unexpected(Error::resource_limit);
column_work -= charge;
if (policy.unit == ColumnUnit::utf8_bytes) {
if (target > text.size() - offset)
return {};
offset += target;
} else {
std::size_t display = 0;
while (display < target && offset < text.size()) {
const auto ch = static_cast<unsigned char>(text[offset++]);
if (ch == '\t' && policy.unit == ColumnUnit::gcc_display && policy.tabstop > 0 &&
policy.tabstop <= 100) {
display += policy.tabstop - display % policy.tabstop;
} else if (ch >= 0x20 && ch <= 0x7e) {
++display;
} else {
return {};
}
}
if (display != target)
return {};
// The prefix advanced strictly, but a following non-ASCII scalar
// can share this display column. Require a provable boundary.
if (offset < text.size() && static_cast<unsigned char>(text[offset]) >= 0x80)
return {};
}
auto pos = snapshot.offset_to_position(*start + offset);
if (!pos)
return {};
return *pos;
}
Result<DiagnosticLocation> locate(const Object *loc, std::size_t result_index,
std::size_t location_index, bool related) {
if (positions_left == 0)
return std::unexpected(Error::resource_limit);
--positions_left;
const auto *physical = object(loc, "physicalLocation");
if (!physical)
return DiagnosticLocation{};
const auto file = binding(object(physical, "artifactLocation"));
if (!file || !file->file)
return DiagnosticLocation{LocationGap::unknown_artifact};
if (!file->contents_match)
return DiagnosticLocation{LocationGap::artifact_mismatch};
const auto *region = object(physical, "region");
auto first = natural(member(region, "startLine")),
left = natural(member(region, "startColumn"));
auto last = member(region, "endLine") ? natural(member(region, "endLine")) : first;
auto right = natural(member(region, "endColumn"));
if (!first || !left || !last || !right || !*first || !*left || !*last || !*right ||
*last < *first || (*last == *first && *right < *left))
return DiagnosticLocation{LocationGap::incomplete_region};
LocationRequest request{
*file->file, {*first, *left, *last, *right}, result_index, location_index, related};
const auto policy = job.physical_origin ? job.physical_origin(request) : std::nullopt;
if (!policy)
return DiagnosticLocation{LocationGap::unproven_origin};
const auto &snapshot = file->file->snapshot;
auto start = position(*snapshot, *first, *left, *policy);
if (!start)
return std::unexpected(start.error());
auto end = position(*snapshot, *last, *right, *policy);
if (!end)
return std::unexpected(end.error());
if (!*start || !*end || **end < **start)
return DiagnosticLocation{LocationGap::ambiguous_column};
return DiagnosticLocation{LocationGap::none, snapshot, Documents::Range{**start, **end}};
}
};
std::optional<DiagnosticSeverity> severity(const Object *record) {
if (equals(record, "level", "error"))
return DiagnosticSeverity::error;
if (equals(record, "level", "warning"))
return DiagnosticSeverity::warning;
if (equals(record, "level", "note"))
return DiagnosticSeverity::information;
if (equals(record, "level", "none"))
return DiagnosticSeverity::hint;
return {};
}
Result<void> append_locations(Reader &reader, const Json *value, std::size_t index, bool related,
CompilerDiagnostic &diagnostic) {
if (!value)
return {};
const auto *locations = P::as_array(value);
if (!locations)
return std::unexpected(Error::malformed_report);
for (std::size_t i = 0; i != locations->size(); ++i) {
const auto *record = P::as_object(&(*locations)[i]);
if (!record)
return std::unexpected(Error::malformed_report);
auto location = reader.locate(record, index, i, related);
if (!location)
return std::unexpected(location.error());
if (!related && i == 0) {
diagnostic.location = std::move(*location);
} else {
const auto *message = string(object(record, "message"), "text");
if (message && message->size() > max_message)
return std::unexpected(Error::resource_limit);
diagnostic.related.push_back(
{message ? *message : std::string{}, std::move(*location)});
}
}
return {};
}
} // namespace
std::expected<DiagnosticBatch, DiagnosticError>
decode_gcc_diagnostics(const DiagnosticJob &job, const DiagnosticOutput &output) {
if (!job.owner || job.invocation_id.empty() || job.input_view_id.empty() ||
job.invocation_id.size() > max_name || job.input_view_id.size() > max_name)
return std::unexpected(Error::invalid_job);
if (job.invocation_id != output.invocation_id || job.input_view_id != output.input_view_id)
return std::unexpected(Error::wrong_capture);
if (!output.stream_complete || output.sarif.empty())
return std::unexpected(Error::incomplete_stream);
if (!output.exit_code || (*output.exit_code != 0 && *output.exit_code != 1))
return std::unexpected(Error::failed_process);
if (output.sarif.size() > max_report_bytes || !within_structure_limit(output.sarif))
return std::unexpected(Error::resource_limit);
auto report = P::parse_json(output.sarif, 40);
if (!report)
return std::unexpected(Error::malformed_report);
const auto *root = P::as_object(&*report);
const auto *run = only_object(root, "runs");
const auto *driver = object(object(run, "tool"), "driver");
if (!equals(root, "version", "2.1.0") || !equals(driver, "name", "GNU C++26") ||
!equals(driver, "version", "16.2.0") || member(run, "columnKind"))
return std::unexpected(Error::unsupported_report);
const auto *invocation = only_object(run, "invocations");
const auto success = P::as_bool(member(invocation, "executionSuccessful"));
const auto *notifications = P::as_array(member(invocation, "toolExecutionNotifications"));
if (!success || *success != (*output.exit_code == 0) || !notifications)
return std::unexpected(Error::malformed_report);
if (!notifications->empty())
return std::unexpected(Error::tool_failure);
Reader reader{job};
const auto owner_matched = reader.bind(run);
if (!owner_matched)
return std::unexpected(owner_matched.error());
if (*success && !*owner_matched)
return std::unexpected(Error::wrong_owner);
// GCC can fail before opening its main file. Keep the invocation's message
// but do not bind positions to an unconfirmed translation unit.
if (!*owner_matched) {
reader.by_index.clear();
reader.listed.clear();
}
const auto *results = P::as_array(member(run, "results"));
if (!results)
return std::unexpected(Error::malformed_report);
if (results->size() > max_results)
return std::unexpected(Error::resource_limit);
DiagnosticBatch batch{
job.invocation_id, job.input_view_id, job.owner, {}, job.inputs_complete && *owner_matched};
bool source_error = false;
for (std::size_t i = 0; i != results->size(); ++i) {
const auto *record = P::as_object(&(*results)[i]);
const auto level = severity(record);
const auto *message = string(object(record, "message"), "text");
const auto *rule = string(record, "ruleId");
if (!level || !message || !rule || message->empty())
return std::unexpected(Error::malformed_report);
if (message->size() > max_message || rule->size() > max_name)
return std::unexpected(Error::resource_limit);
CompilerDiagnostic diagnostic{*level, *message, *rule, {}, {}};
if (auto primary =
append_locations(reader, member(record, "locations"), i, false, diagnostic);
!primary)
return std::unexpected(primary.error());
if (auto related =
append_locations(reader, member(record, "relatedLocations"), i, true, diagnostic);
!related)
return std::unexpected(related.error());
source_error |= *level == DiagnosticSeverity::error;
if (!diagnostic.location.range || *rule == "fatal error" ||
*rule == "internal compiler error")
batch.complete_for_owner = false;
batch.diagnostics.push_back(std::move(diagnostic));
}
if (source_error == *success)
return std::unexpected(Error::malformed_report);
return batch;
}
} // namespace vls::semantic
File diff suppressed because it is too large. Load diff
+195
View File
@@ -0,0 +1,195 @@
#include <vls/semantic/Occurrences.hpp>
#include <Void/LanguageServer/Protocol/Json.hpp>
#include <algorithm>
#include <cstdint>
#include <limits>
#include <optional>
#include <set>
#include <tuple>
namespace vls::semantic {
namespace P = Void::LanguageServer::Protocol;
using Json = P::Json;
namespace {
constexpr std::size_t max_report = 1024 * 1024;
constexpr std::size_t max_occurrences = 256;
constexpr std::size_t max_name = 64;
constexpr std::size_t max_type = 160;
constexpr std::size_t max_signature = 300;
constexpr std::size_t max_reason = 128;
constexpr std::size_t max_path = 4095;
bool plain(std::string_view text, std::size_t limit) {
return text.size() <= limit &&
std::ranges::none_of(text, [](unsigned char c) { return c < 32 || c == 127; });
}
bool identifier(std::string_view name) {
if (name.empty() || name.size() > max_name)
return false;
for (std::size_t i = 0; i != name.size(); ++i) {
const char c = name[i];
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' ||
(i && c >= '0' && c <= '9')))
return false;
}
return true;
}
const Json *member(const Json &value, std::string_view key) {
const auto *object = P::as_object(&value);
return object ? P::find_member(*object, key) : nullptr;
}
std::optional<std::int64_t> integer(const Json *value) {
if (!value)
return {};
if (const auto *number = std::get_if<std::int64_t>(&value->value))
return *number;
return {};
}
struct RawSpan {
std::string path;
std::uint32_t line, start, end;
};
std::optional<RawSpan> span(const Json *value) {
const auto *object = value ? P::as_object(value) : nullptr;
if (!object || object->size() != 4)
return {};
const auto *path = P::as_string(P::find_member(*object, "path"));
const auto line = integer(P::find_member(*object, "line"));
const auto start = integer(P::find_member(*object, "startByte"));
const auto end = integer(P::find_member(*object, "endByte"));
constexpr auto maximum = std::numeric_limits<std::int32_t>::max();
if (!path || !plain(*path, max_path) || path->find('\0') != path->npos || !line || !start ||
!end || *line < 1 || *line > maximum || *start < 1 || *end <= *start || *end > maximum)
return {};
return RawSpan{*path, static_cast<std::uint32_t>(*line), static_cast<std::uint32_t>(*start),
static_cast<std::uint32_t>(*end)};
}
bool captured(std::span<const CapturedSource> capture, const std::string &path) {
return std::ranges::any_of(capture, [&](const auto &entry) {
return entry.snapshot && entry.logical_path.native() == path;
});
}
// Bind a physical byte span to the captured snapshot and convert it through the
// snapshot's negotiated encoding. The sliced bytes must be exactly the declared
// name and both endpoints must fall on UTF-8 boundaries.
std::optional<std::pair<DiagnosticSnapshot, Documents::Range>>
bind_span(const RawSpan &raw, std::string_view name, std::span<const CapturedSource> capture) {
for (const auto &entry : capture) {
if (!entry.snapshot || entry.logical_path.native() != raw.path)
continue;
const auto &snapshot = entry.snapshot;
const std::string_view text = snapshot->text;
std::size_t line_start = 0;
for (std::uint32_t line = 1; line != raw.line; ++line) {
const auto newline = text.find('\n', line_start);
if (newline == std::string_view::npos)
return {};
line_start = newline + 1;
}
auto line_end = text.find('\n', line_start);
if (line_end == std::string_view::npos)
line_end = text.size();
const std::size_t width = line_end - line_start;
if (raw.start - 1 > width || raw.end - 1 > width)
return {};
const std::size_t begin = line_start + raw.start - 1;
const std::size_t end = line_start + raw.end - 1;
if (text.substr(begin, name.size()) != name)
return {};
if (begin && (static_cast<unsigned char>(text[begin - 1]) & 0xC0) == 0x80)
return {};
if (end < text.size() && (static_cast<unsigned char>(text[end]) & 0xC0) == 0x80)
return {};
const auto start = snapshot->offset_to_position(begin);
const auto finish = snapshot->offset_to_position(end);
if (!start || !finish || !(*start < *finish))
return {};
return std::pair{snapshot, Documents::Range{*start, *finish}};
}
return {};
}
} // namespace
std::expected<OccurrenceReport, OccurrenceError>
decode_occurrences(std::string_view report, std::string_view nonce,
std::span<const CapturedSource> capture) {
if (report.empty() || report.size() > max_report)
return std::unexpected{OccurrenceError::invalid_report};
auto parsed = P::parse_json(report, 8);
if (!parsed)
return std::unexpected{OccurrenceError::invalid_report};
const auto *root = P::as_object(&*parsed);
if (!root || root->size() != 6)
return std::unexpected{OccurrenceError::invalid_report};
const auto schema = integer(P::find_member(*root, "schema"));
const auto *nonce_text = P::as_string(P::find_member(*root, "nonce"));
const auto complete = P::as_bool(P::find_member(*root, "complete"));
const auto partial = P::as_bool(P::find_member(*root, "partial"));
const auto *reason = P::as_string(P::find_member(*root, "reason"));
const auto *items = P::as_array(P::find_member(*root, "occurrences"));
if (!schema || *schema != 1 || !nonce_text || !complete || !partial || !reason ||
!plain(*reason, max_reason) || !items || items->size() > max_occurrences)
return std::unexpected{OccurrenceError::invalid_report};
if (*nonce_text != nonce)
return std::unexpected{OccurrenceError::wrong_nonce};
OccurrenceReport result{{}, *complete, *partial, *reason};
if (!*complete)
return result;
std::set<std::tuple<const void *, std::uint32_t, std::uint32_t>> uses;
for (const auto &item : *items) {
const auto *fields = P::as_object(&item);
if (!fields || (fields->size() != 5 && fields->size() != 6))
return std::unexpected{OccurrenceError::invalid_report};
const auto *name = P::as_string(P::find_member(*fields, "name"));
const auto *type = P::as_string(P::find_member(*fields, "type"));
const auto *canonical = P::as_string(P::find_member(*fields, "canonicalType"));
const auto *signature = P::as_string(P::find_member(*fields, "signature"));
if (!name || !identifier(*name) || !type || !plain(*type, max_type) || type->empty() ||
!canonical || !plain(*canonical, max_type) || canonical->empty() ||
(signature && (!plain(*signature, max_signature) || signature->empty())))
return std::unexpected{OccurrenceError::invalid_report};
const auto use_span = span(P::find_member(*fields, "use"));
if (!use_span)
return std::unexpected{OccurrenceError::invalid_report};
auto use = bind_span(*use_span, *name, capture);
if (!use)
return std::unexpected{OccurrenceError::invalid_report};
if (!uses.emplace(use->first.get(), use->second.start.line, use->second.start.character)
.second)
return std::unexpected{OccurrenceError::invalid_report};
Occurrence occurrence;
occurrence.name = *name;
occurrence.type = *type;
occurrence.canonical_type = *canonical;
if (signature)
occurrence.signature = *signature;
occurrence.use_file = use->first;
occurrence.use = use->second;
const auto *definition = P::find_member(*fields, "definition");
if (definition && !std::holds_alternative<std::nullptr_t>(definition->value)) {
const auto definition_span = span(definition);
if (!definition_span)
return std::unexpected{OccurrenceError::invalid_report};
if (captured(capture, definition_span->path)) {
auto bound = bind_span(*definition_span, *name, capture);
if (!bound)
return std::unexpected{OccurrenceError::invalid_report};
occurrence.definition_file = bound->first;
occurrence.definition = bound->second;
}
}
result.occurrences.push_back(std::move(occurrence));
}
return result;
}
} // namespace vls::semantic
+483
View File
@@ -0,0 +1,483 @@
#include <vls/semantic/SourceCatalog.hpp>
#include <Void/LanguageServer/Support/RegularFile.hpp>
#include <algorithm>
#include <cerrno>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <linux/openat2.h>
#include <sys/syscall.h>
namespace vls::semantic {
namespace fs = std::filesystem;
namespace File = Void::LanguageServer::Detail;
using Void::System::OwnedFd;
using Issue = SourceIssue;
// Shared by old and new grant generations. Historical readers keep their own reservations.
struct SourceAccounting {
std::mutex mutex;
std::size_t handles{}, descriptors{}, bytes{};
};
namespace {
auto fail(Issue issue, const fs::path &path = {}) {
return std::unexpected(SourceError{issue, path.native().size() <= 4095 ? path : fs::path{}});
}
struct Reservation {
std::shared_ptr<SourceAccounting> account;
std::size_t descriptors{}, bytes{};
explicit Reservation(std::shared_ptr<SourceAccounting> account) : account(std::move(account)) {}
Reservation(const Reservation &) = delete;
~Reservation() {
std::lock_guard lock{account->mutex};
--account->handles;
account->descriptors -= descriptors;
account->bytes -= bytes;
}
bool claim(std::size_t fds, std::size_t size) {
std::lock_guard lock{account->mutex};
if (fds > 512 - account->descriptors || size > 192 * 1024 * 1024 - account->bytes)
return false;
account->descriptors += fds;
account->bytes += size;
descriptors += fds;
bytes += size;
return true;
}
};
std::shared_ptr<Reservation> reserve(const std::shared_ptr<SourceAccounting> &account) {
std::lock_guard lock{account->mutex};
if (account->handles >= 64)
return {};
auto reservation = std::make_shared<Reservation>(account);
++account->handles;
return reservation;
}
bool direct_name(const fs::path &path) {
return File::valid_path(path) && path.is_absolute() &&
path.native() == path.lexically_normal().native() &&
(path == path.root_path() || path.has_filename()) &&
std::distance(path.begin(), path.end()) <= 64;
}
bool below(const fs::path &path, const fs::path &root) {
auto [r, p] = std::mismatch(root.begin(), root.end(), path.begin(), path.end());
return r == root.end() && p != path.end();
}
struct Pin {
OwnedFd fd;
struct stat state;
};
using Directory = std::shared_ptr<const Pin>;
bool same_object(const struct stat &a, const struct stat &b) {
return a.st_dev == b.st_dev && a.st_ino == b.st_ino;
}
OwnedFd open_directory(const fs::path &path) {
open_how how{};
how.flags = O_PATH | O_CLOEXEC | O_DIRECTORY;
how.resolve = RESOLVE_NO_SYMLINKS | RESOLVE_NO_MAGICLINKS;
return OwnedFd{
static_cast<int>(::syscall(SYS_openat2, AT_FDCWD, path.c_str(), &how, sizeof how))};
}
std::expected<Directory, SourceError> pin_directory(const fs::path &path,
Reservation &reservation) {
auto fd = open_directory(path);
struct stat state{};
if (!fd)
return fail(errno == ELOOP || errno == ENOTDIR ? Issue::unsupported_route
: Issue::unavailable,
path);
if (::fstat(fd.get(), &state) != 0)
return fail(Issue::unavailable, path);
if (!reservation.claim(1, path.native().size()))
return fail(Issue::resource_limit, path);
return std::make_shared<Pin>(std::move(fd), state);
}
bool directory_current(const fs::path &path, const Pin &pin) {
auto fd = open_directory(path);
struct stat state{};
return fd && ::fstat(fd.get(), &state) == 0 && same_object(pin.state, state);
}
SourceIssue from_document(const Documents::DocumentError &error) {
using K = Documents::DocumentError::Kind;
switch (error.kind) {
case K::resource_limit:
return Issue::resource_limit;
case K::stale_read:
return Issue::changed;
case K::invalid_utf8:
return Issue::invalid_text;
case K::invalid_uri:
return Issue::invalid_path;
default:
return Issue::unavailable_overlay;
}
}
struct Leaf {
Directory parent;
fs::path name;
OwnedFd object;
struct stat state{};
};
bool leaf_current(const Leaf &leaf) {
struct stat state{};
if (::fstatat(leaf.parent->fd.get(), leaf.name.c_str(), &state, AT_SYMLINK_NOFOLLOW) != 0)
return !leaf.object && errno == ENOENT;
return leaf.object && File::same_file_state(leaf.state, state);
}
} // namespace
struct SourceGrant {
SourceScope scope;
std::shared_ptr<Reservation> reservation;
Directory workspace;
std::map<fs::path, Directory> roots;
};
struct SourceEvidence {
InstalledSourceGrant grant;
std::shared_ptr<Reservation> reservation;
Documents::FileOverlayGeneration membership;
std::map<fs::path, Directory> directories;
std::vector<std::pair<fs::path, Leaf>> leaves;
std::vector<Documents::BoundSourceObservation> observations;
std::atomic_bool expired{};
SourceEvidence(InstalledSourceGrant grant, std::shared_ptr<Reservation> reservation,
Documents::FileOverlayGeneration membership)
: grant(std::move(grant)), reservation(std::move(reservation)),
membership(std::move(membership)) {}
};
SourceCapture::SourceCapture(std::shared_ptr<SourceEvidence> evidence)
: evidence_(std::move(evidence)) {}
SourceCatalog::SourceCatalog(const Documents::DocumentStore &documents,
std::function<void()> before_capture_validation)
: documents_(documents), accounting_(std::make_shared<SourceAccounting>()),
before_capture_validation_(std::move(before_capture_validation)) {}
std::expected<InstalledSourceGrant, SourceError>
SourceCatalog::install(const SourceScope &scope, std::span<const fs::path> directories) {
std::lock_guard lock{installations_};
installed_.store({});
if (!direct_name(scope.workspace.root) || scope.workspace.session.empty() ||
scope.workspace.session.size() > 4096 || scope.workspace.session.contains('\0'))
return fail(Issue::invalid_path, scope.workspace.root);
if (directories.empty() || directories.size() > 32)
return fail(Issue::resource_limit);
auto reservation = reserve(accounting_);
if (!reservation)
return fail(Issue::resource_limit);
auto workspace = pin_directory(scope.workspace.root, *reservation);
if (!workspace)
return std::unexpected(workspace.error());
auto grant = std::make_shared<SourceGrant>(scope, std::move(reservation), *workspace,
std::map<fs::path, Directory>{});
for (const auto &name : directories) {
if (!direct_name(name))
return fail(Issue::invalid_path, name);
if (grant->roots.contains(name))
continue;
auto pin =
name == scope.workspace.root ? workspace : pin_directory(name, *grant->reservation);
if (!pin)
return std::unexpected(pin.error());
grant->roots.emplace(name, std::move(*pin));
}
installed_.store(grant);
return grant;
}
void SourceCatalog::revoke() {
std::lock_guard lock{installations_};
installed_.store({});
}
namespace {
using Roots = std::map<fs::path, Directory>;
Roots::const_iterator owning_root(const Roots &roots, const fs::path &path) {
auto owner = roots.end();
for (auto root = roots.begin(); root != roots.end(); ++root)
if (below(path, root->first) &&
(owner == roots.end() || root->first.native().size() > owner->first.native().size()))
owner = root;
return owner;
}
std::expected<void, SourceError> check_requests(const SourceGrant &grant,
std::span<const SourceRequest> requests,
const SourceLimits &limits) {
if (requests.size() > std::min(limits.files, SourceLimits{}.files))
return fail(Issue::resource_limit);
auto remaining = std::min(limits.name_bytes, SourceLimits{}.name_bytes);
std::set<fs::path> file_names;
for (const auto &[path, allow_missing, lookup_only] : requests) {
if (!direct_name(path) || !path.has_filename())
return fail(Issue::invalid_path, path);
if (path.native().size() > remaining)
return fail(Issue::resource_limit, path);
remaining -= path.native().size();
if (owning_root(grant.roots, path) == grant.roots.end() &&
!(lookup_only && grant.roots.contains(path)))
return fail(Issue::outside_scope, path);
if (!lookup_only)
file_names.insert(path);
}
for (const auto &request : requests)
for (auto p = request.path.parent_path(); p != p.root_path(); p = p.parent_path())
if (file_names.contains(p))
return fail(Issue::conflicting_names, request.path);
return {};
}
std::expected<Directory, SourceError> parent_directory(SourceEvidence &evidence,
const fs::path &path, std::size_t max_fds) {
const auto root = owning_root(evidence.grant->roots, path);
auto name = root->first;
auto current = root->second;
if (!directory_current(name, *current))
return fail(Issue::changed, name);
evidence.directories.try_emplace(name, current);
const auto relative = path.lexically_relative(name);
for (const auto &part : relative.parent_path()) {
name /= part;
if (auto i = evidence.directories.find(name); i != evidence.directories.end()) {
current = i->second;
continue;
}
OwnedFd fd{::openat(current->fd.get(), part.c_str(), O_PATH | O_NOFOLLOW | O_CLOEXEC)};
if (!fd)
return fail(errno == ENOENT ? Issue::missing_parent : Issue::unavailable, name);
struct stat state{};
if (::fstat(fd.get(), &state) != 0)
return fail(Issue::unavailable, name);
if (!S_ISDIR(state.st_mode))
return fail(Issue::unsupported_route, name);
if (evidence.reservation->descriptors >= max_fds ||
!evidence.reservation->claim(1, name.native().size()))
return fail(Issue::resource_limit, name);
current = std::make_shared<Pin>(std::move(fd), state);
evidence.directories.emplace(name, current);
}
// A cached intermediate directory may have moved since the previous request.
if (!directory_current(name, *current))
return fail(Issue::changed, name);
return current;
}
std::expected<Leaf, SourceError> bind_leaf(Directory parent, const fs::path &path,
Reservation &budget, std::size_t max_fds,
bool allow_directory = false) {
Leaf leaf{std::move(parent), path.filename(), {}};
leaf.object = OwnedFd{
::openat(leaf.parent->fd.get(), leaf.name.c_str(), O_PATH | O_NOFOLLOW | O_CLOEXEC)};
if (!leaf.object) {
if (errno == ENOENT)
return leaf;
return fail(Issue::unavailable, path);
}
if (::fstat(leaf.object.get(), &leaf.state) != 0)
return fail(Issue::unavailable, path);
if (S_ISLNK(leaf.state.st_mode))
return fail(Issue::unsupported_route, path);
if (!S_ISREG(leaf.state.st_mode) && !(allow_directory && S_ISDIR(leaf.state.st_mode)))
return fail(Issue::not_regular, path);
if (S_ISREG(leaf.state.st_mode) && leaf.state.st_nlink != 1)
return fail(Issue::hard_link, path);
if (budget.descriptors >= max_fds || !budget.claim(1, 0))
return fail(Issue::resource_limit, path);
return leaf;
}
using Snapshot = std::shared_ptr<const Documents::DocumentSnapshot>;
std::expected<Snapshot, SourceError>
read_source(const Documents::DocumentStore &documents,
const Documents::BoundSourceObservation &observation, const Leaf &leaf,
const SourceRequest &request, Reservation &budget, std::size_t limit) {
const auto &overlay = observation.overlay();
if (!overlay && !leaf.object) {
if (!request.allow_missing)
return fail(Issue::missing, request.path);
return Snapshot{};
}
if (!overlay && leaf.state.st_size < 0)
return fail(Issue::unavailable, request.path);
const auto size =
overlay ? overlay->text.size() : static_cast<std::uintmax_t>(leaf.state.st_size);
if (size > limit || !budget.claim(0, size))
return fail(Issue::resource_limit, request.path);
if (overlay)
return overlay;
std::string bytes;
bytes.reserve(size);
auto result = File::stream_regular_fd(
leaf.object, leaf.state, limit, false, [&](std::span<const std::byte> chunk) {
bytes.append(reinterpret_cast<const char *>(chunk.data()), chunk.size());
return true;
});
if (!result)
return fail(result.error() == File::FileError::changed ? Issue::changed
: Issue::unavailable,
request.path);
auto snapshot = documents.materialize_bound_disk(observation, std::move(bytes));
if (!snapshot)
return fail(from_document(snapshot.error()), request.path);
return *snapshot;
}
} // namespace
std::expected<std::shared_ptr<const SourceCapture>, SourceError>
SourceCatalog::capture(const SourceScope &job, const InstalledSourceGrant &grant,
const Documents::FileOverlayInventory &census,
std::span<const SourceRequest> requests, SourceLimits limits) const {
if (!grant || installed_.load() != grant || job != grant->scope)
return fail(Issue::wrong_authority);
if (!directory_current(job.workspace.root, *grant->workspace))
return fail(Issue::changed, job.workspace.root);
if (auto checked = check_requests(*grant, requests, limits); !checked)
return std::unexpected(checked.error());
if (auto checked = documents_.validate_bound_sources(census); !checked)
return fail(from_document(checked.error()));
auto reservation = reserve(accounting_);
if (!reservation)
return fail(Issue::resource_limit);
auto evidence =
std::make_shared<SourceEvidence>(grant, std::move(reservation), census.generation());
std::shared_ptr<SourceCapture> result{new SourceCapture(evidence)};
auto remaining = std::min(limits.total_bytes, SourceLimits{}.total_bytes);
const auto file_limit = std::min(limits.file_bytes, SourceLimits{}.file_bytes);
const auto max_fds = std::min(limits.descriptors, SourceLimits{}.descriptors);
std::map<std::pair<dev_t, ino_t>, fs::path> regular_names;
std::set<fs::path> open_names;
for (const auto &entry : census.entries())
open_names.insert(entry.identity.canonical_path);
for (const auto &request : requests) {
const auto &path = request.path;
for (auto p = path.parent_path(); p != p.root_path(); p = p.parent_path())
if (open_names.contains(p))
return fail(Issue::conflicting_names, p);
auto observed =
documents_.observe_bound_source(census, Documents::path_to_file_uri(path), path);
if (!observed)
return fail(from_document(observed.error()), path);
if (!evidence->reservation->claim(0, path.native().size()))
return fail(Issue::resource_limit, path);
if (auto root = grant->roots.find(path);
request.lookup_only && root != grant->roots.end()) {
if (observed->overlay())
return fail(Issue::conflicting_names, path);
evidence->directories.try_emplace(path, root->second);
evidence->observations.push_back(std::move(*observed));
result->entries_.push_back({path, {}, SourceNode::directory});
continue;
}
auto parent = parent_directory(*evidence, path, max_fds);
if (!parent && request.lookup_only && parent.error().issue == Issue::missing_parent) {
const auto &first_missing = parent.error().path;
auto it = open_names.lower_bound(first_missing);
if (it != open_names.end() && (*it == first_missing || below(*it, first_missing)))
return fail(Issue::missing_parent, first_missing);
auto anchor = evidence->directories.find(first_missing.parent_path());
if (anchor == evidence->directories.end())
return fail(Issue::changed, first_missing);
Leaf missing{anchor->second, first_missing.filename(), {}};
evidence->leaves.emplace_back(first_missing, std::move(missing));
evidence->observations.push_back(std::move(*observed));
result->entries_.push_back({path, {}, SourceNode::missing});
continue;
}
if (!parent)
return std::unexpected(parent.error());
auto leaf = bind_leaf(*parent, path, *evidence->reservation, max_fds, request.lookup_only);
if (!leaf)
return std::unexpected(leaf.error());
if (leaf->object && S_ISDIR(leaf->state.st_mode)) {
if (observed->overlay())
return fail(Issue::conflicting_names, path);
evidence->directories.try_emplace(
path, std::make_shared<Pin>(std::move(leaf->object), leaf->state));
evidence->observations.push_back(std::move(*observed));
result->entries_.push_back({path, {}, SourceNode::directory});
continue;
}
if (leaf->object) {
auto [it, added] =
regular_names.try_emplace({leaf->state.st_dev, leaf->state.st_ino}, path);
if (!added && it->second != path)
return fail(Issue::conflicting_names, path);
}
if (installed_.load() != grant)
return fail(Issue::wrong_authority);
const auto node =
leaf->object || observed->overlay() ? SourceNode::regular : SourceNode::missing;
if (node == SourceNode::missing) {
const auto it = open_names.upper_bound(path);
if (it != open_names.end() && below(*it, path))
return fail(Issue::missing_parent, path);
}
std::expected<Snapshot, SourceError> snapshot{Snapshot{}};
if (!request.lookup_only)
snapshot = read_source(documents_, *observed, *leaf, request, *evidence->reservation,
std::min(remaining, file_limit));
if (!snapshot)
return std::unexpected(snapshot.error());
if (*snapshot)
remaining -= (*snapshot)->text.size();
std::optional<std::time_t> modified;
if (*snapshot)
modified = leaf->object ? leaf->state.st_mtim.tv_sec : (*snapshot)->created_at;
result->entries_.push_back({path, std::move(*snapshot), node, modified});
evidence->leaves.emplace_back(path, std::move(*leaf));
evidence->observations.push_back(std::move(*observed));
}
if (before_capture_validation_)
before_capture_validation_();
if (auto checked = validate(job, *result); !checked)
return std::unexpected(checked.error());
return result;
}
std::expected<void, SourceError> SourceCatalog::validate(const SourceScope &job,
const SourceCapture &capture) const {
auto &e = *capture.evidence_;
if (e.grant != installed_.load() || e.grant->scope != job)
return fail(Issue::wrong_authority);
auto expire = [&](const fs::path &path) {
e.expired = true;
return fail(Issue::changed, path);
};
if (e.expired || !directory_current(job.workspace.root, *e.grant->workspace))
return expire(job.workspace.root);
for (const auto &[path, dir] : e.directories)
if (!directory_current(path, *dir))
return expire(path);
for (const auto &[path, leaf] : e.leaves)
if (!leaf_current(leaf))
return expire(path);
if (auto current = documents_.validate_bound_sources(e.membership, e.observations); !current)
return expire({});
if (e.grant != installed_.load())
return fail(Issue::wrong_authority);
if (e.expired)
return fail(Issue::changed);
return {};
}
} // namespace vls::semantic
File diff suppressed because it is too large. Load diff