From 946b1a005ecf43f808079021a412125435091e0c Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Sat, 5 Dec 2026 15:03:21 +0300 Subject: [PATCH] Offer compiler quick fixes as code actions Decode GCC SARIF fixes into bounded diagnostic edits through the same physical-origin policy as locations; unprovable regions are dropped. A bounded projection filters fixes to the requested range, deduplicates and bounds them, and textDocument/codeAction serves them from retained published diagnostics. Registered tests cover the SARIF binding and the projection; a real stdio session returned the compiler's Replace 'valu' with 'value' quickfix. --- CMakeLists.txt | 2 +- build.cpp | 3 +- docs/agent-workflow/LSP-PARITY.md | 9 +-- docs/agent-workflow/STATE.md | 2 +- docs/agent-workflow/VERIFICATION.md | 22 +++++++ include/vls/features/CodeActions.hpp | 51 +++++++++++++++ include/vls/semantic/Diagnostics.hpp | 13 ++++ include/vls/semantic/EditorDiagnostics.hpp | 4 ++ src/Server.cpp | 31 +++++++++ src/features/CodeActions.cpp | 47 ++++++++++++++ src/semantic/Diagnostics.cpp | 73 +++++++++++++++++++++- src/semantic/EditorDiagnostics.cpp | 69 +++++++++++++++++++- tests/CMakeLists.txt | 2 +- tests/features/CodeActionsTests.cpp | 72 +++++++++++++++++++++ tests/semantic/DiagnosticTests.cpp | 28 +++++++++ 15 files changed, 418 insertions(+), 10 deletions(-) create mode 100644 include/vls/features/CodeActions.hpp create mode 100644 src/features/CodeActions.cpp create mode 100644 tests/features/CodeActionsTests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 5b637f8..102d5b2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -30,7 +30,7 @@ add_library(vls_protocol STATIC src/Protocol/Framing.cpp src/Protocol/Json.cpp src/Build/ProviderFile.cpp src/Build/CommandImport.cpp src/Build/VbsProvider.cpp src/Build/CompdbProvider.cpp src/DocumentSync.cpp src/WorkspaceSession.cpp src/Server.cpp src/semantic/Diagnostics.cpp src/semantic/SourceCatalog.cpp src/semantic/StockCompiler.cpp src/semantic/EditorDiagnostics.cpp src/semantic/Occurrences.cpp src/scheduler/Scheduler.cpp - src/modules/ModuleGraph.cpp src/modules/ArtifactCache.cpp src/modules/GccArtifacts.cpp src/modules/ScheduledArtifacts.cpp src/index/SymbolIndex.cpp src/navigation/Navigation.cpp src/reflection/Provenance.cpp src/features/Completion.cpp src/features/IndexNavigation.cpp src/features/SignatureHelp.cpp src/features/DocumentSymbols.cpp src/features/TextStructure.cpp src/debug/live/LiveSession.cpp src/modules/ModuleWorkQueue.cpp src/modules/GccScan.cpp src/modules/ScanCommand.cpp) + src/modules/ModuleGraph.cpp src/modules/ArtifactCache.cpp src/modules/GccArtifacts.cpp src/modules/ScheduledArtifacts.cpp src/index/SymbolIndex.cpp src/navigation/Navigation.cpp src/reflection/Provenance.cpp src/features/Completion.cpp src/features/IndexNavigation.cpp src/features/SignatureHelp.cpp src/features/DocumentSymbols.cpp src/features/TextStructure.cpp src/features/CodeActions.cpp src/debug/live/LiveSession.cpp src/modules/ModuleWorkQueue.cpp src/modules/GccScan.cpp src/modules/ScanCommand.cpp) target_include_directories(vls_protocol PUBLIC "${PROJECT_SOURCE_DIR}/include") target_link_libraries(vls_protocol PUBLIC Void::Data PRIVATE Void::Unicode Void::Text Void::Crypto Void::System) target_compile_options(vls_protocol PUBLIC -freflection PRIVATE -Wall -Wextra -Wpedantic) diff --git a/build.cpp b/build.cpp index 98a7ad3..ec3565d 100644 --- a/build.cpp +++ b/build.cpp @@ -71,6 +71,7 @@ void build(Void::Build::Project &project) { "src/features/SignatureHelp.cpp", "src/features/DocumentSymbols.cpp", "src/features/TextStructure.cpp", + "src/features/CodeActions.cpp", "src/debug/live/LiveSession.cpp", "src/modules/ModuleWorkQueue.cpp", "src/modules/GccScan.cpp", @@ -150,7 +151,7 @@ void build(Void::Build::Project &project) { suite("vls_feature_tests", {"tests/features/CompletionTests.cpp", "tests/features/IndexNavigationTests.cpp", "tests/features/SignatureHelpTests.cpp", "tests/features/DocumentSymbolsTests.cpp", - "tests/features/TextStructureTests.cpp"}); + "tests/features/TextStructureTests.cpp", "tests/features/CodeActionsTests.cpp"}); auto live_worker = project.executable("vls_live_worker_fixture"); live_worker.cxx_standard(CxxStandard::Cxx26) .sources({"tests/debug/LiveWorkerFixture.cpp"}) diff --git a/docs/agent-workflow/LSP-PARITY.md b/docs/agent-workflow/LSP-PARITY.md index 1ed2b0c..ec44f5c 100644 --- a/docs/agent-workflow/LSP-PARITY.md +++ b/docs/agent-workflow/LSP-PARITY.md @@ -18,6 +18,7 @@ missing part. | textDocument/documentSymbol | `vls_index_tests` path query, real stdio session | | textDocument/documentHighlight | `vls_feature_tests`, real stdio session | | textDocument/selectionRange, foldingRange | `vls_feature_tests`, real stdio session | +| textDocument/codeAction (quickfix) | `vls_feature_tests` + `vls_diagnostic_tests`, real stdio session | | workspace/symbol | stock occurrence corpus | | voidLanguageServer/analysisStatus, providerStatus | stdio corpora | | Debug adapter (DAP) separately through `vls-dap` | `vls_live_tests`, `vls_dap_tests` | @@ -28,7 +29,7 @@ missing part. | --- | --- | | Compiler-native completion with visibility proof | index-backed completion is explicitly incomplete | | Overload-set signature help | only the selected occurrence's signature is available | -| textDocument/codeAction, formatting | compiler-backed; needs a plan | +| textDocument/formatting | needs a plan | | textDocument/semanticTokens, inlayHint | larger | textDocument/codeLens, executeCommand | command surface not designed | | callHierarchy / typeHierarchy | needs compiler call/type relationships | @@ -38,6 +39,6 @@ missing part. ## Next slices -1. codeAction quick fixes from published diagnostics. -2. Semantic tokens from stock occurrences. -3. Formatting and inlay hints. +1. Semantic tokens from stock occurrences. +2. Formatting and inlay hints. +3. call/type hierarchy and code lens. diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 1e30823..27648c7 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -102,7 +102,7 @@ ingests occurrence facts after each analysis and the server answers Hash.hpp definition through it. Real persistence migrations and cross-file rename coverage remain open. -Index-backed completion (roadmap 14 first slice) is implemented: `include/vls/features/Completion.hpp`, `src/features/Completion.cpp` and registered `vls_feature_tests` cover prefix extraction, filtering with replacement ranges, label+kind deduplication, deterministic ranking and bounds. `Server.cpp` advertises `completionProvider` and answers `textDocument/completion` from the symbol index through `EditorDiagnostics::completion`; a real stdio session with the stock observer returned `fnv1a64` and `fnv1a64_update` at a real call site. Every result is marked incomplete because the index does not prove visibility. Signature help is now served from the compiler-provided occurrence signature (parameter labels and ranges, active parameter, innermost call selection) and advertised by the server. Document symbols are served from the index by path and document highlights from same-binding occurrence facts; both are advertised and were exercised over stdio with the stock observer. Selection and folding ranges are served from immutable document snapshots with registered bounded cores. Compiler-native completion with visibility proof and deferred detail resolution remain open. +Index-backed completion (roadmap 14 first slice) is implemented: `include/vls/features/Completion.hpp`, `src/features/Completion.cpp` and registered `vls_feature_tests` cover prefix extraction, filtering with replacement ranges, label+kind deduplication, deterministic ranking and bounds. `Server.cpp` advertises `completionProvider` and answers `textDocument/completion` from the symbol index through `EditorDiagnostics::completion`; a real stdio session with the stock observer returned `fnv1a64` and `fnv1a64_update` at a real call site. Every result is marked incomplete because the index does not prove visibility. Signature help is now served from the compiler-provided occurrence signature (parameter labels and ranges, active parameter, innermost call selection) and advertised by the server. Document symbols are served from the index by path and document highlights from same-binding occurrence facts; both are advertised and were exercised over stdio with the stock observer. Selection and folding ranges are served from immutable document snapshots with registered bounded cores. Code actions now offer the compiler's own suggested fixes (quickfix) from retained published diagnostics, with SARIF fix decoding bound to the owner snapshot. Compiler-native completion with visibility proof and deferred detail resolution remain open. The reflection provenance representation (roadmap 12 first slice) is implemented as a bounded library with a registered suite: innermost-first diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index 460fcbf..90efdbd 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -79,6 +79,28 @@ the upgraded snapshot (keeping `snapshot.prev.json`) and rewrites a legacy about 25-30s in a Debug build (it passed VBS at ~27s); the full CMake run then passed 18/18. +## December 5 code actions from compiler fixes + +GCC's SARIF `fixes` are now decoded: `CompilerDiagnostic::fixes` carries a +bounded description plus edits whose deleted regions are converted through the +same physical-origin policy and owner-snapshot coordinates as locations. A fix +for another artifact, an unprovable region or an unbound snapshot is dropped, +never guessed. `include/vls/features/CodeActions.hpp` filters fixes to those +intersecting the requested range, deduplicates and bounds them, and +`EditorDiagnostics::code_actions` serves `textDocument/codeAction` (advertised +with `codeActionKinds: ["quickfix"]`) from the retained published diagnostics. + +A real stdio session with the stock observer on `int main() { return valu; }`: +``` +codeAction: 1 + title: Replace 'valu' with 'value' + kind: quickfix preferred: True + edit: {"changes": {"file:///.../main.cpp": [{"newText": "value", "range": {"end": {"character": 24, "line": 1}, "start": {"character": 20, "line": 1}}}]}} +``` +Registered cases cover the SARIF fix binding and the action projection; +`vls_diagnostic_tests` and `vls_feature_tests` passed, as did all 18 native +suites and all 18 CMake tests. + ## December 5 selection and folding ranges `include/vls/features/TextStructure.hpp` and diff --git a/include/vls/features/CodeActions.hpp b/include/vls/features/CodeActions.hpp new file mode 100644 index 0000000..ae0ba63 --- /dev/null +++ b/include/vls/features/CodeActions.hpp @@ -0,0 +1,51 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace vls::features::code_actions { + +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 Edit { + Range range; + std::string replacement; + auto operator<=>(const Edit &) const = default; +}; +// One compiler-suggested fix: its title, the file it edits and its edits. +struct Fix { + std::string title; + std::string path; + std::vector edits; +}; +struct Action { + std::string title; + std::string path; + std::vector edits; + auto operator<=>(const Action &) const = default; +}; + +struct Limits { + std::size_t actions{64}; + std::size_t edits{8}; + std::size_t titleBytes{256}; + std::size_t editBytes{4096}; +}; + +// Keeps fixes with at least one edit intersecting the requested range, drops +// empty or malformed fixes, deduplicates identical edits and actions, and +// bounds every field. Order is the input order. +[[nodiscard]] std::vector actions(std::span, Range requested, + const Limits & = Limits{}); + +} // namespace vls::features::code_actions diff --git a/include/vls/semantic/Diagnostics.hpp b/include/vls/semantic/Diagnostics.hpp index 174bd3c..8f25051 100644 --- a/include/vls/semantic/Diagnostics.hpp +++ b/include/vls/semantic/Diagnostics.hpp @@ -90,11 +90,24 @@ struct RelatedLocation { DiagnosticLocation location; }; enum class DiagnosticSeverity { error, warning, information, hint }; +// One replacement from a compiler-suggested fix, in the owner snapshot's +// negotiated coordinates. +struct DiagnosticEdit { + Documents::Range range; + std::string replacement; +}; +struct DiagnosticFix { + std::string description; + std::vector edits; +}; struct CompilerDiagnostic { DiagnosticSeverity severity; std::string message, rule; DiagnosticLocation location; std::vector related; + // Bounded compiler-suggested fixes. An edit whose region cannot be proven + // in the owner snapshot is dropped, never guessed. + std::vector fixes; }; struct DiagnosticBatch { std::string invocation_id, input_view_id; diff --git a/include/vls/semantic/EditorDiagnostics.hpp b/include/vls/semantic/EditorDiagnostics.hpp index a383814..8eb5b3a 100644 --- a/include/vls/semantic/EditorDiagnostics.hpp +++ b/include/vls/semantic/EditorDiagnostics.hpp @@ -48,6 +48,10 @@ class EditorDiagnostics { selection_ranges(std::string_view uri, std::span) const; // Foldable brace blocks, comments, regions and include groups. [[nodiscard]] Void::LanguageServer::Protocol::Json folding_ranges(std::string_view uri) const; + // Quick fixes suggested by the compiler for diagnostics overlapping the + // requested range. Only fixes proven in the owner snapshot are offered. + [[nodiscard]] Void::LanguageServer::Protocol::Json code_actions(std::string_view uri, + Documents::Range range) const; struct NavigationReply { Void::LanguageServer::Protocol::Json result; diff --git a/src/Server.cpp b/src/Server.cpp index e05d17c..73f7304 100644 --- a/src/Server.cpp +++ b/src/Server.cpp @@ -266,6 +266,11 @@ DispatchResult Server::handle(std::string_view body) { capabilities.emplace("selectionRangeProvider", Json{true}); capabilities.emplace("foldingRangeProvider", Json{true}); } + if (diagnostics_ && diagnostics_->supports_occurrences()) + capabilities.emplace( + "codeActionProvider", + Json{Json::Object{ + {"codeActionKinds", Json{Json::Array{Json{std::string{"quickfix"}}}}}}}); if (diagnostics_ && diagnostics_->supports_occurrences()) { capabilities.emplace("hoverProvider", Json{true}); capabilities.emplace("definitionProvider", Json{true}); @@ -373,6 +378,32 @@ DispatchResult Server::handle(std::string_view body) { } return reply(id, "result", diagnostics_->selection_ranges(*uri, selected)); } + if (*method == "textDocument/codeAction") { + if (!diagnostics_ || !diagnostics_->supports_occurrences()) + return error(id, -32601, "Method not found"); + const auto *uri = as_string(member(member(params, "textDocument"), "uri")); + const auto *range = member(params, "range"); + const auto *start = member(range, "start"); + const auto *end = member(range, "end"); + const auto coordinate = [](const Json *value, + std::string_view key) -> std::optional { + const auto *field = member(value, key); + const auto *number = field ? std::get_if(&field->value) : nullptr; + if (!number || *number < 0 || + *number > Void::LanguageServer::Documents::kMaxPositionValue) + return std::nullopt; + return static_cast(*number); + }; + const auto start_line = coordinate(start, "line"), + start_character = coordinate(start, "character"); + const auto end_line = coordinate(end, "line"), end_character = coordinate(end, "character"); + if (!uri || !Void::LanguageServer::Documents::client_uri_key(*uri) || !start_line || + !start_character || !end_line || !end_character) + return error(id, -32602, "Expected textDocument.uri and a bounded range"); + return reply(id, "result", + diagnostics_->code_actions( + *uri, {{*start_line, *start_character}, {*end_line, *end_character}})); + } if (*method == "textDocument/documentSymbol") { if (!diagnostics_) return error(id, -32601, "Method not found"); diff --git a/src/features/CodeActions.cpp b/src/features/CodeActions.cpp new file mode 100644 index 0000000..0a6f610 --- /dev/null +++ b/src/features/CodeActions.cpp @@ -0,0 +1,47 @@ +#include + +#include +#include +#include +#include + +namespace vls::features::code_actions { +namespace { +bool intersects(const Range &left, const Range &right) { + return left.start <= right.end && right.start <= left.end; +} + +std::string bounded(std::string value, std::size_t limit) { + if (value.size() > limit) + value.resize(limit); + return value; +} +} // namespace + +std::vector actions(std::span fixes, Range requested, const Limits &limits) { + std::vector result; + std::set>> seen; + for (const auto &fix : fixes) { + if (fix.path.empty() || result.size() >= limits.actions) + continue; + Action action{.title = bounded(fix.title, limits.titleBytes), .path = fix.path, .edits = {}}; + std::set unique; + for (const auto &edit : fix.edits) { + if (action.edits.size() >= limits.edits) + break; + if (edit.range.end < edit.range.start || !intersects(edit.range, requested)) + continue; + if (!unique.insert(edit).second) + continue; + action.edits.push_back({edit.range, bounded(edit.replacement, limits.editBytes)}); + } + if (action.edits.empty()) + continue; + if (!seen.emplace(action.title, action.path, action.edits).second) + continue; + result.push_back(std::move(action)); + } + return result; +} + +} // namespace vls::features::code_actions diff --git a/src/semantic/Diagnostics.cpp b/src/semantic/Diagnostics.cpp index 61999b4..54131d1 100644 --- a/src/semantic/Diagnostics.cpp +++ b/src/semantic/Diagnostics.cpp @@ -17,6 +17,7 @@ template using Result = std::expected; constexpr std::size_t max_report_bytes = 4 * 1024 * 1024; constexpr std::size_t max_artifacts = 2048, max_results = 4096, max_locations = 16384; constexpr std::size_t max_name = 16384, max_message = 65536; +constexpr std::size_t max_fixes = 8, max_edits = 4, max_fix_text = 4096; constexpr std::string_view bom = "\xef\xbb\xbf"; // Cap container allocation in Void's JSON value tree before parsing. Brackets @@ -317,6 +318,74 @@ Result append_locations(Reader &reader, const Json *value, std::size_t ind } return {}; } +Result append_fixes(Reader &reader, const Json *value, std::size_t index, + CompilerDiagnostic &diagnostic) { + if (!value) + return {}; + const auto *fixes = P::as_array(value); + if (!fixes || fixes->size() > max_fixes) + return std::unexpected(Error::malformed_report); + if (fixes->empty()) + return {}; + if (!diagnostic.location.snapshot || !diagnostic.location.range) + return {}; + const auto &snapshot = *diagnostic.location.snapshot; + for (const auto &item : *fixes) { + const auto *fix = P::as_object(&item); + if (!fix) + return std::unexpected(Error::malformed_report); + const auto *description = string(object(fix, "description"), "text"); + if (description && description->size() > max_message) + return std::unexpected(Error::resource_limit); + const auto *changes = P::as_array(member(fix, "artifactChanges")); + if (!changes || changes->size() != 1) + return std::unexpected(Error::malformed_report); + const auto *change = P::as_object(&changes->front()); + if (!change) + return std::unexpected(Error::malformed_report); + const auto file = reader.binding(object(change, "artifactLocation")); + const auto *replacements = P::as_array(member(change, "replacements")); + if (!file || !file->file || file->file->snapshot != diagnostic.location.snapshot || + !file->contents_match || !replacements || replacements->size() > max_edits) + continue; + DiagnosticFix parsed; + parsed.description = description ? *description : std::string{}; + for (const auto &replacement_item : *replacements) { + const auto *replacement = P::as_object(&replacement_item); + const auto *region = object(replacement, "deletedRegion"); + const auto first = natural(member(region, "startLine")); + const auto left = natural(member(region, "startColumn")); + const auto last = + member(region, "endLine") ? natural(member(region, "endLine")) : first; + const auto right = natural(member(region, "endColumn")); + const auto *content = string(object(replacement, "insertedContent"), "text"); + if (!first || !left || !last || !right || !*first || !*left || !*last || !*right || + *last < *first || (*last == *first && *right < *left)) + continue; + if (content && content->size() > max_fix_text) + return std::unexpected(Error::resource_limit); + const LocationRequest request{ + *file->file, {*first, *left, *last, *right}, index, 0, false}; + const auto policy = + reader.job.physical_origin ? reader.job.physical_origin(request) : std::nullopt; + if (!policy) + continue; + auto start = reader.position(snapshot, *first, *left, *policy); + if (!start) + return std::unexpected(start.error()); + auto end = reader.position(snapshot, *last, *right, *policy); + if (!end) + return std::unexpected(end.error()); + if (!*start || !*end || **end < **start) + continue; + parsed.edits.push_back( + {Documents::Range{**start, **end}, content ? *content : std::string{}}); + } + if (!parsed.edits.empty()) + diagnostic.fixes.push_back(std::move(parsed)); + } + return {}; +} } // namespace std::expected @@ -377,7 +446,7 @@ decode_gcc_diagnostics(const DiagnosticJob &job, const DiagnosticOutput &output) return std::unexpected(Error::malformed_report); if (message->size() > max_message || rule->size() > max_name) return std::unexpected(Error::resource_limit); - CompilerDiagnostic diagnostic{*level, *message, *rule, {}, {}}; + CompilerDiagnostic diagnostic{*level, *message, *rule, {}, {}, {}}; if (auto primary = append_locations(reader, member(record, "locations"), i, false, diagnostic); !primary) @@ -386,6 +455,8 @@ decode_gcc_diagnostics(const DiagnosticJob &job, const DiagnosticOutput &output) append_locations(reader, member(record, "relatedLocations"), i, true, diagnostic); !related) return std::unexpected(related.error()); + if (auto fixes = append_fixes(reader, member(record, "fixes"), i, diagnostic); !fixes) + return std::unexpected(fixes.error()); source_error |= *level == DiagnosticSeverity::error; if (!diagnostic.location.range || *rule == "fatal error" || *rule == "internal compiler error") diff --git a/src/semantic/EditorDiagnostics.cpp b/src/semantic/EditorDiagnostics.cpp index dc4e77d..379e835 100644 --- a/src/semantic/EditorDiagnostics.cpp +++ b/src/semantic/EditorDiagnostics.cpp @@ -1,5 +1,6 @@ #include +#include #include #include #include @@ -99,8 +100,17 @@ int symbol_kind(index::SymbolKind kind) { return 1; // LSP File fallback for an unclassified symbol } +struct PublishedDiagnostic { + std::string path; + Documents::Range range; + DiagnosticSeverity severity; + std::string message, rule; + std::vector fixes; +}; + struct EditorReport { Json::Array diagnostics, other_messages; + std::vector published; std::size_t unlocated{}; }; @@ -114,6 +124,8 @@ EditorReport for_owner(const DiagnosticBatch &batch) { report.other_messages.emplace_back(d.message.substr(0, 1024)); continue; } + report.published.push_back({d.location.snapshot->identity.canonical_path.native(), + *d.location.range, d.severity, d.message, d.rule, d.fixes}); auto &r = *d.location.range; Json::Object item{ {"range", Json{Json::Object{{"start", position(r.start)}, {"end", position(r.end)}}}}, @@ -150,6 +162,7 @@ struct Entry { std::optional version, published_version; bool sent{}, had_findings{}; std::shared_ptr receipt; + std::vector published; std::shared_ptr> occurrences; std::string occurrence_state{"disabled"}, occurrence_reason; std::string module_state{"disabled"}, module_detail; @@ -331,8 +344,11 @@ struct EditorDiagnostics::State { entry.sent = true; entry.had_findings = has_findings; entry.published_version = owner->version; - } else + entry.published = std::move(report.published); + } else { retract(entry); + entry.published.clear(); + } entry.provider = selection->generation->identity().provider; entry.alternative = selection->selected->key.alternative; entry.hint_selection = selection; @@ -1092,6 +1108,57 @@ Json EditorDiagnostics::folding_ranges(std::string_view uri) const { return Json{std::move(result)}; } +Json EditorDiagnostics::code_actions(std::string_view uri, Documents::Range range) const { + auto &s = *state_; + const auto identity = Documents::normalize_uri(uri); + if (!identity || !identity->is_file_uri) + return Json{nullptr}; + std::vector published; + { + std::lock_guard lock{s.mutex}; + const auto i = s.entries.find(identity->canonical_uri); + if (i == s.entries.end()) + return Json{Json::Array{}}; + published = i->second.published; + } + std::vector fixes; + for (const auto &diagnostic : published) { + if (diagnostic.path != identity->canonical_path.native()) + continue; + for (const auto &fix : diagnostic.fixes) { + features::code_actions::Fix entry; + entry.title = + fix.description.empty() ? diagnostic.message.substr(0, 256) : fix.description; + entry.path = diagnostic.path; + for (const auto &edit : fix.edits) + entry.edits.push_back({{{edit.range.start.line, edit.range.start.character}, + {edit.range.end.line, edit.range.end.character}}, + edit.replacement}); + fixes.push_back(std::move(entry)); + } + } + const auto selected = features::code_actions::actions( + fixes, {{range.start.line, range.start.character}, {range.end.line, range.end.character}}); + Json::Array actions; + for (const auto &action : selected) { + Json::Array edits; + for (const auto &edit : action.edits) + edits.push_back(Json{Json::Object{ + {"range", + range_json(Documents::Range{{edit.range.start.line, edit.range.start.character}, + {edit.range.end.line, edit.range.end.character}})}, + {"newText", Json{edit.replacement}}}}); + Json::Object changes; + changes.emplace(Documents::path_to_file_uri(action.path), Json{std::move(edits)}); + actions.push_back(Json{ + Json::Object{{"title", Json{action.title}}, + {"kind", Json{std::string{"quickfix"}}}, + {"isPreferred", Json{true}}, + {"edit", Json{Json::Object{{"changes", Json{std::move(changes)}}}}}}}); + } + return Json{std::move(actions)}; +} + void EditorDiagnostics::set_transactional_rename(bool supported) { std::lock_guard lock{state_->mutex}; state_->transactional_rename = supported; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index f4772dc..d4ec557 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -22,7 +22,7 @@ vls_test_suite(vls_scheduler_tests scheduler/SchedulerTests.cpp) vls_test_suite(vls_index_tests index/SymbolIndexTests.cpp) vls_test_suite(vls_navigation_tests navigation/NavigationTests.cpp) vls_test_suite(vls_reflection_tests reflection/ProvenanceTests.cpp) -vls_test_suite(vls_feature_tests features/CompletionTests.cpp features/IndexNavigationTests.cpp features/SignatureHelpTests.cpp features/DocumentSymbolsTests.cpp features/TextStructureTests.cpp) +vls_test_suite(vls_feature_tests features/CompletionTests.cpp features/IndexNavigationTests.cpp features/SignatureHelpTests.cpp features/DocumentSymbolsTests.cpp features/TextStructureTests.cpp features/CodeActionsTests.cpp) vls_test_suite(vls_live_tests debug/LiveSessionTests.cpp debug/LiveDapTests.cpp) target_link_libraries(vls_live_tests PRIVATE Void::System) add_dependencies(vls_live_tests vls_live_worker_fixture vls-dap) diff --git a/tests/features/CodeActionsTests.cpp b/tests/features/CodeActionsTests.cpp new file mode 100644 index 0000000..d0cfbf1 --- /dev/null +++ b/tests/features/CodeActionsTests.cpp @@ -0,0 +1,72 @@ +#include + +#include +#include + +#include +#include + +namespace { +using namespace vls::features::code_actions; +using Void::Testing::expect; +using Void::Testing::require; + +Range range(std::uint32_t line, std::uint32_t character, std::uint32_t end_character) { + return {{line, character}, {line, end_character}}; +} + +Fix fix(std::string title, std::vector edits, std::string path = "/project/a.cpp") { + return {std::move(title), std::move(path), std::move(edits)}; +} +} // namespace + +VOID_TEST(CodeActions, keeps_only_fixes_intersecting_the_requested_range) { + const std::vector fixes{fix("Replace value", {{range(3, 12, 16), "value"}}), + fix("Replace other", {{range(9, 0, 4), "other"}}), + fix("Adjoining", {{range(4, 0, 2), "next"}})}; + const auto result = actions(fixes, range(3, 14, 14)); + require(result.size() == 1); + expect(result.front().title == "Replace value"); + expect(result.front().edits.front().replacement == "value"); +} + +VOID_TEST(CodeActions, empty_and_malformed_fixes_are_dropped) { + const std::vector fixes{fix("No edits", {}), fix("No path", {{range(1, 0, 2), "x"}}, ""), + fix("Reversed", {{{{2, 4}, {2, 1}}, "x"}}), + fix("Valid", {{range(1, 0, 2), "x"}})}; + const auto result = actions(fixes, range(1, 0, 1)); + require(result.size() == 1); + expect(result.front().title == "Valid"); +} + +VOID_TEST(CodeActions, deduplicates_edits_and_actions) { + const std::vector fixes{fix("Replace", {{range(1, 0, 2), "x"}, {range(1, 0, 2), "x"}}), + fix("Replace", {{range(1, 0, 2), "x"}})}; + const auto result = actions(fixes, range(1, 0, 1)); + require(result.size() == 1); + expect(result.front().edits.size() == 1); +} + +VOID_TEST(CodeActions, bounds_actions_edits_and_text) { + std::vector fixes; + for (int index = 0; index != 5; ++index) + fixes.push_back( + fix("Action " + std::to_string(index), + {{range(1, 0, 2), "one"}, {range(1, 3, 4), "two"}, {range(1, 5, 6), "three"}})); + const auto result = actions(fixes, range(1, 0, 6), Limits{.actions = 2, .edits = 2}); + expect(result.size() == 2); + expect(result.front().edits.size() == 2); + const auto bounded = actions(fixes, range(1, 0, 6), Limits{.titleBytes = 3, .editBytes = 2}); + require(!bounded.empty()); + expect(bounded.front().title == "Act"); + expect(bounded.front().edits.front().replacement == "on"); +} + +VOID_TEST(CodeActions, preserves_input_order) { + const std::vector fixes{fix("Second alphabetically", {{range(1, 0, 2), "b"}}), + fix("First alphabetically", {{range(1, 0, 2), "a"}})}; + const auto result = actions(fixes, range(1, 0, 1)); + require(result.size() == 2); + expect(result[0].title == "Second alphabetically"); + expect(result[1].title == "First alphabetically"); +} diff --git a/tests/semantic/DiagnosticTests.cpp b/tests/semantic/DiagnosticTests.cpp index 867aa69..793097f 100644 --- a/tests/semantic/DiagnosticTests.cpp +++ b/tests/semantic/DiagnosticTests.cpp @@ -333,3 +333,31 @@ VOID_TEST(DiagnosticTests, report_structure_and_output_sizes_are_bounded) { 0) .has_value()); } + +VOID_TEST(DiagnosticTests, compiler_fixes_bind_to_the_owner_snapshot) { + Capture f{"int value = 1;\nint main() { return valu; }\n"}; + const auto region = R"({"startLine":2,"startColumn":21,"endColumn":25})"sv; + const auto fix = + R"("fixes":[{"description":{"text":"Replace 'valu' with 'value'"},"artifactChanges":[{"artifactLocation":)" + + std::string{primary} + + R"(,"replacements":[{"deletedRegion":{"startLine":2,"startColumn":21,"endColumn":25},"insertedContent":{"text":"value"}}]}]}])"; + const auto findings = + R"({"level":"error","ruleId":"error","message":{"text":"did you mean value?"},"locations":[)" + + location(primary, region) + "]," + fix + "}"; + const auto batch = f.batch(report(false, findings)); + require(batch.diagnostics.size() == 1); + const auto &diagnostic = batch.diagnostics.front(); + require(diagnostic.fixes.size() == 1); + expect(diagnostic.fixes[0].description == "Replace 'valu' with 'value'"); + require(diagnostic.fixes[0].edits.size() == 1); + expect(diagnostic.fixes[0].edits[0].range == D::Range{{1, 20}, {1, 24}}); + expect(diagnostic.fixes[0].edits[0].replacement == "value"); + + // A fix for another artifact, or one whose region cannot be proven, is dropped. + const auto foreign = + R"("fixes":[{"description":{"text":"x"},"artifactChanges":[{"artifactLocation":{"uri":"a.hpp","uriBaseId":"PWD"},"replacements":[{"deletedRegion":{"startLine":2,"startColumn":21,"endColumn":25},"insertedContent":{"text":"value"}}]}]}])"; + const auto dropped = f.batch( + report(false, R"({"level":"error","ruleId":"error","message":{"text":"m"},"locations":[)" + + location(primary, region) + "]," + foreign + "}")); + expect(dropped.diagnostics.front().fixes.empty()); +}