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.
This commit is contained in:
1 parent
624c24d028
commit
946b1a005e
15 files changed
+418
-10
No files matched your search
+1
-1
@@ -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)
|
||||
|
||||
@@ -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"})
|
||||
|
||||
@@ -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.
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
#pragma once
|
||||
|
||||
#include <compare>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<Edit> edits;
|
||||
};
|
||||
struct Action {
|
||||
std::string title;
|
||||
std::string path;
|
||||
std::vector<Edit> 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<Action> actions(std::span<const Fix>, Range requested,
|
||||
const Limits & = Limits{});
|
||||
|
||||
} // namespace vls::features::code_actions
|
||||
@@ -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<DiagnosticEdit> edits;
|
||||
};
|
||||
struct CompilerDiagnostic {
|
||||
DiagnosticSeverity severity;
|
||||
std::string message, rule;
|
||||
DiagnosticLocation location;
|
||||
std::vector<RelatedLocation> related;
|
||||
// Bounded compiler-suggested fixes. An edit whose region cannot be proven
|
||||
// in the owner snapshot is dropped, never guessed.
|
||||
std::vector<DiagnosticFix> fixes;
|
||||
};
|
||||
struct DiagnosticBatch {
|
||||
std::string invocation_id, input_view_id;
|
||||
|
||||
@@ -48,6 +48,10 @@ class EditorDiagnostics {
|
||||
selection_ranges(std::string_view uri, std::span<const Documents::Position>) 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;
|
||||
|
||||
@@ -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<std::uint32_t> {
|
||||
const auto *field = member(value, key);
|
||||
const auto *number = field ? std::get_if<std::int64_t>(&field->value) : nullptr;
|
||||
if (!number || *number < 0 ||
|
||||
*number > Void::LanguageServer::Documents::kMaxPositionValue)
|
||||
return std::nullopt;
|
||||
return static_cast<std::uint32_t>(*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");
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
#include <vls/features/CodeActions.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <set>
|
||||
#include <tuple>
|
||||
#include <utility>
|
||||
|
||||
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<Action> actions(std::span<const Fix> fixes, Range requested, const Limits &limits) {
|
||||
std::vector<Action> result;
|
||||
std::set<std::tuple<std::string, std::string, std::vector<Edit>>> 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<Edit> 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
|
||||
@@ -17,6 +17,7 @@ template <class T> using Result = std::expected<T, Error>;
|
||||
constexpr std::size_t max_report_bytes = 4 * 1024 * 1024;
|
||||
constexpr std::size_t max_artifacts = 2048, max_results = 4096, max_locations = 16384;
|
||||
constexpr std::size_t max_name = 16384, max_message = 65536;
|
||||
constexpr std::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<void> append_locations(Reader &reader, const Json *value, std::size_t ind
|
||||
}
|
||||
return {};
|
||||
}
|
||||
Result<void> 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<DiagnosticBatch, DiagnosticError>
|
||||
@@ -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")
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include <vls/semantic/EditorDiagnostics.hpp>
|
||||
|
||||
#include <vls/features/CodeActions.hpp>
|
||||
#include <vls/features/Completion.hpp>
|
||||
#include <vls/features/DocumentSymbols.hpp>
|
||||
#include <vls/features/IndexNavigation.hpp>
|
||||
@@ -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<DiagnosticFix> fixes;
|
||||
};
|
||||
|
||||
struct EditorReport {
|
||||
Json::Array diagnostics, other_messages;
|
||||
std::vector<PublishedDiagnostic> 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<std::int32_t> version, published_version;
|
||||
bool sent{}, had_findings{};
|
||||
std::shared_ptr<const Receipt> receipt;
|
||||
std::vector<PublishedDiagnostic> published;
|
||||
std::shared_ptr<const std::vector<Occurrence>> 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<PublishedDiagnostic> 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<features::code_actions::Fix> 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;
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
#include <vls/features/CodeActions.hpp>
|
||||
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<Edit> 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<Fix> 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<Fix> 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<Fix> 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<Fix> 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<Fix> 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");
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
Reference in new issue
Block a user