17#include <boost/asio/post.hpp>
33constexpr int MaxCompletionSize = 30;
38struct ExceedSizeError : std::exception {
39 [[nodiscard]]
const char *what() const noexcept
override {
40 return "Size exceeded";
44void addItem(std::vector<CompletionItem> &Items,
CompletionItem Item) {
45 if (Items.size() >= MaxCompletionSize) {
46 throw ExceedSizeError();
48 Items.emplace_back(std::move(Item));
51class VLACompletionProvider {
52 const VariableLookupAnalysis &VLA;
56 return CompletionItemKind::Keyword;
58 return CompletionItemKind::Variable;
62 void collectDef(std::vector<CompletionItem> &Items,
const EnvNode *Env,
63 const std::string &Prefix) {
66 collectDef(Items, Env->
parent(), Prefix);
67 for (
const auto &[Name, Def] : Env->
defs()) {
72 if (Name.starts_with(Prefix)) {
73 addItem(Items, CompletionItem{
75 .kind = getCompletionItemKind(*Def),
82 VLACompletionProvider(
const VariableLookupAnalysis &VLA) : VLA(VLA) {}
85 void complete(
const nixf::ExprVar &Desc, std::vector<CompletionItem> &Items,
86 const ParentMapAnalysis &PM) {
87 std::string Prefix = Desc.
id().
name();
88 collectDef(Items,
upEnv(Desc, VLA, PM), Prefix);
99class NixpkgsCompletionProvider {
101 AttrSetClient &NixpkgsClient;
104 NixpkgsCompletionProvider(AttrSetClient &NixpkgsClient)
105 : NixpkgsClient(NixpkgsClient) {}
107 void resolvePackage(std::vector<std::string> Scope, std::string Name,
108 CompletionItem &Item) {
109 std::binary_semaphore Ready(0);
110 AttrPathInfoResponse Desc;
111 auto OnReply = [&Ready, &Desc](llvm::Expected<AttrPathInfoResponse> Resp) {
116 Scope.emplace_back(std::move(Name));
117 NixpkgsClient.attrpathInfo(Scope, std::move(OnReply));
122 .kind = MarkupKind::Markdown,
130 void completePackages(
const AttrPathCompleteParams &Params,
131 std::vector<CompletionItem> &Items) {
132 std::binary_semaphore Ready(0);
133 std::vector<std::string> Names;
134 auto OnReply = [&Ready,
135 &Names](llvm::Expected<AttrPathCompleteResponse> Resp) {
145 NixpkgsClient.attrpathComplete(Params, std::move(OnReply));
148 for (
const auto &Name : Names) {
149 if (Name.starts_with(Params.
Prefix)) {
150 addItem(Items, CompletionItem{
152 .kind = CompletionItemKind::Field,
153 .data = llvm::formatv(
"{0}",
toJSON(Params)),
161class OptionCompletionProvider {
162 AttrSetClient &OptionClient;
165 std::string ModuleOrigin;
168 bool ClientSupportSnippet;
170 static std::string escapeCharacters(
const std::set<char> &Charset,
171 const std::string &Origin) {
174 Ret.reserve(Origin.size());
175 for (
const auto Ch : Origin) {
176 if (Charset.contains(Ch)) {
186 void fillInsertText(CompletionItem &Item,
const std::string &Name,
187 const OptionDescription &Desc)
const {
188 if (!ClientSupportSnippet) {
196 "${1:" + escapeCharacters({
'\\',
'$',
'}'}, Desc.
Example.value_or(
"")) +
201 OptionCompletionProvider(AttrSetClient &OptionClient,
202 std::string ModuleOrigin,
bool ClientSupportSnippet)
203 : OptionClient(OptionClient), ModuleOrigin(std::move(ModuleOrigin)),
204 ClientSupportSnippet(ClientSupportSnippet) {}
206 void completeOptions(std::vector<std::string> Scope, std::string Prefix,
207 std::vector<CompletionItem> &Items) {
208 std::binary_semaphore Ready(0);
210 auto OnReply = [&Ready,
211 &Names](llvm::Expected<OptionCompleteResponse> Resp) {
221 AttrPathCompleteParams Params{std::move(Scope), std::move(Prefix)};
222 OptionClient.optionComplete(Params, std::move(OnReply));
225 for (
const nixd::OptionField &
Field : Names) {
229 Item.
detail = ModuleOrigin;
231 if (
Field.Description) {
233 Item.
kind = OptionKind;
234 fillInsertText(Item,
Field.Name, Desc);
236 .kind = MarkupKind::Markdown,
241 std::string TypeName = Desc.
Type->Name.value_or(
"");
242 std::string TypeDesc = Desc.
Type->Description.value_or(
"");
243 Item.
detail += llvm::formatv(
"{0} ({1})", TypeName, TypeDesc);
245 Item.
detail +=
"? (missing type)";
247 addItem(Items, std::move(Item));
249 Item.
kind = OptionAttrKind;
250 addItem(Items, std::move(Item));
256void completeAttrName(
const std::vector<std::string> &Scope,
257 const std::string &Prefix,
259 std::vector<CompletionItem> &List) {
260 for (
const auto &[Name, Provider] : Options) {
262 if (!Client) [[unlikely]] {
263 elog(
"skipped client {0} as it is dead", Name);
266 OptionCompletionProvider OCP(*Client, Name, CompletionSnippets);
267 OCP.completeOptions(Scope, Prefix, List);
274 std::vector<lspserver::CompletionItem> &Items) {
275 std::vector<std::string> Scope;
278 if (R == PathResult::OK) {
280 std::string Prefix = Scope.back();
283 std::lock_guard
_(OptionsLock);
284 completeAttrName(Scope, Prefix, Options, Snippets, Items);
290 if (IsComplete || Sel.empty()) {
292 .Scope = std::move(Sel),
296 std::string Back = std::move(Sel.back());
300 .Prefix = std::move(Back),
304#define DBG DBGPREFIX ": "
309#define DBGPREFIX "completion/var"
311 VLACompletionProvider VLAP(VLA);
312 VLAP.complete(N, List, PM);
323 NixpkgsCompletionProvider NCP(Client);
325 NCP.completePackages(mkParams(Sel,
false), List);
326 }
catch (ExceedSizeError &) {
329 }
catch (std::exception &E) {
330 return log(
DBG "skipped, reason: {0}", E.what());
345 std::vector<CompletionItem> &List) {
346#define DBGPREFIX "completion/select"
353 if (BaseExpr.
kind() != Node::NK_ExprVar) {
357 const auto &Var =
static_cast<const nixf::ExprVar &
>(BaseExpr);
359 NixpkgsCompletionProvider NCP(Client);
364 NCP.completePackages(mkParams(Sel, IsComplete), List);
365 }
catch (ExceedSizeError &) {
368 }
catch (std::exception &E) {
369 return log(
DBG "skipped, reason: {0}", E.what());
379 using CheckTy = CompletionList;
380 auto Action = [Reply = std::move(Reply), URI = Params.
textDocument.
uri,
382 const auto File = URI.file().str();
383 return Reply([&]() -> llvm::Expected<CompletionList> {
387 const auto *Desc = AST->descend({Pos, Pos});
390 const auto &N = *Desc;
391 const auto &PM = *TU->parentMap();
396 const VariableLookupAnalysis &VLA = *TU->variableLookup();
398 switch (UpExpr.kind()) {
400 case Node::NK_ExprVar: {
401 completeVarName(VLA, PM,
static_cast<const nixf::ExprVar &
>(UpExpr),
402 *nixpkgsClient(), List.
items);
409 case Node::NK_ExprSelect: {
410 const auto &Select =
static_cast<const nixf::ExprSelect &
>(UpExpr);
411 completeSelect(Select, *nixpkgsClient(), VLA, PM,
415 case Node::NK_ExprAttrs: {
416 completeAttrPath(N, PM, OptionsLock, Options,
417 ClientCaps.CompletionSnippets, List.
items);
423 }
catch (ExceedSizeError &Err) {
430 boost::asio::post(Pool, std::move(Action));
433void Controller::onCompletionItemResolve(
const CompletionItem &Params,
436 auto Action = [Params, Reply = std::move(Reply),
this]()
mutable {
437 if (Params.
data.empty()) {
441 AttrPathCompleteParams Req;
442 auto EV = llvm::json::parse(Params.
data);
445 Reply(EV.takeError());
449 llvm::json::Path::Root Root;
453 NixpkgsCompletionProvider NCP(*nixpkgsClient());
454 CompletionItem Resp = Params;
455 NCP.resolvePackage(Req.
Scope, Params.
label, Resp);
457 Reply(std::move(Resp));
459 boost::asio::post(Pool, std::move(Action));
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
Convert between LSP and nixf types.
Lookup variable names, from it's parent scope.
std::map< std::string, std::unique_ptr< AttrSetClientProc > > OptionMapTy
const DefMap & defs() const
const Identifier & id() const
const std::string & name() const
const Node * upExpr(const Node &N) const
Search up until the node becomes a concrete expression. a ^<--— ID -> ExprVar.
Whether current platform treats paths case insensitively.
llvm::unique_function< void(llvm::Expected< T >)> Callback
void elog(const char *Fmt, Ts &&...Vals)
CompletionItemKind
The kind of a completion entry.
void log(const char *Fmt, Ts &&...Vals)
Selector mkVarSelector(const nixf::ExprVar &Var, const nixf::VariableLookupAnalysis &VLA, const nixf::ParentMapAnalysis &PM)
Construct a nixd::Selector from Var.
Selector mkSelector(const nixf::AttrPath &AP, Selector BaseSelector)
Construct a nixd::Selector from AP.
bool fromJSON(const llvm::json::Value &Params, Configuration::Diagnostic &R, llvm::json::Path P)
llvm::json::Value toJSON(const PackageDescription &Params)
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".
std::vector< std::string > Selector
A list of strings that "select"s into a attribute set.
nixf::Position toNixfPosition(const lspserver::Position &P)
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...
std::vector< OptionField > OptionCompleteResponse
InsertTextFormat insertTextFormat
std::optional< MarkupContent > documentation
A human-readable string that represents a doc-comment.
std::vector< CompletionItem > items
The completion items.
URIForFile uri
The text document's URI.
Position position
The position inside the text document.
TextDocumentIdentifier textDocument
The text document.
std::string Prefix
Search for packages prefixed with this "prefix".
PackageDescription PackageDesc
Package description of the attribute path, if available.
std::optional< std::string > Description
std::optional< std::string > Example
std::optional< OptionType > Type
std::optional< std::string > Version
std::optional< std::string > Description
std::optional< std::string > LongDescription