nixd
Loading...
Searching...
No Matches
Completion.cpp
Go to the documentation of this file.
1/// \file
2/// \brief Implementation of [Code Completion].
3/// [Code Completion]:
4/// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_completion
5
6#include "AST.h"
7#include "CheckReturn.h"
8#include "Convert.h"
9
10#include "lspserver/Protocol.h"
11
14
16
17#include <boost/asio/post.hpp>
18
19#include <exception>
20#include <semaphore>
21#include <set>
22#include <utility>
23
24using namespace nixd;
25using namespace lspserver;
26using namespace nixf;
27
28namespace {
29
30/// Set max completion size to this value, we don't want to send large lists
31/// because of slow IO.
32/// Items exceed this size should be marked "incomplete" and recomputed.
33constexpr int MaxCompletionSize = 30;
34
37
38struct ExceedSizeError : std::exception {
39 [[nodiscard]] const char *what() const noexcept override {
40 return "Size exceeded";
41 }
42};
43
44void addItem(std::vector<CompletionItem> &Items, CompletionItem Item) {
45 if (Items.size() >= MaxCompletionSize) {
46 throw ExceedSizeError();
47 }
48 Items.emplace_back(std::move(Item));
49}
50
51bool hasConcreteChild(const Node &N) {
52 for (const Node *Child : N.children()) {
53 if (Child)
54 return true;
55 }
56 return false;
57}
58
59bool canCompleteAt(const Node &N) {
60 if (!hasConcreteChild(N))
61 return true;
62 return N.kind() == Node::NK_Binds || N.kind() == Node::NK_ExprAttrs;
63}
64
65class VLACompletionProvider {
66 const VariableLookupAnalysis &VLA;
67
68 static CompletionItemKind getCompletionItemKind(const Definition &Def) {
69 if (Def.isBuiltin()) {
70 return CompletionItemKind::Keyword;
71 }
72 return CompletionItemKind::Variable;
73 }
74
75 /// Collect definition on some env, and also it's ancestors.
76 void collectDef(std::vector<CompletionItem> &Items, const EnvNode *Env,
77 const std::string &Prefix) {
78 if (!Env)
79 return;
80 collectDef(Items, Env->parent(), Prefix);
81 for (const auto &[Name, Def] : Env->defs()) {
82 if (Name.starts_with(
83 "__")) // These names are nix internal implementation, skip.
84 continue;
85 assert(Def);
86 if (Name.starts_with(Prefix)) {
87 addItem(Items, CompletionItem{
88 .label = Name,
89 .kind = getCompletionItemKind(*Def),
90 });
91 }
92 }
93 }
94
95public:
96 VLACompletionProvider(const VariableLookupAnalysis &VLA) : VLA(VLA) {}
97
98 /// Perform code completion right after this node.
99 void complete(const nixf::ExprVar &Desc, std::vector<CompletionItem> &Items,
100 const ParentMapAnalysis &PM) {
101 std::string Prefix = Desc.id().name();
102 collectDef(Items, upEnv(Desc, VLA, PM), Prefix);
103 }
104};
105
106/// \brief Provide completions by IPC. Asking nixpkgs provider.
107/// We simply select nixpkgs in separate process, thus this value does not need
108/// to be cached. (It is already cached in separate process.)
109///
110/// Currently, this procedure is explicitly blocked (synchronized). Because
111/// query nixpkgs value is relatively fast. In the future there might be nixd
112/// index, for performance.
113class NixpkgsCompletionProvider {
114
115 AttrSetClient &NixpkgsClient;
116
117public:
118 NixpkgsCompletionProvider(AttrSetClient &NixpkgsClient)
119 : NixpkgsClient(NixpkgsClient) {}
120
121 void resolvePackage(std::vector<std::string> Scope, std::string Name,
122 CompletionItem &Item) {
123 std::binary_semaphore Ready(0);
124 AttrPathInfoResponse Desc;
125 auto OnReply = [&Ready, &Desc](llvm::Expected<AttrPathInfoResponse> Resp) {
126 if (Resp)
127 Desc = *Resp;
128 Ready.release();
129 };
130 Scope.emplace_back(std::move(Name));
131 NixpkgsClient.attrpathInfo(Scope, std::move(OnReply));
132 Ready.acquire();
133 // Format "detail" and document.
134 const PackageDescription &PD = Desc.PackageDesc;
135 Item.documentation = MarkupContent{
136 .kind = MarkupKind::Markdown,
137 .value = PD.Description.value_or("") + "\n\n" +
138 PD.LongDescription.value_or(""),
139 };
140 Item.detail = PD.Version.value_or("?");
141 }
142
143 /// \brief Ask nixpkgs provider, give us a list of names. (thunks)
144 void completePackages(const AttrPathCompleteParams &Params,
145 std::vector<CompletionItem> &Items) {
146 std::binary_semaphore Ready(0);
147 std::vector<std::string> Names;
148 auto OnReply = [&Ready,
149 &Names](llvm::Expected<AttrPathCompleteResponse> Resp) {
150 if (!Resp) {
151 lspserver::elog("nixpkgs evaluator reported: {0}", Resp.takeError());
152 Ready.release();
153 return;
154 }
155 Names = *Resp; // Copy response to waiting thread.
156 Ready.release();
157 };
158 // Send request.
159 NixpkgsClient.attrpathComplete(Params, std::move(OnReply));
160 Ready.acquire();
161 // Now we have "Names", use these to fill "Items".
162 for (const auto &Name : Names) {
163 if (Name.starts_with(Params.Prefix)) {
164 addItem(Items, CompletionItem{
165 .label = Name,
166 .kind = CompletionItemKind::Field,
167 .data = llvm::formatv("{0}", toJSON(Params)),
168 });
169 }
170 }
171 }
172};
173
174/// \brief Provide completion list by nixpkgs module system (options).
175class OptionCompletionProvider {
176 AttrSetClient &OptionClient;
177
178 // Where is the module set. (e.g. nixos)
179 std::string ModuleOrigin;
180
181 // Wheter the client support code snippets.
182 bool ClientSupportSnippet;
183
184 static std::string escapeCharacters(const std::set<char> &Charset,
185 const std::string &Origin) {
186 // Escape characters listed in charset.
187 std::string Ret;
188 Ret.reserve(Origin.size());
189 for (const auto Ch : Origin) {
190 if (Charset.contains(Ch)) {
191 Ret += "\\";
192 Ret += Ch;
193 } else {
194 Ret += Ch;
195 }
196 }
197 return Ret;
198 }
199
200 void fillInsertText(CompletionItem &Item, const std::string &Name,
201 const std::string &Value) const {
202 if (!ClientSupportSnippet) {
203 Item.insertTextFormat = InsertTextFormat::PlainText;
204 Item.insertText = Name + " = " + Value + ";";
205 return;
206 }
207 Item.insertTextFormat = InsertTextFormat::Snippet;
208 Item.insertText = Name + " = " +
209 "${1:" + escapeCharacters({'\\', '$', '}'}, Value) + "}" +
210 ";";
211 }
212
213public:
214 OptionCompletionProvider(AttrSetClient &OptionClient,
215 std::string ModuleOrigin, bool ClientSupportSnippet)
216 : OptionClient(OptionClient), ModuleOrigin(std::move(ModuleOrigin)),
217 ClientSupportSnippet(ClientSupportSnippet) {}
218
219 void completeOptions(std::vector<std::string> Scope, std::string Prefix,
220 std::vector<CompletionItem> &Items) {
221 std::binary_semaphore Ready(0);
223 auto OnReply = [&Ready,
224 &Names](llvm::Expected<OptionCompleteResponse> Resp) {
225 if (!Resp) {
226 lspserver::elog("option worker reported: {0}", Resp.takeError());
227 Ready.release();
228 return;
229 }
230 Names = *Resp; // Copy response to waiting thread.
231 Ready.release();
232 };
233 // Send request.
234 AttrPathCompleteParams Params{std::move(Scope), std::move(Prefix)};
235 OptionClient.optionComplete(Params, std::move(OnReply));
236 Ready.acquire();
237 // Now we have "Names", use these to fill "Items".
238 for (const nixd::OptionField &Field : Names) {
239 if (!Field.Description) {
240 CompletionItem Item;
241 Item.label = Field.Name;
242 Item.detail = ModuleOrigin;
243 Item.kind = OptionAttrKind;
244 addItem(Items, std::move(Item));
245 continue;
246 }
247
248 const OptionDescription &Desc = *Field.Description;
249
250 // Build the shared bits (detail, documentation) once, then emit one
251 // completion item per value source (`example`, `default`). This lets
252 // the user pick between the sample code the option author suggested
253 // and its default value - useful when an option only has one of the
254 // two, or when the user wants the default as a starting point.
255 std::string TypeDetail = ModuleOrigin + " | ";
256 if (Desc.Type) {
257 std::string TypeName = Desc.Type->Name.value_or("");
258 std::string TypeDesc = Desc.Type->Description.value_or("");
259 TypeDetail += llvm::formatv("{0} ({1})", TypeName, TypeDesc);
260 } else {
261 TypeDetail += "? (missing type)";
262 }
263 MarkupContent Doc{
264 .kind = MarkupKind::Markdown,
265 .value = Desc.Description.value_or(""),
266 };
267
268 // Check whether both variants will be emitted so we can decide
269 // whether to disambiguate the labels with "(example)" / "(default)".
270 bool HasExample = Desc.Example.has_value();
271 // Only emit a separate `default` item when it would differ from the
272 // example; otherwise the user would see two identical snippets.
273 bool HasDefault =
274 Desc.Default.has_value() && Desc.Default != Desc.Example;
275 bool HasBoth = HasExample && HasDefault;
276
277 auto emit = [&](const std::string &Value, llvm::StringRef Source,
278 llvm::StringRef SortPrefix) {
279 CompletionItem Item;
280 // When both variants exist, append the source so users can tell
281 // them apart. `filterText` is always the plain option name so
282 // typing the name matches both items.
283 if (HasBoth)
284 Item.label = llvm::formatv("{0} ({1})", Field.Name, Source);
285 else
286 Item.label = Field.Name;
287 Item.filterText = Field.Name;
288 Item.sortText = (SortPrefix + Field.Name).str();
289 Item.kind = OptionKind;
290 Item.detail = TypeDetail;
291 Item.documentation = Doc;
292 fillInsertText(Item, Field.Name, Value);
293 addItem(Items, std::move(Item));
294 };
295
296 bool Emitted = false;
297 if (HasExample) {
298 emit(*Desc.Example, "example", "0");
299 Emitted = true;
300 }
301 if (HasDefault) {
302 emit(*Desc.Default, "default", "1");
303 Emitted = true;
304 }
305 if (!Emitted) {
306 // No example or default to insert — still offer the option name
307 // as a bare completion so users can discover it.
308 CompletionItem Item;
309 Item.label = Field.Name;
310 Item.kind = OptionKind;
311 Item.detail = TypeDetail;
312 Item.documentation = Doc;
313 fillInsertText(Item, Field.Name, "");
314 addItem(Items, std::move(Item));
315 }
316 }
317 }
318};
319
320void completeAttrName(const std::vector<std::string> &Scope,
321 const std::string &Prefix,
322 Controller::OptionMapTy &Options, bool CompletionSnippets,
323 std::vector<CompletionItem> &List) {
324 for (const auto &[Name, Provider] : Options) {
325 AttrSetClient *Client = Options.at(Name)->client();
326 if (!Client) [[unlikely]] {
327 elog("skipped client {0} as it is dead", Name);
328 continue;
329 }
330 OptionCompletionProvider OCP(*Client, Name, CompletionSnippets);
331 OCP.completeOptions(Scope, Prefix, List);
332 }
333}
334
335void completeAttrPath(const Node &N, const ParentMapAnalysis &PM,
336 std::mutex &OptionsLock, Controller::OptionMapTy &Options,
337 bool Snippets,
338 std::vector<lspserver::CompletionItem> &Items) {
339 std::vector<std::string> Scope;
340 using PathResult = FindAttrPathResult;
341 auto R = findAttrPathForOptions(N, PM, Scope);
342 if (R == PathResult::OK) {
343 // Construct request.
344 std::string Prefix = Scope.back();
345 Scope.pop_back();
346 {
347 std::lock_guard _(OptionsLock);
348 completeAttrName(Scope, Prefix, Options, Snippets, Items);
349 }
350 }
351}
352
353AttrPathCompleteParams mkParams(nixd::Selector Sel, bool IsComplete) {
354 if (IsComplete || Sel.empty()) {
355 return {
356 .Scope = std::move(Sel),
357 .Prefix = "",
358 };
359 }
360 std::string Back = std::move(Sel.back());
361 Sel.pop_back();
362 return {
363 .Scope = Sel,
364 .Prefix = std::move(Back),
365 };
366}
367
368#define DBG DBGPREFIX ": "
369
370void completeVarName(const VariableLookupAnalysis &VLA,
371 const ParentMapAnalysis &PM, const nixf::ExprVar &N,
372 AttrSetClient &Client, std::vector<CompletionItem> &List) {
373#define DBGPREFIX "completion/var"
374
375 VLACompletionProvider VLAP(VLA);
376 VLAP.complete(N, List, PM);
377
378 // Try to complete the name by known idioms.
379 try {
380 Selector Sel = idioms::mkVarSelector(N, VLA, PM);
381
382 // Clickling "pkgs" does not make sense for variable completion
383 if (Sel.empty())
384 return;
385
386 // Invoke nixpkgs provider to get the completion list.
387 NixpkgsCompletionProvider NCP(Client);
388 // Variable names are always incomplete.
389 NCP.completePackages(mkParams(Sel, /*IsComplete=*/false), List);
390 } catch (ExceedSizeError &) {
391 // Let "onCompletion" catch this exception to set "inComplete" field.
392 throw;
393 } catch (std::exception &E) {
394 return log(DBG "skipped, reason: {0}", E.what());
395 }
396
397#undef DBGPREFIX
398}
399
400/// \brief Complete a "select" expression.
401/// \param IsComplete Whether or not the last element of the selector is
402/// effectively incomplete.
403/// e.g.
404/// - incomplete: `lib.gen|`
405/// - complete: `lib.attrset.|`
406void completeSelect(const nixf::ExprSelect &Select, AttrSetClient &Client,
408 const nixf::ParentMapAnalysis &PM, bool IsComplete,
409 std::vector<CompletionItem> &List) {
410#define DBGPREFIX "completion/select"
411 // The base expr for selecting.
412 const nixf::Expr &BaseExpr = Select.expr();
413
414 // Determine that the name is one of special names interesting
415 // for nix language. If it is not a simple variable, skip this
416 // case.
417 if (BaseExpr.kind() != Node::NK_ExprVar) {
418 return;
419 }
420
421 const auto &Var = static_cast<const nixf::ExprVar &>(BaseExpr);
422 // Ask nixpkgs provider to get idioms completion.
423 NixpkgsCompletionProvider NCP(Client);
424
425 try {
426 Selector Sel =
427 idioms::mkSelector(Select, idioms::mkVarSelector(Var, VLA, PM));
428 NCP.completePackages(mkParams(Sel, IsComplete), List);
429 } catch (ExceedSizeError &) {
430 // Let "onCompletion" catch this exception to set "inComplete" field.
431 throw;
432 } catch (std::exception &E) {
433 return log(DBG "skipped, reason: {0}", E.what());
434 }
435
436#undef DBGPREFIX
437}
438
439} // namespace
440
441void Controller::onCompletion(const CompletionParams &Params,
443 using CheckTy = CompletionList;
444 auto Action = [Reply = std::move(Reply), URI = Params.textDocument.uri,
445 Pos = toNixfPosition(Params.position), this]() mutable {
446 const auto File = URI.file().str();
447 return Reply([&]() -> llvm::Expected<CompletionList> {
448 const auto TU = CheckDefault(getTU(File));
449 const auto AST = CheckDefault(getAST(*TU));
450
451 const auto *Desc = AST->descend({Pos, Pos});
452 CheckDefault(Desc && canCompleteAt(*Desc));
453
454 const auto &N = *Desc;
455 const auto &PM = *TU->parentMap();
456 const auto &UpExpr = *CheckDefault(PM.upExpr(N));
457
458 return [&]() {
459 CompletionList List;
460 const VariableLookupAnalysis &VLA = *TU->variableLookup();
461 try {
462 switch (UpExpr.kind()) {
463 // In these cases, assume the cursor have "variable" scoping.
464 case Node::NK_ExprVar: {
465 completeVarName(VLA, PM, static_cast<const nixf::ExprVar &>(UpExpr),
466 *nixpkgsClient(), List.items);
467 return List;
468 }
469 // A "select" expression. e.g.
470 // foo.a|
471 // foo.|
472 // foo.a.bar|
473 case Node::NK_ExprSelect: {
474 const auto &Select = static_cast<const nixf::ExprSelect &>(UpExpr);
475 completeSelect(Select, *nixpkgsClient(), VLA, PM,
476 N.kind() == Node::NK_Dot, List.items);
477 return List;
478 }
479 case Node::NK_ExprAttrs: {
480 completeAttrPath(N, PM, OptionsLock, Options,
481 ClientCaps.CompletionSnippets, List.items);
482 return List;
483 }
484 default:
485 return List;
486 }
487 } catch (ExceedSizeError &Err) {
488 List.isIncomplete = true;
489 return List;
490 }
491 }();
492 }());
493 };
494 boost::asio::post(Pool, std::move(Action));
495}
496
497void Controller::onCompletionItemResolve(const CompletionItem &Params,
499
500 auto Action = [Params, Reply = std::move(Reply), this]() mutable {
501 if (Params.data.empty()) {
502 Reply(Params);
503 return;
504 }
505 AttrPathCompleteParams Req;
506 auto EV = llvm::json::parse(Params.data);
507 if (!EV) {
508 // If the json value cannot be parsed, this is very unlikely to happen.
509 Reply(EV.takeError());
510 return;
511 }
512
513 llvm::json::Path::Root Root;
514 fromJSON(*EV, Req, Root);
515
516 // FIXME: handle null nixpkgsClient()
517 NixpkgsCompletionProvider NCP(*nixpkgsClient());
518 CompletionItem Resp = Params;
519 NCP.resolvePackage(Req.Scope, Params.label, Resp);
520
521 Reply(std::move(Resp));
522 };
523 boost::asio::post(Pool, std::move(Action));
524}
This file declares some common analysis (tree walk) on the AST.
Types used in nixpkgs provider.
#define CheckDefault(x)
Variant of CheckReturn, but returns default constructed CheckTy.
Definition CheckReturn.h:16
#define DBG
Convert between LSP and nixf types.
Lookup variable names, from it's parent scope.
std::map< std::string, std::unique_ptr< AttrSetClientProc > > OptionMapTy
Definition Controller.h:21
bool isBuiltin() const
EnvNode * parent() const
const DefMap & defs() const
Expr & expr() const
Definition Expr.h:24
const Identifier & id() const
Definition Simple.h:200
const std::string & name() const
Definition Basic.h:120
NodeKind kind() const
Definition Basic.h:34
virtual ChildVector children() const =0
const Node * upExpr(const Node &N) const
Search up until the node becomes a concrete expression. a ^<--— ID -> ExprVar.
Definition ParentMap.cpp:17
Whether current platform treats paths case insensitively.
Definition Connection.h:11
llvm::unique_function< void(llvm::Expected< T >)> Callback
Definition Function.h:14
void elog(const char *Fmt, Ts &&...Vals)
Definition Logger.h:52
CompletionItemKind
The kind of a completion entry.
void log(const char *Fmt, Ts &&...Vals)
Definition Logger.h:58
Selector mkVarSelector(const nixf::ExprVar &Var, const nixf::VariableLookupAnalysis &VLA, const nixf::ParentMapAnalysis &PM)
Construct a nixd::Selector from Var.
Definition AST.cpp:199
Selector mkSelector(const nixf::AttrPath &AP, Selector BaseSelector)
Construct a nixd::Selector from AP.
Definition AST.cpp:249
bool fromJSON(const llvm::json::Value &Params, Configuration::Diagnostic &R, llvm::json::Path P)
llvm::json::Value toJSON(const PackageDescription &Params)
Definition AttrSet.cpp:56
const nixf::EnvNode * upEnv(const nixf::Node &Desc, const nixf::VariableLookupAnalysis &VLA, const nixf::ParentMapAnalysis &PM)
Search up until there are some node associated with "EnvNode".
Definition AST.cpp:98
std::vector< std::string > Selector
A list of strings that "select"s into a attribute set.
Definition AttrSet.h:43
FindAttrPathResult
Definition AST.h:119
nixf::Position toNixfPosition(const lspserver::Position &P)
Definition Convert.cpp:32
FindAttrPathResult findAttrPathForOptions(const nixf::Node &N, const nixf::ParentMapAnalysis &PM, std::vector< std::string > &Path)
Heuristically find attrpath suitable for "attrpath" completion. Strips "config." from the start to su...
Definition AST.cpp:332
std::vector< OptionField > OptionCompleteResponse
Definition AttrSet.h:152
std::optional< MarkupContent > documentation
A human-readable string that represents a doc-comment.
std::vector< CompletionItem > items
The completion items.
Position position
The position inside the text document.
TextDocumentIdentifier textDocument
The text document.
std::string Prefix
Search for packages prefixed with this "prefix".
Definition AttrSet.h:110
PackageDescription PackageDesc
Package description of the attribute path, if available.
Definition AttrSet.h:98
std::optional< std::string > Description
Definition AttrSet.h:129
std::optional< std::string > Example
Definition AttrSet.h:132
std::optional< OptionType > Type
Definition AttrSet.h:134
std::optional< std::string > Default
Definition AttrSet.h:133
std::optional< std::string > Version
Definition AttrSet.h:53
std::optional< std::string > Description
Definition AttrSet.h:54
std::optional< std::string > LongDescription
Definition AttrSet.h:55