nixd
Loading...
Searching...
No Matches
CodeAction.cpp
Go to the documentation of this file.
1/// \file
2/// \brief Implementation of [Code Action].
3/// [Code Action]:
4/// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_codeAction
5
6#include "CheckReturn.h"
7#include "Convert.h"
8
10
11#include <boost/asio/post.hpp>
12
13namespace nixd {
14
15using namespace llvm::json;
16using namespace lspserver;
17
18void Controller::onCodeAction(const lspserver::CodeActionParams &Params,
19 Callback<std::vector<CodeAction>> Reply) {
20 using CheckTy = std::vector<CodeAction>;
21 std::string File(Params.textDocument.uri.file());
22 Range Range = Params.range;
23 auto Action = [Reply = std::move(Reply), File, Range, this]() mutable {
24 return Reply([&]() -> llvm::Expected<CheckTy> {
25 const auto TU = CheckDefault(getTU(File));
26
27 const auto &Diagnostics = TU->diagnostics();
28 auto Actions = std::vector<CodeAction>();
29 Actions.reserve(Diagnostics.size());
30 for (const nixf::Diagnostic &D : Diagnostics) {
31 auto DRange = toLSPRange(TU->src(), D.range());
32 if (!Range.overlap(DRange))
33 continue;
34
35 // Add fixes.
36 for (const nixf::Fix &F : D.fixes()) {
37 std::vector<TextEdit> Edits;
38 Edits.reserve(F.edits().size());
39 for (const nixf::TextEdit &TE : F.edits()) {
40 Edits.emplace_back(TextEdit{
41 .range = toLSPRange(TU->src(), TE.oldRange()),
42 .newText = std::string(TE.newText()),
43 });
44 }
45 using Changes = std::map<std::string, std::vector<TextEdit>>;
46 std::string FileURI = URIForFile::canonicalize(File, File).uri();
47 WorkspaceEdit WE{.changes = Changes{
48 {std::move(FileURI), std::move(Edits)},
49 }};
50 Actions.emplace_back(CodeAction{
51 .title = F.message(),
52 .kind = std::string(CodeAction::QUICKFIX_KIND),
53 .edit = std::move(WE),
54 });
55 }
56 }
57 return Actions;
58 }());
59 };
60 boost::asio::post(Pool, std::move(Action));
61}
62
63} // namespace nixd
#define CheckDefault(x)
Variant of CheckReturn, but returns default constructed CheckTy
Definition CheckReturn.h:16
Convert between LSP and nixf types.
Whether current platform treats paths case insensitively.
Definition Connection.h:11
llvm::unique_function< void(llvm::Expected< T >)> Callback
Definition Function.h:14
lspserver::Range toLSPRange(llvm::StringRef Code, const nixf::LexerCursorRange &R)
Definition Convert.cpp:40
Range range
The range for which the command was invoked.
TextDocumentIdentifier textDocument
The document in which the command was invoked.
static const llvm::StringLiteral QUICKFIX_KIND
bool overlap(const Range &RHS) const
static URIForFile canonicalize(llvm::StringRef AbsPath, llvm::StringRef TUPath)
llvm::StringRef file() const
Retrieves absolute path to the file.