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

+331
View File
@@ -0,0 +1,331 @@
#pragma once
#include <Void/LanguageServer/Documents/DocumentSnapshot.hpp>
#include <array>
#include <compare>
#include <cstdint>
#include <expected>
#include <filesystem>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::LanguageServer::Build {
struct WorkspaceIdentity {
std::filesystem::path root;
std::string session;
bool operator==(const WorkspaceIdentity &) const = default;
};
struct GenerationIdentity {
WorkspaceIdentity workspace;
std::string provider, revision;
};
enum class ContextRole { unknown, target, host_description };
// The alternative is stable across record reorderings. Providers distinguish commands using
// structured values or collision-checked identities. An empty TU is reserved for an original
// provider record whose physical owner could not be established.
struct ContextKey {
std::optional<std::string> profile, target;
ContextRole role{ContextRole::unknown};
std::string alternative;
std::filesystem::path owning_tu;
auto operator<=>(const ContextKey &) const = default;
};
enum class SourceOrigin { unknown, workspace, snapshot, generated, external };
enum class Editability { unknown, read_only, editable };
struct SourceMapping {
std::filesystem::path source_path;
std::optional<std::filesystem::path> compiler_path;
SourceOrigin origin{SourceOrigin::unknown};
Editability editability{Editability::unknown};
std::optional<std::string> provenance;
};
struct OriginalCommand {
std::filesystem::path metadata_file;
std::string record_id;
std::optional<std::vector<std::string>> arguments;
std::optional<std::string> command;
std::optional<std::string> original_record;
};
enum class Availability { unknown, missing, stale, ready };
struct Prerequisite {
std::string name;
std::optional<std::string> input_identity;
Availability state{Availability::unknown};
};
struct Artifact {
std::filesystem::path path;
std::optional<std::string> content_identity;
Availability state{Availability::unknown};
};
// A provider keeps the generation's immutable artifact contents available for this lifetime.
class ArtifactLease {
public:
virtual ~ArtifactLease() = default;
};
struct BuildContext {
ContextKey key;
std::optional<std::string> source_language;
std::optional<OriginalCommand> original;
std::optional<std::vector<std::string>> semantic_arguments;
std::optional<std::filesystem::path> working_directory;
std::optional<std::string> toolchain, standard_library, environment;
// One mapping per known source including the owning TU. A header may occur in many contexts.
std::vector<SourceMapping> sources;
// An engaged empty list is a verified absence of requirements.
std::optional<std::vector<Prerequisite>> prerequisites;
std::optional<std::vector<Artifact>> artifacts;
std::vector<std::string> limitations;
[[nodiscard]] const SourceMapping *mapping_for(const std::filesystem::path &source) const;
};
enum class ModelError {
invalid_identity,
invalid_context,
duplicate_context,
invalid_mapping,
wrong_scope,
invalid_input,
superseded,
sequence_exhausted,
no_inputs,
operation_unavailable
};
class BuildGeneration;
using Generation = std::shared_ptr<const BuildGeneration>;
class BuildGeneration {
public:
// Providers supply normalized, absolute physical source paths. Freeze the metadata into
// generation-owned storage, including argv, mappings and original provider records.
[[nodiscard]] static std::expected<Generation, ModelError>
create(const GenerationIdentity &identity, const std::vector<BuildContext> &records,
std::shared_ptr<const ArtifactLease> lease = {});
BuildGeneration(const BuildGeneration &) = delete;
BuildGeneration &operator=(const BuildGeneration &) = delete;
[[nodiscard]] const GenerationIdentity &identity() const { return identity_; }
[[nodiscard]] const std::vector<BuildContext> &contexts() const { return records_; }
[[nodiscard]] std::span<const BuildContext *const>
candidates(const std::filesystem::path &source) const;
[[nodiscard]] const BuildContext *find(const ContextKey &key) const;
[[nodiscard]] bool retains_artifacts() const { return static_cast<bool>(lease_); }
private:
BuildGeneration(GenerationIdentity, std::vector<BuildContext>,
std::shared_ptr<const ArtifactLease>);
GenerationIdentity identity_;
std::vector<BuildContext> records_;
std::shared_ptr<const ArtifactLease> lease_;
std::map<std::filesystem::path, std::vector<const BuildContext *>> by_source_;
};
// Persist the per-file value in the configuration owner. Lookups never edit that configuration.
struct FileOverride {
std::filesystem::path workspace_root, file;
std::string provider;
ContextKey key;
bool operator==(const FileOverride &) const = default;
};
struct EditorSelection {
std::filesystem::path workspace_root;
std::string provider;
std::optional<std::string> profile, target, alternative;
std::optional<ContextRole> role;
bool operator==(const EditorSelection &) const = default;
};
enum class SelectionReason { file_override, missing_override, editor, fallback, no_owner };
struct SelectionScope {
WorkspaceIdentity workspace;
std::filesystem::path file;
};
class ContextSelection {
public:
const std::shared_ptr<const SelectionScope> scope;
const Generation generation;
const std::uint64_t revision;
const std::optional<FileOverride> file_override;
const std::optional<EditorSelection> editor;
const SelectionReason reason;
const BuildContext *const selected;
[[nodiscard]] auto alternatives() const { return generation->candidates(scope->file); }
private:
friend class SelectionState;
ContextSelection(std::shared_ptr<const SelectionScope>, Generation, std::uint64_t,
std::optional<FileOverride>, std::optional<EditorSelection>, SelectionReason,
const BuildContext *);
};
using Selection = std::shared_ptr<const ContextSelection>;
// One sequenced owner per session/workspace/document. Update on each real selection transition.
// Fallback, including ties within the editor's profile/target, uses ascending ContextKey order.
class SelectionState {
public:
SelectionState(const WorkspaceIdentity &workspace, const std::filesystem::path &file);
SelectionState(const SelectionState &) = delete;
SelectionState &operator=(const SelectionState &) = delete;
[[nodiscard]] std::expected<Selection, ModelError>
update(Generation generation, const std::optional<FileOverride> &file_override = {},
const std::optional<EditorSelection> &editor = {});
[[nodiscard]] const auto &scope() const { return scope_; }
private:
std::shared_ptr<const SelectionScope> scope_;
Selection current_;
};
using Snapshot = std::shared_ptr<const Documents::DocumentSnapshot>;
enum class DependencyKind { include, import, generated_source, response_file };
struct DependencyInput {
DependencyKind kind;
std::string name;
std::filesystem::path lookup_path;
Snapshot source;
};
struct BackendIdentity {
std::string implementation, version, protocol;
bool operator==(const BackendIdentity &) const = default;
};
struct ContextProof {
Generation generation;
ContextKey key;
// Identity of the checked disposition, including that context's TU, dependencies and
// authority. The rename owner also supplies proofs for candidates it ruled unaffected.
std::optional<std::string> verification;
bool operator==(const ContextProof &) const = default;
};
struct RenameCoverage {
// The rename owner certifies the complete declared root set and affected-context census.
// The census includes every alternative for the requested file and can span other files.
std::vector<std::filesystem::path> workspace_roots;
std::optional<std::vector<ContextProof>> contexts;
std::optional<std::string> editable_spelling_proof;
bool operator==(const RenameCoverage &) const = default;
};
struct AnalysisInputs {
Snapshot document, translation_unit;
std::optional<std::vector<DependencyInput>> dependencies;
// The owner advances this on any change affecting ordered include/import lookup, including
// misses and overlay changes, across ALL search roots. Absent means coverage is unknown.
std::optional<std::uint64_t> lookup_epoch;
// Session owners provide monotonic configuration and workspace authority identities.
// A dispatcher separately checks permission for its exact invocation.
std::optional<std::uint64_t> configuration_generation, trust_generation;
std::optional<BackendIdentity> backend;
std::optional<RenameCoverage> rename;
};
enum class Operation { status, diagnostics, semantic, rename };
enum class ReadinessLevel { unavailable, degraded, ready };
enum class InputIssue {
context,
document,
translation_unit,
language,
command,
working_directory,
backend,
configuration,
trust,
command_provenance,
source_mapping,
toolchain,
standard_library,
environment,
prerequisites,
artifacts,
provider_limitation,
dependencies,
lookup_coverage,
affected_contexts,
edit_provenance
};
struct Readiness {
ReadinessLevel level;
std::vector<InputIssue> issues;
};
class AnalysisRevision;
using Revision = std::shared_ptr<const AnalysisRevision>;
class AnalysisRevision {
public:
// Copy metadata once and retain immutable snapshots from the session document store.
[[nodiscard]] static std::expected<Revision, ModelError> capture(Selection,
const AnalysisInputs &);
[[nodiscard]] const Readiness &readiness(Operation op) const;
[[nodiscard]] bool same_input_as(const AnalysisRevision &) const;
const Selection selection;
const AnalysisInputs inputs;
private:
AnalysisRevision(Selection, AnalysisInputs);
std::array<Readiness, 4> readiness_;
};
struct AnalysisRequest {
std::uint64_t id;
Operation operation;
Revision revision;
};
using Ticket = std::shared_ptr<const AnalysisRequest>;
struct Publication {
Ticket request;
// Exact validated result bytes. Their encoding belongs to the operation/backend.
std::string payload;
};
// One slot per selection scope and operation. The owner assigns increasing sequence numbers
// WHEN observing inputs, and installs that observation or invalidates it with a null revision.
// Sequence all document, selection, configuration, lookup, trust and backend changes here,
// including changes to other roots in a rename proof. A watcher gap invalidates its evidence.
// Observations from external systems become effective in this slot at these calls.
class PublicationSlot {
public:
PublicationSlot(const SelectionState &, Operation);
[[nodiscard]] std::expected<void, ModelError> replace_inputs(std::uint64_t sequence,
Revision revision);
// Accepts a revocation for the owning workspace even while no revision is installed.
// Delayed attempts carrying an older authority generation remain ineligible.
void revoke_trust(const WorkspaceIdentity &, std::uint64_t new_generation);
[[nodiscard]] std::expected<Ticket, ModelError> issue();
[[nodiscard]] bool cancel(const Ticket &);
// The adapter associates a validated reply with its original request ticket.
[[nodiscard]] bool publish(const Ticket &, std::string_view validated_payload);
// A retained publication describes the instant of observation. Sequence delivery and edit
// application with the owner, including any subsequent invalidation.
[[nodiscard]] std::shared_ptr<const Publication> current() const;
private:
struct State {
Revision revision;
Ticket pending;
std::shared_ptr<const Publication> published;
};
const std::shared_ptr<const SelectionScope> scope_;
const Operation operation_;
mutable std::mutex mutex_;
std::uint64_t sequence_{}, last_request_{}, selection_floor_{};
std::optional<std::uint64_t> configuration_floor_, trust_floor_, lookup_floor_;
State state_;
};
} // namespace Void::LanguageServer::Build
@@ -0,0 +1,112 @@
#pragma once
#include <Void/LanguageServer/Build/Model.hpp>
#include <Void/LanguageServer/Workspace/Trust.hpp>
#include <cstdint>
#include <expected>
#include <filesystem>
#include <memory>
#include <optional>
#include <string>
#include <vector>
namespace Void::LanguageServer::Build {
// The launcher binds explicitly selected external inputs to a single workspace.
// Relative producer locators need an independently known producer working directory.
struct ProviderAnchors;
struct ProviderScope {
WorkspaceIdentity workspace;
std::optional<std::filesystem::path> exact_database, exact_selector, build_root, producer_cwd;
Workspace::ResourceLimitsConfig limits;
std::shared_ptr<const ProviderAnchors> anchors;
};
enum class FilePurpose { selection, status, database, native_database, response };
struct ProviderIssue {
std::string code, message;
std::filesystem::path path;
};
// Bind once when installing launcher grants for this workspace incarnation.
// File readers validate the binding even if a caller copies and edits the scope.
[[nodiscard]] std::expected<ProviderScope, ProviderIssue> bind_provider_scope(ProviderScope);
// Reuse captured directories across a new incarnation of the same folder.
[[nodiscard]] std::expected<ProviderScope, ProviderIssue>
reuse_provider_scope(const ProviderScope &bound, std::string new_session);
struct ProviderStamp;
struct ProviderFile {
FilePurpose purpose;
std::filesystem::path logical_path, canonical_path;
std::shared_ptr<const std::string> bytes;
std::string content_id;
std::shared_ptr<const ProviderStamp> stamp;
};
[[nodiscard]] std::expected<ProviderFile, ProviderIssue>
read_provider_file(const ProviderScope &, const std::filesystem::path &, FilePurpose,
std::size_t byte_limit);
[[nodiscard]] bool provider_file_current(const ProviderScope &, const ProviderFile &);
[[nodiscard]] bool same_provider_object(const ProviderFile &, const ProviderFile &) noexcept;
// Command paths identify filesystem names. Resolving one never reads its contents.
// A missing direct suffix can name a generated input; an unsafe route has no physical path.
enum class CommandPathKind { file, directory };
struct CommandPathStamp;
struct CommandPathLookup {
std::filesystem::path logical_path, physical_path;
std::string issue;
std::shared_ptr<const CommandPathStamp> stamp;
};
[[nodiscard]] CommandPathLookup inspect_command_path(const ProviderScope &,
const std::filesystem::path &, CommandPathKind);
struct FailedResponseLookup {
ProviderIssue issue;
std::size_t byte_limit{};
};
struct CommandLookups {
std::vector<CommandPathLookup> paths;
std::vector<FailedResponseLookup> failed_responses;
};
// Only the workspace authority owner supplies an identified driver. Process
// dispatch requires its own check against the current authority generation.
struct DriverInput {
Workspace::ToolCheck tool;
Workspace::CompilerDriver driver;
std::vector<std::string> wrappers;
};
struct DatabaseInput {
const ProviderScope &scope;
const ProviderFile &database;
std::optional<std::string> profile;
std::optional<DriverInput> driver;
};
struct ImportedCommands {
std::vector<BuildContext> contexts;
std::vector<ProviderFile> dependencies;
std::string revision;
CommandLookups lookups;
};
[[nodiscard]] std::expected<ImportedCommands, ProviderIssue> import_commands(const DatabaseInput &);
enum class ProviderHealth { ready, missing, unavailable, invalid, stale, changed, disabled };
struct ProviderObservation {
std::string provider;
ProviderHealth health{ProviderHealth::unavailable};
std::optional<std::uint64_t> selection_ticket;
std::optional<std::string> profile;
std::optional<std::string> native_generation;
Generation generation;
std::vector<ProviderIssue> issues, warnings;
std::vector<ProviderFile> inputs;
CommandLookups lookups;
};
[[nodiscard]] std::optional<std::filesystem::path>
changed_provider_input(const ProviderScope &, const ProviderObservation &);
[[nodiscard]] ProviderObservation observe_vbs(const ProviderScope &, const std::filesystem::path &,
const std::optional<DriverInput> & = {});
[[nodiscard]] ProviderObservation observe_compdb(const ProviderScope &,
const std::filesystem::path &,
const std::optional<DriverInput> & = {});
} // namespace Void::LanguageServer::Build
@@ -0,0 +1,63 @@
#pragma once
#include <Void/LanguageServer/Documents/Position.hpp>
#include <Void/LanguageServer/Documents/Uri.hpp>
#include <cstdint>
#include <ctime>
#include <expected>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
namespace Void::LanguageServer::Documents {
struct ContentHash {
std::uint64_t fnv1a64{0};
std::string sha256_hex;
[[nodiscard]] bool operator==(const ContentHash &other) const noexcept = default;
[[nodiscard]] std::string display_digest() const;
};
[[nodiscard]] ContentHash compute_content_hash(std::string_view text);
enum class DocumentOrigin { overlay, disk };
struct DocumentSnapshot {
DocumentIdentity identity;
std::string language_id;
std::optional<std::int32_t> version;
// Process-local snapshot sequence. Re-reading a disk input can allocate a new snapshot.
std::uint64_t revision_id{0};
// File overlay membership and encoding generation in the owning document store.
std::uint64_t overlay_epoch{0};
std::string text;
ContentHash content_hash;
LineIndex line_index;
PositionEncoding encoding{PositionEncoding::utf16};
DocumentOrigin origin{DocumentOrigin::overlay};
std::time_t created_at{std::time(nullptr)};
// Compare inputs within a session. Disk inputs use the bound physical path, encoding,
// overlay epoch and exact bytes; open overlays have distinct revisions.
[[nodiscard]] bool same_input_as(const DocumentSnapshot &other) const noexcept;
[[nodiscard]] std::expected<std::size_t, std::string>
position_to_offset(Position position) const {
return line_index.position_to_offset(text, position, encoding);
}
[[nodiscard]] std::expected<Position, std::string>
offset_to_position(std::size_t byte_offset) const {
return line_index.offset_to_position(text, byte_offset, encoding);
}
[[nodiscard]] std::expected<std::pair<std::size_t, std::size_t>, std::string>
range_to_offsets(Range range) const {
return line_index.range_to_offsets(text, range, encoding);
}
};
} // namespace Void::LanguageServer::Documents
@@ -0,0 +1,215 @@
#pragma once
#include <Void/LanguageServer/Documents/DocumentSnapshot.hpp>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <filesystem>
#include <functional>
#include <map>
#include <memory>
#include <optional>
#include <shared_mutex>
#include <span>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::LanguageServer::Documents {
inline constexpr std::size_t kDefaultMaxDiskDocumentBytes = 16ULL * 1024ULL * 1024ULL;
struct TextEdit {
std::optional<Range> range;
std::string text;
};
struct DocumentError {
enum class Kind {
invalid_uri,
invalid_utf8,
not_open,
already_open,
invalid_version,
nonmonotonic_version,
malformed_change,
invalid_range,
desynchronized,
resource_limit,
unavailable_overlay,
ambiguous_overlay,
stale_read,
disk_read_failed,
};
Kind kind{Kind::invalid_uri};
std::string message;
};
struct DocumentLimits {
std::size_t max_document_bytes{kDefaultMaxDiskDocumentBytes};
std::size_t max_snapshot_bytes{128ULL * 1024ULL * 1024ULL};
std::size_t max_open_documents{4096};
std::size_t max_unavailable_documents{4096};
std::size_t max_changes{4096};
std::size_t max_change_bytes{2 * kDefaultMaxDiskDocumentBytes};
};
inline constexpr std::size_t kDefaultMaxFileOverlayEntries =
DocumentLimits{}.max_open_documents + DocumentLimits{}.max_unavailable_documents;
struct FileOverlayBinding {
DocumentIdentity identity;
// A unique ready overlay at enumeration time, or the reason its bytes are unavailable.
std::expected<std::shared_ptr<const DocumentSnapshot>, DocumentError> content;
};
// A membership witness can outlive enumeration without retaining unrelated open text.
class FileOverlayGeneration {
private:
friend class DocumentStore;
friend class FileOverlayInventory;
friend class BoundSourceObservation;
FileOverlayGeneration() = default;
FileOverlayGeneration(std::shared_ptr<const void> store, std::uint64_t epoch)
: store(std::move(store)), epoch(epoch) {}
std::shared_ptr<const void> store;
std::uint64_t epoch{};
};
class FileOverlayInventory {
public:
[[nodiscard]] std::span<const FileOverlayBinding> entries() const noexcept { return entries_; }
[[nodiscard]] const FileOverlayGeneration &generation() const noexcept { return generation_; }
private:
friend class DocumentStore;
friend class BoundSourceObservation;
FileOverlayInventory() = default;
FileOverlayGeneration generation_;
std::vector<FileOverlayBinding> entries_;
};
class BoundSourceObservation {
public:
[[nodiscard]] const DocumentIdentity &identity() const noexcept { return identity_; }
// Null means the caller may acquire disk bytes through its own bound handle.
[[nodiscard]] const std::shared_ptr<const DocumentSnapshot> &overlay() const noexcept {
return overlay_;
}
private:
friend class DocumentStore;
BoundSourceObservation() = default;
FileOverlayGeneration generation_;
DocumentIdentity identity_;
std::shared_ptr<const DocumentSnapshot> overlay_;
};
class DocumentStore {
public:
using DiskReadObserver = std::function<void()>;
// The optional observer runs outside the lock after each attempted disk read.
explicit DocumentStore(PositionEncoding encoding = PositionEncoding::utf16,
DocumentLimits limits = {}, DiskReadObserver after_disk_read = {});
// Position encoding is negotiated before any document opens.
bool set_position_encoding(PositionEncoding encoding);
[[nodiscard]] PositionEncoding position_encoding() const noexcept;
[[nodiscard]] std::expected<std::shared_ptr<const DocumentSnapshot>, DocumentError>
open(std::string_view raw_uri, std::string language_id, std::int64_t version, std::string text);
[[nodiscard]] std::expected<std::shared_ptr<const DocumentSnapshot>, DocumentError>
apply_changes(std::string_view raw_uri, std::int64_t new_version,
std::span<const TextEdit> edits);
[[nodiscard]] std::expected<void, DocumentError>
mark_desynchronized(std::string_view raw_uri, std::optional<std::int64_t> observed_version,
DocumentError cause);
[[nodiscard]] std::expected<void, DocumentError> close(std::string_view raw_uri);
[[nodiscard]] std::shared_ptr<const DocumentSnapshot> snapshot(std::string_view raw_uri) const;
[[nodiscard]] std::shared_ptr<const DocumentSnapshot>
snapshot_by_path(const std::filesystem::path &path) const;
[[nodiscard]] std::vector<std::shared_ptr<const DocumentSnapshot>> list_overlays() const;
// Captures all local file opens and the membership generation, even for an empty census.
[[nodiscard]] std::expected<FileOverlayInventory, DocumentError>
file_overlay_inventory(std::size_t max_entries = kDefaultMaxFileOverlayEntries) const;
// Both names come from the caller's source binding. This operation performs no disk lookup.
// Stage the observation's overlay; an inventory entry can predate a text-only edit.
[[nodiscard]] std::expected<BoundSourceObservation, DocumentError>
observe_bound_source(const FileOverlayInventory &inventory, std::string_view file_uri,
const std::filesystem::path &physical_path) const;
// Moves caller-acquired bytes into a budgeted disk snapshot after rechecking absence.
// A changed generation yields stale_read; a live overlay observation yields already_open.
[[nodiscard]] std::expected<std::shared_ptr<const DocumentSnapshot>, DocumentError>
materialize_bound_disk(const BoundSourceObservation &observation, std::string bytes) const;
// Atomically rechecks membership and every selected document's editor authority.
// The source catalog separately validates disk objects, names, and directory lookups.
[[nodiscard]] std::expected<void, DocumentError>
validate_bound_sources(const FileOverlayInventory &inventory,
std::span<const BoundSourceObservation> selected = {}) const;
[[nodiscard]] std::expected<void, DocumentError>
validate_bound_sources(const FileOverlayGeneration &generation,
std::span<const BoundSourceObservation> selected) const;
// Resolves a unique, ready overlay before considering a bounded regular-file read.
[[nodiscard]] std::expected<std::shared_ptr<const DocumentSnapshot>, DocumentError>
resolve_content(const std::filesystem::path &path,
std::size_t max_bytes = kDefaultMaxDiskDocumentBytes) const;
private:
using Snapshot = std::shared_ptr<const DocumentSnapshot>;
using SnapshotResult = std::expected<Snapshot, DocumentError>;
struct OpenDocument {
DocumentIdentity identity;
std::optional<std::string> language_id;
std::int32_t highest_version;
Snapshot current;
bool admitted;
std::string problem;
};
[[nodiscard]] SnapshotResult overlay_for_path(const DocumentIdentity &identity) const;
[[nodiscard]] bool current_generation(const FileOverlayGeneration &generation) const;
[[nodiscard]] std::expected<void, DocumentError>
check_observation(const BoundSourceObservation &observation) const;
[[nodiscard]] std::size_t snapshot_overhead(const DocumentIdentity &identity,
std::string_view language_id) const noexcept;
[[nodiscard]] std::size_t available_snapshot_bytes() const noexcept;
[[nodiscard]] SnapshotResult make_snapshot(const DocumentIdentity &identity,
std::string_view language_id,
std::optional<std::int32_t> version,
std::string text,
std::optional<LineIndex> index = std::nullopt) const;
static void desynchronize(OpenDocument &document, const DocumentError &cause);
mutable std::shared_mutex mutex_;
const DocumentLimits limits_;
const DiskReadObserver after_disk_read_;
const std::shared_ptr<std::atomic_size_t> snapshot_bytes_;
PositionEncoding encoding_;
std::uint64_t overlay_epoch_{0};
std::size_t admitted_documents_{0};
std::size_t unbound_file_documents_{0};
bool unknown_file_open_{false};
bool unknown_virtual_open_{false};
std::map<std::string, OpenDocument, std::less<>> by_uri_;
std::multimap<std::filesystem::path, const OpenDocument *> by_path_;
};
} // namespace Void::LanguageServer::Documents
@@ -0,0 +1,75 @@
#pragma once
#include <compare>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <limits>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::LanguageServer::Documents {
enum class PositionEncoding {
utf16,
utf8,
};
inline constexpr auto kMaxPositionValue =
static_cast<std::uint32_t>(std::numeric_limits<std::int32_t>::max());
[[nodiscard]] constexpr std::string_view encoding_name(PositionEncoding encoding) noexcept {
return encoding == PositionEncoding::utf8 ? "utf-8" : "utf-16";
}
struct Position {
std::uint32_t line{0};
std::uint32_t character{0};
[[nodiscard]] constexpr auto operator<=>(const Position &other) const noexcept = default;
};
struct Range {
Position start{};
Position end{};
[[nodiscard]] constexpr bool operator==(const Range &other) const noexcept = default;
};
class LineIndex {
public:
LineIndex() = default;
explicit LineIndex(std::string_view text);
[[nodiscard]] std::size_t line_count() const noexcept { return line_starts_.size(); }
[[nodiscard]] std::optional<std::size_t> line_start_offset(std::uint32_t line) const noexcept;
[[nodiscard]] std::optional<std::size_t>
line_content_end_offset(std::string_view text, std::uint32_t line) const noexcept;
[[nodiscard]] std::expected<std::size_t, std::string>
position_to_offset(std::string_view text, Position position, PositionEncoding encoding) const;
[[nodiscard]] std::expected<Position, std::string>
offset_to_position(std::string_view text, std::size_t byte_offset,
PositionEncoding encoding) const;
[[nodiscard]] std::expected<std::pair<std::size_t, std::size_t>, std::string>
range_to_offsets(std::string_view text, Range range, PositionEncoding encoding) const;
private:
friend class DocumentStore;
LineIndex(std::string_view text, std::size_t line_count);
[[nodiscard]] static std::size_t count_lines(std::string_view text) noexcept;
[[nodiscard]] std::size_t storage_bytes() const noexcept;
[[nodiscard]] bool apply_replacement(std::string_view text, std::size_t start, std::size_t end,
std::string_view replacement, std::size_t max_lines);
std::vector<std::size_t> line_starts_{0};
std::size_t text_size_{};
};
} // namespace Void::LanguageServer::Documents
@@ -0,0 +1,41 @@
#pragma once
#include <cstddef>
#include <expected>
#include <filesystem>
#include <string>
#include <string_view>
namespace Void::LanguageServer::Documents {
inline constexpr std::size_t kMaxDocumentUriBytes = 16 * 1024;
struct DocumentIdentity {
// Client binding key. Filesystem aliases such as separate symlinks have separate keys.
std::string canonical_uri;
std::string display_uri;
// Physical lookup path at binding time. Empty if there is no resolved file path.
std::filesystem::path canonical_path;
bool is_file_uri{false};
[[nodiscard]] bool operator==(const DocumentIdentity &other) const noexcept = default;
};
// Normalizes the client key and binds the current physical lookup path for local files.
[[nodiscard]] std::expected<DocumentIdentity, std::string> normalize_uri(std::string_view raw_uri);
// Normalizes the client key without querying the filesystem.
[[nodiscard]] std::expected<std::string, std::string> client_uri_key(std::string_view raw_uri);
// Return the original decoded path, preserving symlinks and parent components.
// A valid non-file URI has an empty path.
[[nodiscard]] std::expected<std::filesystem::path, std::string>
client_file_path(std::string_view raw_uri);
// Derives the lexical key and physical identity for a local filesystem lookup.
[[nodiscard]] std::expected<DocumentIdentity, std::string>
identity_from_path(const std::filesystem::path &path);
[[nodiscard]] std::string path_to_file_uri(const std::filesystem::path &absolute_path);
} // namespace Void::LanguageServer::Documents
@@ -0,0 +1,35 @@
#pragma once
#include <Void/LanguageServer/Protocol/Json.hpp>
#include <cstddef>
#include <expected>
#include <iosfwd>
#include <optional>
#include <string>
#include <string_view>
namespace Void::LanguageServer::Protocol {
inline constexpr std::size_t kDefaultHeaderBytes = 8192;
inline constexpr std::size_t kDefaultBodyBytes = 16777216;
struct FrameLimits {
std::size_t header_bytes{kDefaultHeaderBytes};
std::size_t body_bytes{kDefaultBodyBytes};
};
// A disengaged optional means EOF between frames. Framing errors are fatal: the
// caller must not attempt to find another frame in an untrusted byte stream.
[[nodiscard]] std::expected<std::optional<std::string>, std::string>
read_frame(std::istream &input, FrameLimits limits = {});
[[nodiscard]] std::expected<void, std::string> write_frame(std::ostream &output,
std::string_view body);
// Encoding must succeed before any part of the frame is written.
[[nodiscard]] std::expected<void, std::string>
write_json_frame(std::ostream &output, const Json &body,
std::size_t maximum_depth = kDefaultMaxJsonDepth);
} // namespace Void::LanguageServer::Protocol
@@ -0,0 +1,38 @@
#pragma once
#include <Void/Data/StrictJson.hpp>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <optional>
#include <string>
#include <string_view>
#include <variant>
namespace Void::LanguageServer::Protocol {
using Json = Void::Json::Strict::Value;
using RequestId = std::variant<std::int32_t, std::string>;
inline constexpr std::size_t kDefaultMaxJsonDepth = 64;
// The protocol counts open containers. A scalar needs no depth, and callers can
// lower the protocol limit with maximum_depth.
[[nodiscard]] std::expected<Json, std::string>
parse_json(std::string_view text, std::size_t maximum_depth = kDefaultMaxJsonDepth);
[[nodiscard]] std::expected<std::string, std::string>
serialize_json(const Json &value, std::size_t maximum_depth = kDefaultMaxJsonDepth);
[[nodiscard]] std::expected<RequestId, std::string> request_id(const Json &value);
[[nodiscard]] Json request_id_json(RequestId id);
[[nodiscard]] const Json *find_member(const Json::Object &object, std::string_view key) noexcept;
[[nodiscard]] const Json::Object *as_object(const Json *value) noexcept;
[[nodiscard]] const Json::Array *as_array(const Json *value) noexcept;
[[nodiscard]] const std::string *as_string(const Json *value) noexcept;
[[nodiscard]] std::optional<bool> as_bool(const Json *value) noexcept;
[[nodiscard]] std::optional<std::int64_t> as_int64(const Json *value) noexcept;
[[nodiscard]] std::optional<std::uint32_t> as_uint32(const Json *value) noexcept;
} // namespace Void::LanguageServer::Protocol
@@ -0,0 +1,135 @@
#pragma once
#include <Void/System/Types.hpp>
#include <algorithm>
#include <array>
#include <cerrno>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <filesystem>
#include <span>
#include <string>
#include <utility>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
namespace Void::LanguageServer::Detail {
enum class FileError {
invalid_path,
unavailable,
not_regular,
not_executable,
too_large,
changed,
sink_failed
};
struct FileInfo {
std::filesystem::path canonical_path;
struct stat metadata;
};
inline bool valid_path(const std::filesystem::path &path) {
return !path.empty() && path.native().size() <= 4095 &&
path.native().find('\0') == std::string::npos;
}
inline bool same_file_state(const struct stat &a, const struct stat &b) {
return a.st_dev == b.st_dev && a.st_ino == b.st_ino && a.st_mode == b.st_mode &&
a.st_nlink == b.st_nlink &&
a.st_uid == b.st_uid && a.st_gid == b.st_gid && a.st_size == b.st_size &&
a.st_mtim.tv_sec == b.st_mtim.tv_sec && a.st_mtim.tv_nsec == b.st_mtim.tv_nsec &&
a.st_ctim.tv_sec == b.st_ctim.tv_sec && a.st_ctim.tv_nsec == b.st_ctim.tv_nsec;
}
// Callers obtain metadata with fstat on their admitted O_PATH descriptor. Both the
// reopened reader and its final state must match that capture before any result is published.
template <typename Sink>
std::expected<void, FileError> stream_regular_fd(const System::OwnedFd &object,
const struct stat &before, std::uint64_t limit,
bool executable, Sink &&sink) {
if (!S_ISREG(before.st_mode)) {
return std::unexpected(FileError::not_regular);
}
if (executable && ((before.st_mode & 0111) == 0 ||
::faccessat(object.get(), "", X_OK, AT_EMPTY_PATH | AT_EACCESS) != 0)) {
return std::unexpected(FileError::not_executable);
}
if (before.st_size < 0 || static_cast<std::uint64_t>(before.st_size) > limit) {
return std::unexpected(FileError::too_large);
}
const auto descriptor = "/proc/self/fd/" + std::to_string(object.get());
const System::OwnedFd input{
::open(descriptor.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC | O_NOCTTY)};
struct stat opened{};
if (!input || ::fstat(input.get(), &opened) != 0) {
return std::unexpected(FileError::unavailable);
}
if (!same_file_state(before, opened)) {
return std::unexpected(FileError::changed);
}
std::array<std::byte, 64 * 1024> buffer;
auto remaining = static_cast<std::uint64_t>(before.st_size);
for (;;) {
// One extra byte distinguishes a growing/pseudo file from the promised EOF.
const auto amount = std::min<std::uint64_t>(buffer.size(), remaining + 1);
const auto n = ::read(input.get(), buffer.data(), amount);
if (n < 0) {
if (errno == EINTR) {
continue;
}
return std::unexpected(FileError::unavailable);
}
if (n == 0) {
break;
}
if (static_cast<std::uint64_t>(n) > remaining) {
return std::unexpected(FileError::changed);
}
if (!sink(std::span<const std::byte>{buffer.data(), static_cast<std::size_t>(n)})) {
return std::unexpected(FileError::sink_failed);
}
remaining -= static_cast<std::uint64_t>(n);
}
struct stat after{};
if (remaining != 0 || ::fstat(input.get(), &after) != 0 || !same_file_state(before, after)) {
return std::unexpected(FileError::changed);
}
return {};
}
// Linux release target. O_PATH identifies the referent without opening a device or blocking on a
// FIFO. The selected-file API also checks the caller's original name after streaming.
template <typename Sink>
std::expected<FileInfo, FileError> read_regular(const std::filesystem::path &path,
std::uint64_t limit, bool executable, Sink sink) {
if (!valid_path(path) || !path.is_absolute()) {
return std::unexpected(FileError::invalid_path);
}
const System::OwnedFd object{::open(path.c_str(), O_PATH | O_CLOEXEC)};
struct stat before{};
if (!object || ::fstat(object.get(), &before) != 0) {
return std::unexpected(FileError::unavailable);
}
std::error_code ec;
auto canonical = std::filesystem::canonical(path, ec);
if (ec) {
return std::unexpected(FileError::unavailable);
}
auto read = stream_regular_fd(object, before, limit, executable, sink);
if (!read) {
return std::unexpected(read.error());
}
struct stat named{};
if (std::filesystem::canonical(path, ec) != canonical || ec ||
::stat(canonical.c_str(), &named) != 0 || !same_file_state(before, named)) {
return std::unexpected(FileError::changed);
}
return FileInfo{std::move(canonical), before};
}
} // namespace Void::LanguageServer::Detail
@@ -0,0 +1,159 @@
#pragma once
#include <Void/LanguageServer/Protocol/Json.hpp>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <filesystem>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Void::LanguageServer::Workspace {
enum class ConfigLayer { defaults, workspace_local, user_runtime, cli };
struct ConfigOrigin {
ConfigLayer layer{ConfigLayer::defaults};
std::filesystem::path base;
std::optional<std::filesystem::path> selected_file;
std::uint64_t revision{}; // Assigned at trusted input ingress; copying/remerging preserves it.
};
enum class ProviderPreference { auto_detect, vbs, compdb, none };
enum class AuthorityLevel {
passive_read,
trusted_metadata_refresh,
compiler_use,
explicit_build_action
};
struct ToolSelection {
std::filesystem::path root;
AuthorityLevel operation{AuthorityLevel::passive_read};
std::filesystem::path executable;
bool operator==(const ToolSelection &) const = default;
};
struct ResourceLimitsConfig {
std::uint32_t max_semantic_workers{2};
std::uint32_t worker_memory_limit_mib{2048};
std::uint32_t max_response_file_depth{8};
std::size_t max_response_file_bytes{1024ULL * 1024ULL};
std::size_t max_compdb_bytes{64ULL * 1024ULL * 1024ULL};
std::size_t max_manifest_bytes{32ULL * 1024ULL * 1024ULL};
};
enum class ConfigIssue {
invalid_value,
invalid_origin,
unsupported,
untrusted_setting,
resource_limit,
file_error
};
struct ConfigDiagnostic {
ConfigLayer source_layer;
std::string key;
std::string message;
ConfigIssue issue;
};
// Typed input for launcher flags. Paths are interpreted relative to the supplied CLI base.
struct SettingsOverrides {
std::optional<ProviderPreference> provider;
std::optional<std::filesystem::path> vbs_manifest_path;
std::optional<std::filesystem::path> compdb_path;
std::optional<std::string> selected_profile;
std::optional<bool> enable_background_indexing;
std::optional<std::uint32_t> max_semantic_workers;
std::optional<std::uint32_t> worker_memory_limit_mib;
std::optional<std::uint32_t> max_response_file_depth;
std::optional<std::uint32_t> max_response_file_bytes;
std::optional<std::uint32_t> max_compdb_bytes;
std::optional<std::uint32_t> max_manifest_bytes;
std::optional<std::vector<std::filesystem::path>> trusted_roots;
std::optional<std::vector<std::filesystem::path>> approved_compilers;
std::optional<std::vector<std::string>> approved_wrappers;
std::optional<bool> allow_metadata_refresh;
std::optional<bool> allow_explicit_build_actions;
std::optional<bool> allow_compiler_plugins;
std::optional<std::vector<ToolSelection>> tool_approvals;
};
class PartialWorkspaceSettings {
public:
[[nodiscard]] const ConfigOrigin &origin() const noexcept { return origin_; }
[[nodiscard]] const auto &diagnostics() const noexcept { return diagnostics_; }
private:
PartialWorkspaceSettings(ConfigOrigin, SettingsOverrides, std::vector<ConfigDiagnostic>);
static std::uint64_t latest_trusted_revision() noexcept;
ConfigOrigin origin_;
SettingsOverrides values_;
std::vector<ConfigDiagnostic> diagnostics_;
friend PartialWorkspaceSettings parse_workspace_settings(const Protocol::Json &,
const std::filesystem::path &);
friend std::expected<PartialWorkspaceSettings, ConfigDiagnostic>
read_user_settings(const std::filesystem::path &);
friend PartialWorkspaceSettings settings_from_cli(SettingsOverrides,
const std::filesystem::path &);
friend class MergedConfiguration;
friend class TrustPolicy;
};
struct WorkspaceSettings {
std::filesystem::path workspace_root;
ProviderPreference provider{ProviderPreference::auto_detect};
std::optional<std::filesystem::path> vbs_manifest_path;
ConfigOrigin vbs_manifest_origin;
std::optional<std::filesystem::path> compdb_path;
ConfigOrigin compdb_origin;
std::optional<std::string> selected_profile;
bool enable_background_indexing{true};
ResourceLimitsConfig limits{};
// The legacy lists remain configuration data. Only an exact toolApprovals entry selects a pin.
std::vector<std::filesystem::path> trusted_roots;
std::vector<std::filesystem::path> approved_compilers;
std::vector<std::string> approved_wrappers{"ccache", "sccache", "distcc"};
bool allow_metadata_refresh{false};
bool allow_explicit_build_actions{false};
bool allow_compiler_plugins{false};
std::vector<ToolSelection> tool_approvals;
ConfigOrigin tool_approvals_origin;
};
class MergedConfiguration {
public:
[[nodiscard]] const WorkspaceSettings &effective() const noexcept { return effective_; }
[[nodiscard]] const auto &diagnostics() const noexcept { return diagnostics_; }
private:
MergedConfiguration() = default;
WorkspaceSettings effective_;
std::vector<ConfigDiagnostic> diagnostics_;
std::optional<bool> metadata_refresh_, build_actions_;
void apply(const PartialWorkspaceSettings &, ConfigLayer);
friend MergedConfiguration merge_configuration(const PartialWorkspaceSettings &,
const PartialWorkspaceSettings *,
const PartialWorkspaceSettings *);
};
[[nodiscard]] PartialWorkspaceSettings
parse_workspace_settings(const Protocol::Json &payload,
const std::filesystem::path &workspace_root);
// The launcher explicitly selects this absolute file. No repository discovery or cwd fallback.
[[nodiscard]] std::expected<PartialWorkspaceSettings, ConfigDiagnostic>
read_user_settings(const std::filesystem::path &selected_file);
[[nodiscard]] PartialWorkspaceSettings settings_from_cli(SettingsOverrides options,
const std::filesystem::path &base);
[[nodiscard]] MergedConfiguration
merge_configuration(const PartialWorkspaceSettings &workspace,
const PartialWorkspaceSettings *user = nullptr,
const PartialWorkspaceSettings *cli = nullptr);
[[nodiscard]] std::string_view provider_preference_name(ProviderPreference pref) noexcept;
[[nodiscard]] bool is_transparent_wrapper(std::string_view name) noexcept;
} // namespace Void::LanguageServer::Workspace
@@ -0,0 +1,165 @@
#pragma once
#include <Void/LanguageServer/Workspace/Configuration.hpp>
#include <cstdint>
#include <expected>
#include <filesystem>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
namespace Void::LanguageServer::Workspace {
enum class TrustError {
invalid_path,
unavailable_file,
not_regular,
not_executable,
too_large,
digest_unavailable,
identity_changed,
untrusted_root,
operation_not_approved,
tool_not_approved,
tool_not_pinned,
stale_generation,
explicit_action_required,
invalid_invocation,
action_pending,
action_not_current,
invocation_mismatch,
capacity_exceeded
};
[[nodiscard]] std::string_view trust_error_message(TrustError error) noexcept;
struct ToolIdentity {
std::filesystem::path selected_path;
std::filesystem::path canonical_path;
std::uint64_t device{}, inode{}, file_size{};
std::uint32_t mode{}, owner{}, group{};
std::string content_hash_hex;
bool operator==(const ToolIdentity &) const = default;
};
inline constexpr std::uint64_t max_tool_bytes = 256ULL * 1024 * 1024;
[[nodiscard]] std::expected<ToolIdentity, TrustError>
inspect_tool_identity(const std::filesystem::path &executable);
[[nodiscard]] std::expected<ToolIdentity, TrustError>
revalidate_tool_identity(const ToolIdentity &pinned);
enum class CompilerDriver { unknown, gcc, clang };
enum class FlagClassification {
safe,
transparent_wrapper,
invalid_command,
unapproved_compiler_path,
unsupported_driver,
execution_bearing_plugin,
execution_bearing_wrapper,
suspicious_toolchain_override,
unresolved_response_file,
unsupported_option,
unsupported_operand
};
struct CommandSecurityReport {
bool allowed{};
FlagClassification classification{FlagClassification::invalid_command};
std::size_t argument_index{};
std::string_view reason;
std::vector<std::string> unwrapped_argv;
std::vector<std::string> unwrapped_wrappers;
};
// Describes a normalized GCC/Clang C/C++ argv. The provider expands response files and
// resolves supported path operands first. Only the accepted data suffix appears in unwrapped_argv.
[[nodiscard]] CommandSecurityReport
classify_and_unwrap_command(std::span<const std::string> argv,
std::span<const std::string> recognized_wrappers,
const ToolIdentity &selected_compiler, CompilerDriver driver);
struct ToolCheck {
ToolIdentity identity;
std::filesystem::path workspace_root;
AuthorityLevel operation;
std::uint64_t trust_generation;
ConfigOrigin selection_origin;
};
struct BuildInvocation {
std::filesystem::path root, executable, working_directory;
std::vector<std::string> arguments; // excludes executable, order is significant
std::string input_identity, environment_identity;
std::uint64_t trust_generation{};
bool operator==(const BuildInvocation &other) const;
};
class BuildApproval {
friend class TrustPolicy;
BuildApproval(std::shared_ptr<const BuildInvocation> invocation,
std::pair<std::uint64_t, std::uint64_t> cwd)
: invocation_(std::move(invocation)), directory_(cwd) {}
std::shared_ptr<const BuildInvocation> invocation_;
std::pair<std::uint64_t, std::uint64_t> directory_;
};
// A ToolCheck describes one passive observation. A future dispatcher must bind the verified
// open object, exact invocation and current generation at dispatch; a path/report is insufficient.
class TrustPolicy {
public:
// Observers may reenter. Concurrent callbacks carry their committed workspace generations.
using RevocationCallback =
std::move_only_function<void(const std::filesystem::path &, std::uint64_t) const noexcept>;
explicit TrustPolicy(RevocationCallback on_revocation = {});
// Launcher-side configuration install/refresh. Invalidates the old pins, work and pending
// action.
[[nodiscard]] std::expected<std::uint64_t, TrustError>
replace_configuration(const MergedConfiguration &configuration);
[[nodiscard]] std::expected<ToolCheck, TrustError>
pin_approved_tool(const std::filesystem::path &root, AuthorityLevel purpose,
const std::filesystem::path &executable);
[[nodiscard]] std::expected<ToolCheck, TrustError>
check_tool(const std::filesystem::path &root, AuthorityLevel purpose,
const std::filesystem::path &executable, std::uint64_t expected_generation);
void revoke_root_authority(const std::filesystem::path &root);
[[nodiscard]] std::uint64_t generation(const std::filesystem::path &root) const;
// Only a new explicit user action may call approve_build_action. Consuming/cancelling its
// ticket is atomic. Every copy of a spent or revoked ticket is ineligible.
[[nodiscard]] std::expected<BuildApproval, TrustError>
approve_build_action(const BuildInvocation &invocation);
[[nodiscard]] std::expected<ToolCheck, TrustError>
consume_build_action(const BuildApproval &approval, const BuildInvocation &invocation);
[[nodiscard]] bool cancel_build_action(const BuildApproval &approval);
private:
using Key = std::pair<AuthorityLevel, std::string>;
using DirectoryId = std::pair<std::uint64_t, std::uint64_t>;
struct RootState {
DirectoryId directory;
ConfigOrigin origin;
std::uint64_t approval_floor{}; // Previously read selections cannot re-arm a revoked pin.
std::uint64_t generation{};
std::map<Key, std::optional<ToolIdentity>> tools;
std::shared_ptr<const BuildInvocation> pending;
};
std::expected<ToolCheck, TrustError>
inspect_selected(const std::filesystem::path &root, AuthorityLevel purpose,
const std::filesystem::path &executable,
std::optional<std::uint64_t> required_generation);
void notify(const std::filesystem::path &root, std::uint64_t generation) const;
mutable std::mutex mutex_;
std::uint64_t last_generation_{};
std::map<std::filesystem::path, RootState> roots_;
RevocationCallback on_revocation_;
};
} // namespace Void::LanguageServer::Workspace
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include <Void/LanguageServer/Documents/DocumentStore.hpp>
#include <Void/LanguageServer/Protocol/Json.hpp>
namespace vls {
[[nodiscard]] Void::LanguageServer::Documents::PositionEncoding
negotiate_position_encoding(const Void::LanguageServer::Protocol::Json &initialize_params);
void reject_change_envelope(Void::LanguageServer::Documents::DocumentStore &store,
const Void::LanguageServer::Protocol::Json *params);
[[nodiscard]] std::expected<void, std::string>
synchronize_document(Void::LanguageServer::Documents::DocumentStore &store, std::string_view method,
const Void::LanguageServer::Protocol::Json *params);
} // namespace vls
+4 -18
View File
@@ -1,25 +1,11 @@
#pragma once
#include <cstddef>
#include <expected>
#include <iosfwd>
#include <optional>
#include <string>
#include <string_view>
#include <Void/LanguageServer/Protocol/Framing.hpp>
namespace vls {
struct FrameLimits {
std::size_t header_bytes{8192};
std::size_t body_bytes{16777216};
};
// A disengaged optional means EOF between frames. Framing errors are fatal: the
// caller must not attempt to find another frame in an untrusted byte stream.
[[nodiscard]] std::expected<std::optional<std::string>, std::string>
read_frame(std::istream &input, FrameLimits limits = {});
[[nodiscard]] std::expected<void, std::string> write_frame(std::ostream &output,
std::string_view body);
using Void::LanguageServer::Protocol::FrameLimits;
using Void::LanguageServer::Protocol::read_frame;
using Void::LanguageServer::Protocol::write_frame;
} // namespace vls
+27 -14
View File
@@ -1,23 +1,36 @@
#pragma once
#include <Void/Data/StrictJson.hpp>
#include <Void/LanguageServer/Protocol/Json.hpp>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <string>
#include <string_view>
#include <variant>
#include <stdexcept>
#include <utility>
namespace vls {
using Json = Void::Json::Strict::Value;
using RequestId = std::variant<std::int32_t, std::string>;
using Void::LanguageServer::Protocol::Json;
using Void::LanguageServer::Protocol::parse_json;
using Void::LanguageServer::Protocol::request_id;
using Void::LanguageServer::Protocol::RequestId;
[[nodiscard]] std::expected<Json, std::string> parse_json(std::string_view text,
std::size_t maximum_depth = 64);
[[nodiscard]] std::expected<RequestId, std::string> request_id(const Json &value);
[[nodiscard]] std::string quote_json(std::string_view text);
[[nodiscard]] std::string encode_id(const RequestId &id);
namespace detail {
inline std::string require_json_encoding(std::expected<std::string, std::string> encoded) {
if (!encoded) {
throw std::invalid_argument{encoded.error()};
}
return std::move(*encoded);
}
} // namespace detail
[[nodiscard]] inline std::string quote_json(std::string_view text) {
return detail::require_json_encoding(
Void::LanguageServer::Protocol::serialize_json(Json{std::string{text}}));
}
[[nodiscard]] inline std::string encode_id(const RequestId &id) {
return detail::require_json_encoding(Void::LanguageServer::Protocol::serialize_json(
Void::LanguageServer::Protocol::request_id_json(id)));
}
} // namespace vls
+13 -1
View File
@@ -1,32 +1,44 @@
#pragma once
#include <Void/LanguageServer/Documents/DocumentStore.hpp>
#include <vls/Framing.hpp>
#include <vls/WorkspaceSession.hpp>
#include <functional>
#include <iosfwd>
#include <optional>
#include <string>
#include <string_view>
namespace vls {
namespace semantic {
class EditorDiagnostics;
}
inline constexpr std::string_view server_version = "0.1.0";
struct DispatchResult {
std::optional<std::string> response;
std::optional<int> exit_code;
std::string diagnostic{};
};
class Server {
public:
explicit Server(WorkspaceLaunch launch = {}, std::function<bool(std::string)> send = {});
~Server();
[[nodiscard]] DispatchResult handle(std::string_view body);
private:
enum class State { awaiting_initialize, running, shutdown };
State state_{State::awaiting_initialize};
Void::LanguageServer::Documents::DocumentStore documents_;
WorkspaceSession workspace_;
std::unique_ptr<semantic::EditorDiagnostics> diagnostics_;
};
// Thin transport loop shared by the executable and stream-failure unit tests.
[[nodiscard]] int run_stdio(std::istream &input, std::ostream &output, std::ostream &diagnostics,
FrameLimits limits = {});
FrameLimits limits = {}, WorkspaceLaunch launch = {});
} // namespace vls
+90
View File
@@ -0,0 +1,90 @@
#pragma once
#include <Void/LanguageServer/Build/Providers.hpp>
#include <cstdint>
#include <expected>
#include <filesystem>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
namespace vls {
namespace semantic {
class GccProfile;
}
struct WorkspaceLaunch {
std::optional<std::filesystem::path> root, build_root, producer_cwd;
std::optional<Void::LanguageServer::Workspace::PartialWorkspaceSettings> user_settings,
cli_settings;
std::shared_ptr<const semantic::GccProfile> diagnostics_profile{};
};
struct SemanticDriver {
std::filesystem::path executable;
Void::LanguageServer::Workspace::CompilerDriver family{
Void::LanguageServer::Workspace::CompilerDriver::unknown};
};
enum class SemanticContextIssue { unavailable, disabled, no_command, wrong_command, superseded };
struct SemanticContextError {
SemanticContextIssue issue;
std::string message;
};
struct SemanticLeaseData;
class SemanticContextLease {
public:
[[nodiscard]] const Void::LanguageServer::Build::Selection &selection() const;
[[nodiscard]] const Void::LanguageServer::Build::SelectionState &selection_state() const;
[[nodiscard]] const Void::LanguageServer::Build::DriverInput &driver() const;
[[nodiscard]] std::uint64_t configuration_generation() const;
[[nodiscard]] std::uint32_t worker_memory_limit_mib() const;
[[nodiscard]] const std::string &document_uri() const;
private:
friend class WorkspaceSession;
explicit SemanticContextLease(std::shared_ptr<const SemanticLeaseData> data);
std::shared_ptr<const SemanticLeaseData> data_;
};
class WorkspaceSession {
public:
// The optional test hook runs after observation and before the publication checks.
explicit WorkspaceSession(WorkspaceLaunch = {}, std::function<void()> before_publish = {});
~WorkspaceSession();
// The client settings object contains defaults and optional `workspaces`
// overrides keyed by a folder's admitted or canonical file URI.
[[nodiscard]] std::expected<void, std::string>
initialize(const Void::LanguageServer::Protocol::Json &params);
[[nodiscard]] std::expected<void, std::string>
update_folders(const Void::LanguageServer::Protocol::Json *params);
[[nodiscard]] std::expected<void, std::string>
configure(const Void::LanguageServer::Protocol::Json *params);
[[nodiscard]] std::expected<Void::LanguageServer::Protocol::Json, std::string>
provider_status(const Void::LanguageServer::Protocol::Json *params);
// The caller explicitly selects the launcher driver. The lease retains the ordered
// original and checked command in selection()->selected, and its immutable generation.
[[nodiscard]] std::expected<SemanticContextLease, SemanticContextError>
acquire_semantic_context(std::string_view document_uri,
std::optional<std::string_view> workspace_uri,
const SemanticDriver &selected_driver);
[[nodiscard]] std::expected<void, SemanticContextError>
validate_semantic_context(const SemanticContextLease &lease);
// Invalidates launcher authority and in-flight observations for an admitted root.
void revoke_root_authority(const std::filesystem::path &root);
private:
struct State;
std::unique_ptr<State> state_;
};
} // namespace vls
@@ -0,0 +1,66 @@
#pragma once
#include <Void/LanguageServer/Protocol/Json.hpp>
#include <cstdint>
#include <expected>
#include <filesystem>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
namespace vls::gcc {
class ReplayRecording;
}
namespace vls::debug {
namespace Protocol = Void::LanguageServer::Protocol;
using Json = Protocol::Json;
// DAP and the versioned inspection requests share the same cursor and generation.
class ReplaySession {
public:
static std::expected<ReplaySession, std::string> open(const std::filesystem::path &path);
ReplaySession(const ReplaySession &) = delete;
ReplaySession &operator=(const ReplaySession &) = delete;
ReplaySession(ReplaySession &&) noexcept = default;
ReplaySession &operator=(ReplaySession &&) = delete;
[[nodiscard]] Json::Object identity() const;
[[nodiscard]] Json::Object describe() const;
[[nodiscard]] bool matches(const Json::Object &arguments) const;
[[nodiscard]] std::expected<Json::Object, std::string> timeline(std::size_t start,
std::size_t count) const;
[[nodiscard]] std::expected<Json::Object, std::string> frames(std::size_t start,
std::size_t count) const;
// A false result represents the boundary in the requested direction. It preserves the cursor.
[[nodiscard]] std::expected<bool, std::string> initial_position();
[[nodiscard]] std::expected<bool, std::string> move_to_value(bool forward);
[[nodiscard]] std::expected<void, std::string> seek(std::uint32_t sequence);
void finish();
[[nodiscard]] bool paused() const { return sequence_.has_value(); }
[[nodiscard]] std::string_view pause_kind() const { return pause_kind_; }
[[nodiscard]] bool source_available() const { return source_available_; }
[[nodiscard]] std::string_view source_bytes() const;
[[nodiscard]] std::size_t frame_count() const;
[[nodiscard]] const Json &frame(std::size_t top_first_index) const;
[[nodiscard]] std::int64_t frame_handle(std::size_t index) const;
[[nodiscard]] std::int64_t scope_handle(std::size_t index) const;
[[nodiscard]] std::optional<std::size_t> handle_index(std::int64_t handle, bool scope) const;
private:
ReplaySession(std::shared_ptr<const gcc::ReplayRecording> recording, std::string id);
std::shared_ptr<const gcc::ReplayRecording> recording_;
std::string id_;
bool source_available_;
bool finished_{};
std::int64_t generation_{};
std::int64_t next_handle_{1};
std::int64_t frame_base_{1};
std::optional<std::uint32_t> sequence_;
std::string_view pause_kind_{"none"};
Json cursor_{nullptr};
};
} // namespace vls::debug
+66
View File
@@ -0,0 +1,66 @@
#pragma once
#include <Void/LanguageServer/Protocol/Json.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <filesystem>
#include <memory>
#include <optional>
#include <string>
namespace vls::debug::live {
enum class State { idle, running, stopped, completed, failed, cancelled };
struct Stop {
std::uint64_t generation{};
std::uint32_t sequence{};
};
struct Options {
std::filesystem::path worker; // vls_gcc_probe
std::filesystem::path compiler;
std::string compiler_sha256;
std::filesystem::path source;
std::filesystem::path trace;
bool stepping{true};
std::chrono::milliseconds deadline{60000};
std::size_t max_notice_bytes{64 * 1024};
};
// One live private-compiler session speaking the supervisor notice protocol.
// Control actions are serialized; an inspection snapshot belongs to the stop
// generation that requested it and is not reused after the session moves.
class LiveSession {
public:
explicit LiveSession(Options);
~LiveSession();
LiveSession(const LiveSession &) = delete;
LiveSession &operator=(const LiveSession &) = delete;
LiveSession(LiveSession &&) = delete;
LiveSession &operator=(LiveSession &&) = delete;
// Spawns the worker and waits for the first stop.
[[nodiscard]] std::expected<Stop, std::string> start();
// At a stop: single-step. Returns the next stop or nullopt when finished.
[[nodiscard]] std::expected<std::optional<Stop>, std::string> step();
[[nodiscard]] std::expected<std::optional<Stop>, std::string> continue_run();
// Requests cancellation and reaps the worker.
[[nodiscard]] std::expected<void, std::string> cancel();
// Read-only bounded snapshot at the current stop.
[[nodiscard]] std::expected<Void::LanguageServer::Protocol::Json, std::string> inspect();
[[nodiscard]] State state() const;
[[nodiscard]] std::optional<Stop> stop() const;
[[nodiscard]] std::string outcome() const;
[[nodiscard]] std::string reason() const;
private:
struct State_;
std::unique_ptr<State_> state_;
};
} // namespace vls::debug::live
+95
View File
@@ -0,0 +1,95 @@
#pragma once
#include <compare>
#include <cstddef>
#include <cstdint>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace vls::features::completion {
// Candidate origin is explicit: this slice ranks workspace symbols from the
// analysis index and never claims compiler-native completion.
enum class Kind { unknown, function, type, variable, field, namespace_, module, keyword };
struct Limits {
std::size_t candidates{200};
std::size_t labelBytes{256};
std::size_t detailBytes{512};
std::size_t provenanceBytes{128};
};
// Stable identity of one completion candidate across a later resolve request.
struct Identity {
std::string name;
std::string path;
std::uint32_t line{}, character{};
auto operator<=>(const Identity &) const = default;
};
struct Candidate {
std::string label;
Kind kind{Kind::unknown};
std::string detail;
std::string provenance;
Identity identity;
auto operator<=>(const Candidate &) const = default;
};
struct Item {
std::string label;
Kind kind{Kind::unknown};
std::string detail;
std::string provenance;
std::string sort_text;
Identity identity;
// Byte offsets of the identifier prefix the item replaces.
std::size_t replacement_start{}, replacement_end{};
auto operator<=>(const Item &) const = default;
};
struct Result {
std::vector<Item> items;
// True until compiler-native completion exists; index candidates are not
// authoritative for visibility or accessibility.
bool incomplete{true};
std::string backend{"symbol-index"};
};
// Longest ASCII identifier prefix ending at the byte offset. Empty when the
// preceding text is not an identifier or the prefix starts with a digit.
[[nodiscard]] std::string_view prefix_at(std::string_view text, std::size_t offset);
// Filters candidates whose label starts with the prefix, deduplicates by label
// and kind, ranks deterministically (kind priority, shorter label, label) and
// bounds every field. The replacement range covers the prefix.
[[nodiscard]] Result complete(std::span<const Candidate>, std::string_view text, std::size_t offset,
const Limits & = Limits{});
// A candidate as the current index generation reports it.
struct Detail {
Identity identity;
Kind kind{Kind::unknown};
std::string detail;
std::string provenance;
auto operator<=>(const Detail &) const = default;
};
struct Resolved {
enum class Status { resolved, stale, unknown };
Status status{Status::unknown};
std::string documentation;
std::string detail;
};
// Resolves a captured candidate identity against the current generation.
// A changed generation is stale and an absent identity is unknown; neither
// ever returns details for a different entity. Documentation is bounded and
// fenced so that editor rendering cannot be escaped by the content.
[[nodiscard]] Resolved resolve(const Identity &, std::uint64_t captured_generation,
std::uint64_t current_generation, std::span<const Detail>,
const Limits & = Limits{});
} // namespace vls::features::completion
+34
View File
@@ -0,0 +1,34 @@
#pragma once
#include <vls/index/SymbolIndex.hpp>
#include <vls/navigation/Navigation.hpp>
#include <cstddef>
#include <span>
#include <string>
#include <string_view>
namespace vls::features {
// What the caller currently knows about one source path. Content identity is
// the same opaque value the index stored; an empty identity means the caller
// cannot prove the file's current content, so its facts stay non-editable.
struct IndexedSource {
std::string path;
std::string content;
bool editable{};
};
// Merges one published index generation into a navigation fact set.
//
// Contexts the set does not know yet are added with the index's completeness.
// Each record's use location and every proven reference become facts whose
// binding joins on name and definition. Facts are deduplicated by binding,
// source and use; an existing fact always wins, so compiler-derived content
// identities are never replaced by weaker index data. A record whose source
// is unknown stays in the set as a non-editable fact: rename then refuses
// instead of editing an unverified file. Returns the number of added facts.
std::size_t ingest_index_facts(navigation::FactSet &, const index::Generation &,
std::span<const IndexedSource>, std::size_t limit = 65536);
} // namespace vls::features
+62
View File
@@ -0,0 +1,62 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace vls::features::signature {
struct Limits {
std::size_t signatures{8};
std::size_t parameters{64};
std::size_t labelBytes{1024};
std::size_t parameterBytes{256};
std::size_t scanBytes{64 * 1024};
};
struct Parameter {
std::string label;
// Byte range of label within the signature label, when it can be located.
std::optional<std::pair<std::uint32_t, std::uint32_t>> range;
auto operator<=>(const Parameter &) const = default;
};
struct Signature {
std::string label;
std::vector<Parameter> parameters;
auto operator<=>(const Signature &) const = default;
};
struct Result {
std::vector<Signature> signatures;
std::uint32_t active_signature{};
std::uint32_t active_parameter{};
};
// Splits one compiler signature into a label and its parameter list. Commas
// nested in (), [], {} or a plausible template argument list do not separate
// parameters. A signature without a parameter list keeps an empty list.
[[nodiscard]] Signature parse(std::string_view signature, const Limits & = Limits{});
// Number of the active parameter at the byte offset: top-level commas between
// the innermost open parenthesis and the offset, ignoring literals, comments
// and nested brackets. The backward scan is bounded by the limit.
[[nodiscard]] std::uint32_t active_parameter(std::string_view text, std::size_t offset,
const Limits & = Limits{});
// True when the offset lies inside the argument list opened after the callee
// span [use_start, use_end): the first '(' after the span and its matching ')'
// must enclose the offset. The scan is bounded and ignores literals/comments.
[[nodiscard]] bool in_call(std::string_view text, std::size_t use_start, std::size_t use_end,
std::size_t offset, const Limits & = Limits{});
// Complete signature help for a call site. Empty or malformed signatures are
// skipped; an empty result means no signature is available.
[[nodiscard]] Result build(std::span<const std::string> signatures, std::string_view text,
std::size_t offset, const Limits & = Limits{});
} // namespace vls::features::signature
+158
View File
@@ -0,0 +1,158 @@
#pragma once
#include <compare>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <filesystem>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace vls::index {
// Zero-based LSP-style character coordinates within one physical line.
struct Location {
std::string path;
std::uint32_t line{}, character{};
std::uint32_t endLine{}, endCharacter{};
auto operator<=>(const Location &) const = default;
};
enum class SymbolKind { unknown, function, type, variable, field, namespace_, module };
struct SymbolRecord {
std::string name;
SymbolKind kind{SymbolKind::unknown};
Location location; // declaration or definition
std::optional<Location> definition;
std::vector<Location> references;
std::string provenance;
auto operator<=>(const SymbolRecord &) const = default;
};
struct Limits {
std::size_t contexts{64};
std::size_t records{65536};
std::size_t recordsPerContext{16384};
std::size_t referencesPerRecord{256};
std::size_t nameBytes{256};
std::size_t pathBytes{4096};
std::size_t snapshotBytes{32 * 1024 * 1024};
};
struct ContextInput {
std::string context; // Build::ContextKey alternative
std::vector<std::string> dependencies;
// Path and content identity of every source this context consumed.
std::vector<std::pair<std::string, std::string>> sources;
std::vector<SymbolRecord> records;
bool complete{true};
std::string reason;
};
struct Coverage {
bool indexed{}; // at least one context or overlay was considered
bool complete{};
std::vector<std::string> incomplete; // context names, sorted
auto operator<=>(const Coverage &) const = default;
};
struct Query {
std::string name;
bool substring{};
std::optional<std::string> context;
std::size_t limit{100};
};
struct Result {
std::vector<SymbolRecord> symbols;
Coverage coverage;
bool truncated{};
};
// Immutable published snapshot. Readers keep it alive across later publications
// and evictions.
class Generation {
public:
[[nodiscard]] std::uint64_t number() const noexcept { return number_; }
[[nodiscard]] const std::vector<SymbolRecord> &symbols() const noexcept { return records_; }
[[nodiscard]] const std::vector<std::pair<std::string, Coverage>> &contexts() const noexcept {
return contexts_;
}
private:
friend class SymbolIndex;
Generation(std::uint64_t number, std::vector<SymbolRecord> records,
std::vector<std::pair<std::string, Coverage>> contexts)
: number_(number), records_(std::move(records)), contexts_(std::move(contexts)) {}
std::uint64_t number_;
std::vector<SymbolRecord> records_;
std::vector<std::pair<std::string, Coverage>> contexts_;
};
// Context-aware, bounded symbol index. Committed records belong to explicit
// analysis contexts; unsaved document overlays shadow committed records for
// the same path and are reconciled on save/close. A changed, deleted or
// renamed source marks dependent contexts incomplete without discarding the
// last-good records (degraded navigation, never an authoritative rename).
class SymbolIndex {
public:
explicit SymbolIndex(Limits = Limits{});
~SymbolIndex();
SymbolIndex(const SymbolIndex &) = delete;
SymbolIndex &operator=(const SymbolIndex &) = delete;
// Atomically replaces one context and publishes a new generation.
[[nodiscard]] bool publish(const ContextInput &);
[[nodiscard]] bool remove(std::string_view context);
// Unsaved document records. The newest overlay for a path shadows the
// committed records of that path until it is cleared.
[[nodiscard]] bool set_overlay(std::string path, std::string content,
std::vector<SymbolRecord> records);
[[nodiscard]] bool clear_overlay(std::string_view path);
// A new content (or absence) invalidates every context that consumed the
// path. Matching content is a no-op.
[[nodiscard]] std::size_t invalidate(std::string_view path,
const std::optional<std::string> &content);
[[nodiscard]] Result find(const Query &) const;
[[nodiscard]] Coverage coverage() const;
[[nodiscard]] std::shared_ptr<const Generation> current() const;
[[nodiscard]] std::uint64_t generation() const;
[[nodiscard]] std::size_t records() const;
[[nodiscard]] const Limits &limits() const noexcept;
// Versioned persistence. restore() classifies the snapshot; incompatible or
// corrupt bytes are quarantined and the index rebuilds into a new generation.
enum class LoadStatus { loaded, missing, incompatible, corrupt, oversized };
struct LoadResult {
LoadStatus status{LoadStatus::missing};
std::uint64_t generation{};
std::optional<std::filesystem::path> quarantine;
// True when a schema-1 snapshot was accepted and upgraded in memory.
bool migrated{};
};
// Writes the versioned snapshot (schema 2 with a canonical payload digest).
// restore() also accepts schema 1 and reports the upgrade as migrated.
[[nodiscard]] bool save(const std::filesystem::path &) const;
[[nodiscard]] std::expected<LoadResult, std::string> restore(const std::filesystem::path &);
// True only when a compatible snapshot was loaded.
[[nodiscard]] bool load(const std::filesystem::path &);
// Generation-directory backend: each save keeps the previous generation for
// crash recovery, CURRENT selects the newest, and a legacy index.json is
// migrated on the first restore.
[[nodiscard]] bool save_generation(const std::filesystem::path &);
[[nodiscard]] std::expected<LoadResult, std::string>
restore_generation(const std::filesystem::path &);
private:
struct State;
std::shared_ptr<State> state_;
};
} // namespace vls::index
+83
View File
@@ -0,0 +1,83 @@
#pragma once
#include <vls/modules/ModuleGraph.hpp>
#include <compare>
#include <cstddef>
#include <expected>
#include <filesystem>
#include <functional>
#include <map>
#include <memory>
#include <optional>
#include <stop_token>
#include <string>
#include <string_view>
namespace vls::modules {
// Identity of one private module artifact. Compatibility covers frontend,
// target ABI, stdlib and flags; context names the producer; inputs binds the
// exact command, source and textual closure; kind distinguishes CMI/object.
struct ArtifactKey {
std::string compatibility, context, inputs, kind;
auto operator<=>(const ArtifactKey &) const = default;
[[nodiscard]] std::string identity() const;
};
struct ArtifactEntry {
ArtifactKey key;
std::filesystem::path path;
std::string sha256;
};
// An immutable, completely published generation. Readers retain it while
// eviction removes only generations no reader references.
class ArtifactGeneration {
public:
[[nodiscard]] const std::string &id() const noexcept { return id_; }
[[nodiscard]] const std::filesystem::path &root() const noexcept { return root_; }
[[nodiscard]] std::optional<ArtifactEntry> find(const ArtifactKey &key) const;
private:
friend class ArtifactCache;
ArtifactGeneration(std::string id, std::filesystem::path root,
std::map<ArtifactKey, ArtifactEntry> entries)
: id_(std::move(id)), root_(std::move(root)), entries_(std::move(entries)) {}
std::string id_;
std::filesystem::path root_;
std::map<ArtifactKey, ArtifactEntry> entries_;
};
// Private artifact cache. Publication is all-or-nothing and content addressed;
// a failed publication leaves no generation behind.
class ArtifactCache {
public:
explicit ArtifactCache(std::filesystem::path root, std::size_t retained = 2);
~ArtifactCache();
ArtifactCache(const ArtifactCache &) = delete;
ArtifactCache &operator=(const ArtifactCache &) = delete;
[[nodiscard]] std::expected<std::shared_ptr<const ArtifactGeneration>, std::string>
publish(const std::map<ArtifactKey, std::filesystem::path> &artifacts);
[[nodiscard]] std::shared_ptr<const ArtifactGeneration> current() const;
// Removes unreferenced generations beyond the retained limit.
std::size_t collect();
[[nodiscard]] std::size_t generations() const;
private:
struct State;
std::shared_ptr<State> state_;
};
// Produces one artifact per planned unit in dependency order. Any failure or
// cancellation removes the staging directory and publishes nothing.
using ArtifactWork = std::function<std::expected<std::filesystem::path, std::string>(
std::stop_token, const Build::ContextKey &, const std::filesystem::path &output)>;
[[nodiscard]] std::expected<std::shared_ptr<const ArtifactGeneration>, std::string>
produce_module_artifacts(const ModulePlan &plan, ArtifactCache &cache,
const std::filesystem::path &staging, ArtifactWork work,
std::stop_token stop = std::stop_token{});
} // namespace vls::modules
+39
View File
@@ -0,0 +1,39 @@
#pragma once
#include <vls/modules/ArtifactCache.hpp>
#include <chrono>
#include <cstddef>
#include <expected>
#include <filesystem>
#include <functional>
#include <optional>
#include <string>
#include <vector>
namespace vls::modules {
struct ModuleCommand {
std::filesystem::path working_directory;
// Absolute compiler path first. Arguments must not depend on the caller's
// working directory: the work runs in a private directory.
std::vector<std::string> arguments;
};
using ModuleCommandLookup = std::function<std::optional<ModuleCommand>(const Build::ContextKey &)>;
struct GccArtifactOptions {
std::chrono::milliseconds deadline{60000};
std::size_t max_output_bytes{64 * 1024 * 1024};
std::size_t max_artifact_bytes{512 * 1024 * 1024};
};
// Real GCC module artifact production for one planned unit: runs the looked-up
// command in a private working directory with a private module cache, requires
// exactly one verified CMI and copies it to `output`. Tool authority, the
// command's environment and its provenance are the caller's responsibility.
[[nodiscard]] ArtifactWork
gcc_module_artifact_work(ModuleCommandLookup lookup,
GccArtifactOptions options = GccArtifactOptions{});
} // namespace vls::modules
+45
View File
@@ -0,0 +1,45 @@
#pragma once
#include <vls/modules/ModuleGraph.hpp>
#include <chrono>
#include <cstddef>
#include <expected>
#include <filesystem>
#include <functional>
#include <memory>
#include <optional>
#include <stop_token>
#include <string>
#include <vector>
namespace vls::modules {
struct ScanCommand {
std::filesystem::path working_directory;
// Absolute compiler first. Must contain exactly one absolute -fdeps-file=.
std::vector<std::string> arguments;
ExpectedOutput output;
};
using ScanCommandLookup = std::function<std::optional<ScanCommand>(const Build::ContextKey &)>;
struct ScanProduct {
std::string p1689;
std::optional<ScanRule> rule;
};
struct ScanOptions {
std::filesystem::path directory; // private output directory
std::chrono::milliseconds deadline{60000};
std::size_t max_bytes{max_scan_bytes};
};
// Runs one checked P1689 scan command and decodes its dependency file. The
// product is filled only on success; a failure throws so the scheduler records
// a failed task. No compiler option comes from project metadata here.
[[nodiscard]] std::function<std::string(std::stop_token)>
gcc_module_scan_work(ScanCommandLookup lookup, Build::ContextKey context,
std::shared_ptr<ScanProduct> product, ScanOptions options = ScanOptions{});
} // namespace vls::modules
+227
View File
@@ -0,0 +1,227 @@
#pragma once
#include <Void/LanguageServer/Build/Model.hpp>
#include <compare>
#include <cstddef>
#include <expected>
#include <filesystem>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace vls::modules {
namespace Build = Void::LanguageServer::Build;
inline constexpr std::size_t max_scan_bytes = 256 * 1024, max_scan_depth = 16;
inline constexpr std::size_t max_field_bytes = 4096, max_rule_items = 512;
inline constexpr std::size_t max_units = 4096, max_graph_items = 32768;
inline constexpr std::size_t max_graph_bytes = 16 * 1024 * 1024;
struct ExpectedOutput {
std::filesystem::path working_directory;
std::string spelling;
bool operator==(const ExpectedOutput &other) const {
return working_directory.native() == other.working_directory.native() &&
spelling == other.spelling;
}
};
enum class LookupMethod { by_name, include_angle, include_quote };
struct ModuleDescription {
std::string logical_name;
std::optional<std::string> source_path, compiled_module_path;
bool unique_on_source_path{};
auto operator<=>(const ModuleDescription &) const = default;
};
struct ProvidedModule : ModuleDescription {
bool is_interface{true};
auto operator<=>(const ProvidedModule &) const = default;
};
struct RequiredModule : ModuleDescription {
LookupMethod lookup{LookupMethod::by_name};
auto operator<=>(const RequiredModule &) const = default;
};
enum class ScanError {
invalid_json,
invalid_shape,
unsupported_version,
unsupported_field,
invalid_invocation,
wrong_directory,
wrong_output,
limit
};
// GCC 16.2 single-rule version 0, revision 0. Only the decoder constructs rules.
class ScanRule {
public:
const ExpectedOutput &output() const { return output_; }
const auto &additional_outputs() const { return additional_outputs_; }
const auto &provides() const { return provides_; }
const auto &requirements() const { return requirements_; }
std::size_t wire_bytes() const { return wire_bytes_; }
private:
friend std::expected<ScanRule, ScanError> decode_scan(std::string_view, const ExpectedOutput &);
ScanRule() = default;
ExpectedOutput output_;
std::vector<std::string> additional_outputs_;
std::vector<ProvidedModule> provides_;
std::vector<RequiredModule> requirements_;
std::size_t wire_bytes_{};
};
using ScanResult = std::expected<ScanRule, ScanError>;
[[nodiscard]] ScanResult decode_scan(std::string_view bytes, const ExpectedOutput &expected);
// The input owner admits this compatible set. Compatibility identifies frontend, target ABI,
// stdlib, flags/environment affecting module interchange. Lookup covers all ordered search
// roots, including misses, shadowing, overlays and generated inputs.
struct ModuleDomain {
Build::Generation generation;
std::string compatibility, lookup;
bool operator==(const ModuleDomain &) const = default;
};
// Collision-checked identities for the exact invocation, owning source and immutable transitive
// inputs. textual_closure includes header contents behind staged imports and their relevant
// artifact generations. A user-only depfile additionally needs independently sealed system inputs.
struct UnitInputs {
std::string command, source, textual_closure;
std::optional<std::string> system_closure;
bool operator==(const UnitInputs &) const = default;
};
// Provenance from staging an immutable header CMI. The scanner separately identifies the
// generation it actually consumed. source_identity names the resolved header across spellings.
struct StagedHeader {
std::string generation, source_identity;
ModuleDomain domain;
Build::ContextKey producer;
UnitInputs inputs;
bool operator==(const StagedHeader &) const = default;
};
struct CensusMember {
Build::ContextKey context;
ExpectedOutput output;
UnitInputs inputs;
// Changes on scanner replacement, even for equal source/command or a formerly absent rule.
std::string scan_revision;
std::optional<StagedHeader> staged_header;
bool operator==(const CensusMember &) const = default;
};
struct ModuleCensus {
ModuleDomain domain;
std::string revision;
bool closed{};
// All eligible commands in this dependency domain. Other BuildGeneration alternatives
// remain invisible. Distinct visibility sets require distinct censuses.
std::vector<CensusMember> members;
};
enum class ScanMethod { unknown, preprocess_md, preprocess_mmd, missing_allowed };
enum class UnitKind {
unknown,
ordinary,
implementation,
primary_interface,
interface_partition,
internal_partition,
header_unit
};
struct HeaderProvision {
std::size_t index{}; // Index in ScanRule::provides().
std::string source_identity;
};
struct HeaderUse {
std::size_t index{}; // Index in ScanRule::requirements().
std::string source_identity;
std::optional<std::string> loaded_generation;
};
struct ScanEvidence {
ModuleDomain domain;
Build::ContextKey context;
UnitInputs inputs;
std::string scan_revision;
std::optional<int> exit_status;
std::optional<ScanResult> rule;
ScanMethod method{ScanMethod::unknown};
// The owner proves a complete pass under these inputs (including generated inputs) and
// classifies every header-unit provision from its actual invocation and resolved source.
bool complete{};
// Implementation and ordinary importer can have identical rules. Only independent frontend
// evidence can set one of these two kinds on an import-only TU.
UnitKind import_only_kind{UnitKind::unknown};
std::vector<HeaderProvision> provided_headers;
// Engaged empty means the owner positively established absence of header-unit imports.
// Bindings attest every reported lookup/source spelling to the resolved source identity.
std::optional<std::vector<HeaderUse>> header_uses;
// Verified writer identities in primary-output, then additional_outputs() order. An
// isolated invocation can bind the same spelling to a different private destination.
std::vector<std::string> writers;
};
enum class PlanIssue {
incomplete_census,
invalid_context,
wrong_domain,
duplicate_member,
missing_scan,
duplicate_scan,
scan_failed,
missing_rule,
invalid_rule,
stale_scan,
missing_source,
incomplete_inputs,
incomplete_scan,
unproven_mapping,
missing_provider,
duplicate_provider,
stale_header,
writer_collision,
cycle,
limit
};
struct Blocker {
PlanIssue code{};
std::optional<std::size_t> unit; // Index in ModulePlan::units, when available.
std::string detail;
std::optional<ScanError> scan_error;
auto operator<=>(const Blocker &) const = default;
};
struct PlannedUnit {
CensusMember member;
UnitKind kind{UnitKind::unknown};
// Indices in ModulePlan::units. These are direct consumers across the admitted census.
std::vector<std::size_t> consumers;
};
struct ModulePlan {
ModuleDomain domain;
std::string census_revision;
std::vector<PlannedUnit> units; // Ascending ContextKey order.
// Prerequisites first, requested TU last. Failure leaves the order empty.
std::vector<Build::ContextKey> order;
std::vector<Blocker> blockers;
// All eligible scans can establish provider claims. A complete census may still have
// missing imports, duplicate providers, conflicting writers or cycles. Unproven claims
// withhold unit kinds and reverse edges.
bool claims_complete{};
[[nodiscard]] bool ready() const {
return claims_complete && !order.empty() && blockers.empty();
}
// Also checks non-reachable members. A renamed or newly visible provider can change a
// previous successful or missing lookup without having had any positive reverse edge.
[[nodiscard]] bool matches_census(const ModuleCensus &current) const;
};
[[nodiscard]] ModulePlan build_module_plan(const ModuleCensus &census,
std::span<const ScanEvidence> scans,
const Build::ContextKey &requested);
} // namespace vls::modules
+57
View File
@@ -0,0 +1,57 @@
#pragma once
#include <vls/scheduler/Scheduler.hpp>
#include <cstdint>
#include <functional>
#include <map>
#include <mutex>
#include <string>
#include <string_view>
namespace vls::modules {
enum class ModuleWorkKind { scan, artifact };
struct ModuleTaskResult {
std::string document;
ModuleWorkKind kind{ModuleWorkKind::scan};
std::uint64_t revision{};
scheduler::Outcome outcome{scheduler::Outcome::failed};
std::string detail;
};
using ModuleWork = std::function<std::string(std::stop_token)>;
// Editor-facing module work admission on the shared bounded scheduler.
// Scans run at background priority and artifact preparation at artifact
// priority, so neither delays foreground editor requests. A newer revision of
// one kind supersedes queued work and cancels running work; closing or editing
// a document cancels both kinds.
class ModuleWorkQueue {
public:
explicit ModuleWorkQueue(scheduler::Scheduler &scheduler);
ModuleWorkQueue(const ModuleWorkQueue &) = delete;
ModuleWorkQueue &operator=(const ModuleWorkQueue &) = delete;
// False for a stale revision, an empty key or a refused scheduler admission.
[[nodiscard]] bool submit(
std::string document, ModuleWorkKind kind, std::uint64_t revision, ModuleWork work,
std::function<void(ModuleTaskResult)> completion = std::function<void(ModuleTaskResult)>{});
void cancel(std::string_view document);
void cancel_all();
struct Counts {
std::uint64_t submitted{}, completed{}, cancelled{}, failed{};
};
[[nodiscard]] Counts counts() const;
private:
[[nodiscard]] static std::string key(std::string_view document, ModuleWorkKind kind);
scheduler::Scheduler &scheduler_;
mutable std::mutex mutex_;
std::map<std::string, std::uint64_t> revisions_[2];
Counts counts_;
};
} // namespace vls::modules
+34
View File
@@ -0,0 +1,34 @@
#pragma once
#include <vls/modules/ModuleGraph.hpp>
#include <expected>
#include <filesystem>
#include <string>
#include <vector>
namespace vls::modules {
enum class ScanCommandError {
invalid_context,
missing_source,
duplicate_source,
relative_dependency_file,
limit
};
struct ScanInvocation {
// Driver first, then the original checked arguments with the scan options
// appended. The owning source is the final operand.
std::vector<std::string> arguments;
};
// Derives a P1689 scan command from a checked compiler context. The driver and
// owning source come from the context itself; the dependency file must be
// absolute. Existing output, preprocess and dependency options are removed so
// project metadata cannot select or duplicate the scan outputs.
[[nodiscard]] std::expected<ScanInvocation, ScanCommandError>
build_scan_invocation(const Build::BuildContext &context, const ExpectedOutput &output,
const std::filesystem::path &dependency_file);
} // namespace vls::modules
@@ -0,0 +1,23 @@
#pragma once
#include <vls/modules/ArtifactCache.hpp>
#include <vls/scheduler/Scheduler.hpp>
#include <expected>
#include <filesystem>
#include <memory>
#include <stop_token>
#include <string>
namespace vls::modules {
// Produces the planned units in dependency order through the shared scheduler
// at artifact priority. A superseded, cancelled, timed-out or failed unit
// publishes nothing; the staging directory is always removed.
[[nodiscard]] std::expected<std::shared_ptr<const ArtifactGeneration>, std::string>
produce_module_artifacts_scheduled(const ModulePlan &plan, ArtifactCache &cache,
const std::filesystem::path &staging, ArtifactWork work,
scheduler::Scheduler &scheduler,
std::stop_token stop = std::stop_token{});
} // namespace vls::modules
+111
View File
@@ -0,0 +1,111 @@
#pragma once
#include <compare>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <map>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace vls::navigation {
struct Position {
std::uint32_t line{}, character{};
auto operator<=>(const Position &) const = default;
};
struct Range {
Position start, end;
auto operator<=>(const Range &) const = default;
};
struct Location {
std::string path;
Range range;
auto operator<=>(const Location &) const = default;
};
// Semantic identity of one binding. The definition location joins equal
// symbols across analysis contexts; the name distinguishes unrelated symbols
// without a proven definition.
struct Binding {
std::string name;
std::optional<Location> definition;
auto operator<=>(const Binding &) const = default;
};
struct Fact {
Binding binding;
std::string context;
std::string source; // use file
std::string content; // content identity of the observed source
Range use;
bool editable{};
std::string provenance;
};
struct ContextState {
std::string context;
bool complete{};
std::string reason;
};
struct FactSet {
std::string backend;
std::uint64_t generation{};
std::vector<Fact> facts;
std::vector<ContextState> contexts;
std::map<std::string, std::string> current_sources; // path -> current content
};
enum class Refusal {
none,
unknown_binding,
ambiguous_binding,
incomplete_coverage,
stale_source,
non_editable_origin,
generated_name,
invalid_name,
unchanged_name,
multi_file_without_transaction,
};
struct References {
std::vector<Location> locations;
bool coverage_complete{};
std::vector<std::string> incomplete_contexts;
bool truncated{};
};
struct Edit {
std::string path;
Range range;
std::string replacement;
std::string content; // content identity the edit was prepared against
};
struct RenamePlan {
Refusal refusal{Refusal::none};
std::string detail;
std::vector<Edit> edits;
[[nodiscard]] bool ready() const { return refusal == Refusal::none && !edits.empty(); }
};
// Resolves the unique binding at a position. Overlapping distinct bindings are
// ambiguous and never resolved by iteration order.
[[nodiscard]] std::expected<Binding, Refusal> binding_at(const FactSet &, std::string_view path,
Position);
// All proven uses. Partial locations are retained for diagnosis, but
// coverage_complete is false whenever any context is incomplete.
[[nodiscard]] References references(const FactSet &, const Binding &, std::size_t limit = 512);
// Only a ready plan may be applied. Refusals are explicit for incomplete
// coverage, stale sources, non-editable origins, ambiguous bindings,
// generated/invalid names and multi-file edits without a transactional client.
[[nodiscard]] RenamePlan prepare_rename(const FactSet &, std::string_view path, Position,
std::string_view replacement, bool transactional_client);
} // namespace vls::navigation
+243
View File
@@ -0,0 +1,243 @@
#pragma once
#include <compare>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace vls::reflection {
// Version of the provenance/value snapshot schema. Derived index and trace
// renderers must reject an incompatible version rather than reinterpret it.
inline constexpr std::uint32_t schema_version = 1;
// Canonical, context-qualified semantic identity of one reflected or generated
// entity. It is assigned by the extractor from compiler state; this library
// never invents an identity from a source string.
using EntityId = std::string;
struct Range {
std::string path;
std::uint32_t line{}, character{}, endLine{}, endCharacter{};
auto operator<=>(const Range &) const = default;
};
// What one link of a provenance chain represents. A spelling is an editable
// token; expansion and splice sites are the generated constructs that produced
// a token; a reflected declaration is the original entity behind a splice; a
// synthesized entity has no editable spelling at all.
enum class OriginKind {
spelling,
expansion,
splice,
reflected_declaration,
synthesized,
};
struct Origin {
OriginKind kind{OriginKind::synthesized};
std::optional<Range> range; // absent when the compiler gave no location
std::optional<EntityId> entity; // reflected or generated entity identity
std::string note; // proposal/facility or instantiation context
auto operator<=>(const Origin &) const = default;
};
// Innermost origin first. A generated entity can stay navigable through the
// chain while remaining non-editable: generated names without a reliable
// editable origin are never automatically renameable.
struct Provenance {
std::vector<Origin> origins;
bool gap{}; // at least one link in the chain is unavailable
std::string context; // snapshot/instantiation identity
[[nodiscard]] bool navigable() const; // some origin carries a real range
[[nodiscard]] bool editable() const; // complete chain rooted at a spelling
auto operator<=>(const Provenance &) const = default;
};
enum class ValueKind {
integral,
text,
boolean,
entity,
opaque, // a real value the compiler cannot render; text is the reason
unavailable, // the value could not be obtained; text is the reason
};
struct Value {
ValueKind kind{ValueKind::unavailable};
std::int64_t integral{};
bool boolean{};
std::string text; // text value, or the reason for opaque/unavailable
std::string type; // canonical type spelling when the compiler provides it
EntityId entity; // referenced entity when kind is entity
auto operator<=>(const Value &) const = default;
};
struct Member {
std::string name;
Value value;
auto operator<=>(const Member &) const = default;
};
// One real reflected or synthesized entity. Members may reference other
// entities; expansion resolves those references lazily and boundedly.
struct Entity {
EntityId id;
std::string name;
std::string type;
std::vector<Member> members;
Provenance provenance;
bool synthesized{};
auto operator<=>(const Entity &) const = default;
};
struct Limits {
std::size_t entities{4096};
std::size_t membersPerEntity{64};
std::size_t originsPerProvenance{16};
std::size_t nameBytes{256};
std::size_t typeBytes{1024};
std::size_t textBytes{4096};
std::size_t contextBytes{1024};
std::size_t snapshotBytes{8 * 1024 * 1024};
std::size_t expansionDepth{8};
std::size_t expansionValues{1024};
std::size_t capabilities{256};
};
// Flattened, depth-first expansion of one entity. Cycles and limit cuts are
// explicit paths, never silently omitted values.
struct Expansion {
struct Entry {
std::string path; // member path from the root, e.g. "outer.inner"
std::size_t depth{};
ValueKind kind{ValueKind::unavailable};
std::string type;
std::string text;
EntityId entity;
std::optional<Range> link; // source range of the referenced entity
auto operator<=>(const Entry &) const = default;
};
std::vector<Entry> entries;
std::vector<std::string> cycles; // repeated entity on the current path
std::vector<std::string> truncated; // cut by depth or value count
[[nodiscard]] bool complete() const { return cycles.empty() && truncated.empty(); }
};
// One explanation line of a virtual generated view. A line is a semantic
// explanation, never compilable text: it may be indented prose with a source
// link, and consumers must never feed it back to a compiler.
struct VirtualLine {
std::string text;
std::size_t depth{};
std::optional<Range> link;
auto operator<=>(const VirtualLine &) const = default;
};
struct VirtualView {
std::vector<VirtualLine> lines;
bool truncated{};
// Virtual generated views are read-only explanations by construction.
[[nodiscard]] bool compilable() const { return false; }
};
// LSP-shaped hover for one entity: a semantic explanation plus the source
// links it explains. The markup is Markdown but never compilable text.
struct Hover {
std::string markup;
std::optional<Range> range;
auto operator<=>(const Hover &) const = default;
};
// Navigation targets in provenance-chain order, deduplicated and bounded.
// A generated entity stays navigable through the chain that produced it.
[[nodiscard]] std::vector<Range> locations(const Provenance &, std::size_t limit = 16);
// Renders one entity and its bounded expansion as a read-only semantic
// explanation with source links. Cycles, truncation and opaque values stay
// explicit; the result is never compilable text.
[[nodiscard]] VirtualView render(const Entity &, const Expansion &, const Limits & = Limits{});
// LSP-shaped hover markup for one entity and its expansion, with the entity's
// first source range. The markup lists the virtual view and its source links.
[[nodiscard]] Hover hover(const Entity &, const Expansion &, const Limits & = Limits{});
// Bounded snapshot of one analysis generation. Serialization is versioned and
// every consumer validates its own limits before trusting the bytes.
class Snapshot {
public:
explicit Snapshot(Limits = Limits{});
// Rejects duplicates, oversized strings, too many entities or members.
[[nodiscard]] bool add(Entity);
[[nodiscard]] bool contains(const EntityId &) const;
[[nodiscard]] const Entity *find(const EntityId &) const;
[[nodiscard]] const std::vector<Entity> &entities() const noexcept;
[[nodiscard]] std::size_t size() const;
[[nodiscard]] const Limits &limits() const noexcept;
// Depth-first expansion of one entity. Unknown identities are an error.
[[nodiscard]] std::expected<Expansion, std::string>
expand(const EntityId &, std::optional<std::size_t> depth = std::nullopt) const;
[[nodiscard]] std::expected<std::string, std::string> serialize() const;
[[nodiscard]] static std::expected<Snapshot, std::string> parse(std::string_view,
Limits = Limits{});
private:
Limits limits_;
std::vector<Entity> entities_;
};
// Proposal/facility support declared by the accepted backend. An unknown entry
// is an explicit capability error; it never falls back to a lexical answer.
struct Capability {
std::string proposal; // e.g. "P2996"
std::string facility; // e.g. "splices"
bool supported{};
std::string reason; // required when unsupported
auto operator<=>(const Capability &) const = default;
};
class Capabilities {
public:
explicit Capabilities(Limits = Limits{});
// Rejects duplicates, oversized fields and an unsupported entry without a
// reason.
[[nodiscard]] bool add(Capability);
[[nodiscard]] std::expected<Capability, std::string> query(std::string_view proposal,
std::string_view facility) const;
[[nodiscard]] std::size_t size() const;
private:
Limits limits_;
std::vector<Capability> entries_;
};
// One splice origin reported by the compiler: the splice site and the entity
// it designates. Columns are 1-based UTF-8 byte offsets. The compiler reports
// a start coordinate only, so ranges are zero-width until an end is available.
struct SpliceOrigin {
std::string source;
std::uint32_t line{}, byteColumn{};
std::string targetKind; // "declaration", "type" or "value"
std::string targetName;
std::string targetSource;
std::optional<std::uint32_t> targetLine, targetByteColumn;
};
// Composes entities from compiler-reported splice origins. Identity is
// composed from the reported target kind, name and declaration location; the
// provenance chain is the splice site followed by the reflected declaration,
// or an explicit gap when the compiler reported no target location. The first
// chain for an identity wins and the result stays within the snapshot limits.
[[nodiscard]] Snapshot snapshot_from_splices(std::span<const SpliceOrigin>, Limits = Limits{});
} // namespace vls::reflection
+82
View File
@@ -0,0 +1,82 @@
#pragma once
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <stop_token>
#include <string>
#include <string_view>
namespace vls::scheduler {
enum class Priority { artifact = 0, background = 1, foreground = 2 };
struct Budget {
std::size_t foreground{4};
std::size_t background{2};
std::size_t artifact{1};
std::size_t queued{64};
std::size_t memory_mib{1024};
std::chrono::milliseconds watchdog{30000};
[[nodiscard]] bool valid() const noexcept;
};
enum class Outcome { completed, failed, cancelled, timed_out };
struct Estimate {
Priority priority{Priority::background};
std::string key;
std::uint64_t revision{};
std::size_t memory_mib{};
};
struct Result {
std::string key;
std::uint64_t revision{};
Outcome outcome{Outcome::failed};
std::string detail;
};
struct Metrics {
std::uint64_t accepted{}, completed{}, failed{}, cancelled{}, timed_out{}, rejected{};
std::size_t queued_peak{}, running_peak{}, running_memory_peak{};
std::uint64_t queue_nanoseconds{}, run_nanoseconds{};
};
// Work returns a detail string on success or throws on failure. It must honor
// the stop token so cancellation and the running watchdog stay bounded.
using Work = std::function<std::string(std::stop_token)>;
using Completion = std::function<void(Result)>;
// Bounded, priority-separated executor. Foreground, background and artifact
// pools have reserved capacity, so a saturated background queue never delays a
// foreground request. Every accepted submission receives exactly one terminal
// completion; a refused submission receives none and returns false.
class Scheduler {
public:
explicit Scheduler(Budget = Budget{});
~Scheduler();
Scheduler(const Scheduler &) = delete;
Scheduler &operator=(const Scheduler &) = delete;
Scheduler(Scheduler &&) = delete;
Scheduler &operator=(Scheduler &&) = delete;
// A newer revision of the same key supersedes queued work immediately and
// requests cooperative cancellation of running work.
[[nodiscard]] bool submit(Estimate, Work, Completion);
void cancel(std::string_view key);
void cancel_all();
// Waits until every accepted submission has reached a terminal result.
void drain();
[[nodiscard]] Metrics metrics() const;
[[nodiscard]] const Budget &budget() const noexcept;
private:
struct State;
std::unique_ptr<State> state_;
};
} // namespace vls::scheduler
+109
View File
@@ -0,0 +1,109 @@
#pragma once
#include <Void/LanguageServer/Documents/DocumentSnapshot.hpp>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace vls::semantic {
namespace Documents = Void::LanguageServer::Documents;
using DiagnosticSnapshot = std::shared_ptr<const Documents::DocumentSnapshot>;
// GCC can emit literal filenames, including percent signs. These spellings are
// supplied by the launcher and are compared exactly, without URL decoding.
struct ArtifactName {
std::string uri, base_uri;
auto operator<=>(const ArtifactName &) const = default;
};
struct DiagnosticArtifact {
ArtifactName name;
DiagnosticSnapshot snapshot;
};
struct ReportedRegion {
std::uint32_t first_line, first_column, last_line, end_column;
};
enum class ColumnUnit { ascii_consensus, utf8_bytes, gcc_display };
enum class FirstLineBom { unknown, counted, skipped };
struct CoordinatePolicy {
ColumnUnit unit{ColumnUnit::ascii_consensus};
unsigned tabstop{8};
FirstLineBom bom{FirstLineBom::unknown};
};
struct LocationRequest {
const DiagnosticArtifact &artifact;
ReportedRegion region;
std::size_t result_index, location_index;
bool related;
};
struct DiagnosticJob {
std::string invocation_id, input_view_id;
DiagnosticSnapshot owner;
std::vector<DiagnosticArtifact> artifacts;
// The input owner accounts for unresolved includes and lookup dependencies.
bool inputs_complete{};
// Return a policy only for a proven physical location in the immutable
// inputs. A matching snippet cannot establish the origin of a #line remap.
std::function<std::optional<CoordinatePolicy>(const LocationRequest &)> physical_origin;
};
struct DiagnosticOutput {
std::string_view invocation_id, input_view_id;
std::optional<int> exit_code;
bool stream_complete{};
std::string_view sarif;
};
enum class DiagnosticError {
invalid_job,
wrong_capture,
incomplete_stream,
failed_process,
malformed_report,
unsupported_report,
wrong_owner,
tool_failure,
resource_limit
};
enum class LocationGap {
none,
no_location,
unknown_artifact,
artifact_mismatch,
incomplete_region,
unproven_origin,
ambiguous_column
};
struct DiagnosticLocation {
LocationGap gap{LocationGap::no_location};
DiagnosticSnapshot snapshot;
std::optional<Documents::Range> range;
};
struct RelatedLocation {
std::string message;
DiagnosticLocation location;
};
enum class DiagnosticSeverity { error, warning, information, hint };
struct CompilerDiagnostic {
DiagnosticSeverity severity;
std::string message, rule;
DiagnosticLocation location;
std::vector<RelatedLocation> related;
};
struct DiagnosticBatch {
std::string invocation_id, input_view_id;
DiagnosticSnapshot owner;
std::vector<CompilerDiagnostic> diagnostics;
// The publisher must still validate that this invocation is current.
bool complete_for_owner{};
};
[[nodiscard]] std::expected<DiagnosticBatch, DiagnosticError>
decode_gcc_diagnostics(const DiagnosticJob &, const DiagnosticOutput &);
} // namespace vls::semantic
@@ -0,0 +1,65 @@
#pragma once
#include <vls/semantic/StockCompiler.hpp>
#include <functional>
namespace vls::semantic {
// The input thread brackets document and workspace transitions. The analysis worker
// publishes through the same ordered output queue as request responses.
class EditorDiagnostics {
public:
using Send = std::function<bool(std::string)>;
EditorDiagnostics(const std::filesystem::path &root, std::shared_ptr<const GccProfile>,
WorkspaceSession &, const Documents::DocumentStore &, Send);
~EditorDiagnostics();
void set_version_support(bool);
void begin_update();
void finish_update(bool workspace_changed = false);
void stop();
[[nodiscard]] Void::LanguageServer::Protocol::Json status(std::string_view uri) const;
[[nodiscard]] bool supports_occurrences() const noexcept;
// Bounded workspace symbol search over the context-aware index.
[[nodiscard]] Void::LanguageServer::Protocol::Json
workspace_symbols(std::string_view query) const;
// Index-backed completion for the identifier prefix before the position.
// Items are explicitly marked incomplete until compiler-native completion
// exists; visibility is not proven by the index.
[[nodiscard]] Void::LanguageServer::Protocol::Json
completion(std::string_view uri, Documents::Position position) const;
// Compiler-provided call signature at the position, or null when no
// verified occurrence carries one.
[[nodiscard]] Void::LanguageServer::Protocol::Json
signature_help(std::string_view uri, Documents::Position position) const;
// Deferred completion detail. The item's data carries the captured
// identity and index generation; a changed generation returns the item
// without details rather than details for a different entity.
[[nodiscard]] Void::LanguageServer::Protocol::Json
completion_resolve(const Void::LanguageServer::Protocol::Json &item) const;
struct NavigationReply {
Void::LanguageServer::Protocol::Json result;
std::optional<std::string> refusal;
};
// A refusal means the answer would be incomplete or unsafe; the result is
// retained for diagnosis but must not be presented as complete.
[[nodiscard]] NavigationReply references(std::string_view uri,
Documents::Position position) const;
[[nodiscard]] NavigationReply prepare_rename(std::string_view uri,
Documents::Position position) const;
[[nodiscard]] NavigationReply rename(std::string_view uri, Documents::Position position,
std::string_view replacement) const;
void set_transactional_rename(bool supported);
// Answers are null when no verified occurrence covers the requested position.
[[nodiscard]] Void::LanguageServer::Protocol::Json hover(std::string_view uri,
Documents::Position position) const;
[[nodiscard]] Void::LanguageServer::Protocol::Json
definition(std::string_view uri, Documents::Position position) const;
private:
struct State;
std::unique_ptr<State> state_;
};
} // namespace vls::semantic
+42
View File
@@ -0,0 +1,42 @@
#pragma once
#include <vls/semantic/Diagnostics.hpp>
#include <vls/semantic/SourceCatalog.hpp>
#include <expected>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace vls::semantic {
// A compiler-owned direct-call fact. Byte spans from the stock observer are
// already converted to the captured snapshot's negotiated character positions.
struct Occurrence {
std::string name, type, canonical_type, signature;
DiagnosticSnapshot use_file;
Documents::Range use;
DiagnosticSnapshot definition_file;
Documents::Range definition;
[[nodiscard]] bool has_definition() const noexcept { return definition_file != nullptr; }
};
struct OccurrenceReport {
std::vector<Occurrence> occurrences;
bool complete{};
bool partial{};
std::string reason;
};
enum class OccurrenceError { invalid_report, wrong_nonce };
// Decode a stock-observer report against the exact capture that was compiled.
// Unknown paths, byte spans that do not match the captured bytes, duplicates
// and malformed envelopes reject the whole report.
[[nodiscard]] std::expected<OccurrenceReport, OccurrenceError>
decode_occurrences(std::string_view report, std::string_view nonce,
std::span<const CapturedSource> capture);
} // namespace vls::semantic
+118
View File
@@ -0,0 +1,118 @@
#pragma once
#include <Void/LanguageServer/Build/Model.hpp>
#include <Void/LanguageServer/Documents/DocumentStore.hpp>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <ctime>
#include <expected>
#include <filesystem>
#include <functional>
#include <memory>
#include <mutex>
#include <span>
#include <vector>
namespace vls::semantic {
namespace Documents = Void::LanguageServer::Documents;
struct SourceScope {
Void::LanguageServer::Build::WorkspaceIdentity workspace;
std::uint64_t configuration, trust;
bool operator==(const SourceScope &) const = default;
};
enum class SourceIssue {
wrong_authority,
invalid_path,
outside_scope,
unsupported_route,
conflicting_names,
missing,
missing_parent,
not_regular,
hard_link,
unavailable,
unavailable_overlay,
invalid_text,
changed,
resource_limit
};
struct SourceError {
SourceIssue issue;
std::filesystem::path path;
};
struct SourceRequest {
std::filesystem::path path;
bool allow_missing{};
// Observe a file, directory or missing route without opening file payloads.
bool lookup_only{};
};
struct SourceLimits {
std::size_t files{1024};
std::size_t name_bytes{512 * 1024};
std::size_t file_bytes{16 * 1024 * 1024};
std::size_t total_bytes{32 * 1024 * 1024};
std::size_t descriptors{256};
};
enum class SourceNode { missing, directory, regular };
struct CapturedSource {
std::filesystem::path logical_path;
// Content requests retain the selected snapshot. Lookup-only requests retain the node kind.
std::shared_ptr<const Documents::DocumentSnapshot> snapshot;
SourceNode node{SourceNode::missing};
// GCC's __TIMESTAMP__ depends on the input file's modification time in seconds.
std::optional<std::time_t> modified_at{};
};
struct SourceGrant;
using InstalledSourceGrant = std::shared_ptr<const SourceGrant>;
struct SourceEvidence;
struct SourceAccounting;
class SourceCapture {
public:
SourceCapture(const SourceCapture &) = delete;
[[nodiscard]] std::span<const CapturedSource> entries() const noexcept { return entries_; }
private:
friend class SourceCatalog;
explicit SourceCapture(std::shared_ptr<SourceEvidence> evidence);
std::shared_ptr<SourceEvidence> evidence_;
std::vector<CapturedSource> entries_;
};
// The workspace owner installs only its explicitly authorized source directories.
// Captures witness the requested names. A worker must separately establish lookup closure.
class SourceCatalog {
public:
// The owning session keeps its document store alive for the catalog's lifetime.
explicit SourceCatalog(const Documents::DocumentStore &documents,
std::function<void()> before_capture_validation = {});
[[nodiscard]] std::expected<InstalledSourceGrant, SourceError>
install(const SourceScope &scope, std::span<const std::filesystem::path> directories);
void revoke();
[[nodiscard]] std::expected<std::shared_ptr<const SourceCapture>, SourceError>
capture(const SourceScope &job, const InstalledSourceGrant &grant,
const Documents::FileOverlayInventory &census, std::span<const SourceRequest> requests,
SourceLimits limits = {}) const;
[[nodiscard]] std::expected<void, SourceError> validate(const SourceScope &job,
const SourceCapture &capture) const;
private:
const Documents::DocumentStore &documents_;
std::mutex installations_;
std::atomic<InstalledSourceGrant> installed_;
std::shared_ptr<SourceAccounting> accounting_;
std::function<void()> before_capture_validation_;
};
} // namespace vls::semantic
+79
View File
@@ -0,0 +1,79 @@
#pragma once
#include <vls/WorkspaceSession.hpp>
#include <vls/semantic/Diagnostics.hpp>
#include <vls/semantic/Occurrences.hpp>
#include <vls/semantic/SourceCatalog.hpp>
#include <expected>
#include <filesystem>
#include <memory>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <vector>
namespace vls::semantic {
class GccProfile {
public:
// Only the launcher selects this file for its explicitly selected workspace.
static std::expected<std::shared_ptr<const GccProfile>, std::string>
load(const std::filesystem::path &file);
// Prepares the profile in process from the selected GCC driver. No
// external script or pre-generated JSON is required.
static std::expected<std::shared_ptr<const GccProfile>, std::string>
prepare(const std::filesystem::path &driver);
std::filesystem::path driver, frontend, bubblewrap, strace, prlimit;
std::vector<std::filesystem::path> mounts;
// Optional launcher-selected occurrence observer. Its exact bytes are
// re-verified for every job; metadata cannot select or alter it.
std::filesystem::path observer;
std::string observer_identity;
std::string target, flags, identity;
[[nodiscard]] bool observes() const noexcept { return !observer.empty(); }
private:
GccProfile() = default;
};
struct StockAnalysis {
DiagnosticBatch batch;
std::shared_ptr<const SourceCapture> sources;
Void::LanguageServer::Build::Revision revision;
// Present only when the launcher-selected observer produced a verified report.
std::optional<OccurrenceReport> occurrences;
// Why occurrence facts are unavailable when the observer was selected.
std::string occurrence_detail;
// Hints for the next run. Each new job reacquires and verifies all positive and negative
// inputs.
std::vector<std::filesystem::path> lookups;
std::size_t compiler_runs{};
std::optional<std::filesystem::path> unproven_location_origin;
};
// One job owns an isolated filesystem and runs the regular GCC frontend. Caller revalidates
// the lease and capture before delivering diagnostics to an editor.
[[nodiscard]] std::expected<StockAnalysis, std::string>
analyze_with_gcc(const GccProfile &profile, const SemanticContextLease &lease,
const Documents::DocumentStore &documents, const SourceCatalog &catalog,
const InstalledSourceGrant &grant, std::uint64_t sequence,
std::span<const std::filesystem::path> previous_lookups, std::stop_token stop);
struct StockScan {
std::vector<std::string> provides, imports;
bool complete{};
};
// Runs the checked P1689 scan for the selected translation unit in the same
// isolated compiler view. The caller owns admission and cancellation.
[[nodiscard]] std::expected<StockScan, std::string>
scan_modules_with_gcc(const GccProfile &profile, const SemanticContextLease &lease,
const Documents::DocumentStore &documents, const SourceCatalog &catalog,
const InstalledSourceGrant &grant,
std::span<const std::filesystem::path> previous_lookups,
std::stop_token stop);
} // namespace vls::semantic