Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nixd: path completion #530

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions libnixf/src/Parse/Lexer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,8 @@ bool Lexer::consumePathStart() {
// And also check if it contains a slash.
LexerCursor Saved = cur();

bool IsStartedWithDot = peek() == '.';

// {PATH_CHAR}*
consumeManyPathChar();

Expand All @@ -233,6 +235,10 @@ bool Lexer::consumePathStart() {
// This should be parsed as path-interpolation.
if (peekPrefix("${"))
return true;
// Or, look back to see if is a './'.
// This should be parsed as path
if (IsStartedWithDot)
return true;
}

// Otherwise, it is not a path, restore cursor.
Expand Down
14 changes: 14 additions & 0 deletions libnixf/test/Parse/Lexer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

#include "Lexer.h"

#include "Token.h"
Origami404 marked this conversation as resolved.
Show resolved Hide resolved
#include "nixf/Basic/Diagnostic.h"
#include "nixf/Basic/TokenKinds.h"

#include <cstddef>

Expand Down Expand Up @@ -173,6 +175,18 @@ TEST_F(LexerTest, lexIDPath) {
ASSERT_EQ(Tokens.size(), sizeof(Match) / sizeof(TokenKind));
}

TEST_F(LexerTest, lexPathStart) {
Lexer Lexer(R"(./)", Diags);
const TokenKind Match[] = {
tok_path_fragment,
};
auto Tokens = collect(Lexer, &Lexer::lex);
for (size_t I = 0; I < sizeof(Match) / sizeof(TokenKind); I++) {
ASSERT_EQ(Tokens[I].kind(), Match[I]);
}
ASSERT_EQ(Tokens.size(), sizeof(Match) / sizeof(TokenKind));
}

TEST_F(LexerTest, lexKW) {
// FIXME: test pp//a to see that we can lex this as Update(pp, a)
Lexer Lexer(R"(if then)", Diags);
Expand Down
64 changes: 60 additions & 4 deletions nixd/lib/Controller/Completion.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@

#include <boost/asio/post.hpp>

#include <llvm/Support/FileSystem.h>
#include <llvm/Support/Path.h>
#include <semaphore>
#include <set>
#include <utility>
Expand Down Expand Up @@ -250,6 +252,43 @@ class OptionCompletionProvider {
}
};

void completeExprPath(const std::string &CurFilePath,
const nixf::ExprPath &ExprPath,
std::vector<CompletionItem> &Items) {
using namespace llvm::sys;

if (!ExprPath.parts().isLiteral()) {
return;
}

const auto &PathLiteral = ExprPath.parts().literal();
if (PathLiteral.empty()) {
return;
}

llvm::SmallVector<char, 32> Path{PathLiteral.begin(), PathLiteral.end()};
if (PathLiteral[0] == '.') {
const auto &CurFileDir = path::parent_path(CurFilePath);
fs::make_absolute(CurFileDir, Path);
}

if (fs::exists(Path) && fs::is_directory(Path)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we do this in std::filesystem?

std::error_code EC;
for (auto Iter = fs::directory_iterator(Path, EC, false);
Iter != fs::directory_iterator(); Iter.increment(EC)) {
if (EC) {
vlog("failed to read directory: {0}", EC.message());
break;
}
addItem(Items, CompletionItem{
.label = path::filename(Iter->path()).str(),
.kind = CompletionItemKind::File,
.data = ExprPath.parts().literal(),
});
}
}
}

void completeAttrName(const std::vector<std::string> &Scope,
const std::string &Prefix,
Controller::OptionMapTy &Options, bool CompletionSnippets,
Expand Down Expand Up @@ -285,11 +324,12 @@ void Controller::onCompletion(const CompletionParams &Params,
}
CompletionList List;
try {
bool FinishedCompletion = false;
const ParentMapAnalysis &PM = *TU->parentMap();

// if we are in an attribute path, use AttrCompletionProvider only
std::vector<std::string> Scope;
using PathResult = FindAttrPathResult;
auto R = findAttrPath(*Desc, PM, Scope);
if (R == PathResult::OK) {
if (findAttrPath(*Desc, PM, Scope) == FindAttrPathResult::OK) {
// Construct request.
std::string Prefix = Scope.back();
Scope.pop_back();
Expand All @@ -298,7 +338,23 @@ void Controller::onCompletion(const CompletionParams &Params,
completeAttrName(Scope, Prefix, Options,
ClientCaps.CompletionSnippets, List.items);
}
} else {
FinishedCompletion = true;
}

// if we are in a literal path, use PathCompletionProvider only
if (!FinishedCompletion) {
inclyc marked this conversation as resolved.
Show resolved Hide resolved
const auto *Parent = PM.upExpr(*Desc);
if (Parent->kind() == Node::NK_ExprPath) {
const auto &Path = static_cast<const nixf::ExprPath &>(*Parent);
if (Path.parts().isLiteral()) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (Path.parts().isLiteral()) {
if (Path.parts().isLiteral())

remove this curly brace?

completeExprPath(File, Path, List.items);
FinishedCompletion = true;
}
}
}

// otherwise, fallback to VLACompletionProvider
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can determine whether or not providing VLA completion based on the upExpr result. For example if an ExprPath is encountered, then provide path completion, otherwise if ExprVar, provide VLA completion. Try to determine expr kind first, may make the source code more concise.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When writing code, I believe that in future there will be more and more different completion modes added, and ultimately form something like that:

image

IMO the nested levels of codes will be too deep if we just adding if, so I refactor this part of code. But since we only have 3 completion modes at this time, I will revert changes here and use nested if.

Another solution here will be some gotos.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO the nested levels of codes will be too deep if we just adding if, so I refactor this part of code. But since we only have 3 completion modes at this time,

These three completion modes are switchable by the "context" of nix codes. For example, I suppose the attrpath completion only makes sense if there is actually an attrpath user typing, and path completion only makes sense if we are in attrpath.

Another solution here will be some gotos.

No, we are not writing automata.

if (!FinishedCompletion) {
const VariableLookupAnalysis &VLA = *TU->variableLookup();
VLACompletionProvider VLAP(VLA);
VLAP.complete(*Desc, List.items, PM);
Expand Down
Empty file.
Empty file.
85 changes: 85 additions & 0 deletions nixd/tools/nixd/test/completion-path.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# RUN: sed "s|ROOT|%S|g" < %s | nixd --lit-test | FileCheck %s

<-- initialize(0)

```json
{
"jsonrpc":"2.0",
"id":0,
"method":"initialize",
"params":{
"processId":123,
"rootPath":"",
"capabilities": {
},
"trace":"off"
}
}
```


<-- textDocument/didOpen


```json
{
"jsonrpc":"2.0",
"method":"textDocument/didOpen",
"params":{
"textDocument":{
"uri":"file://ROOT/completion-path-root/main.nix",
"languageId":"nix",
"version":1,
"text":"{ bar = ./ }"
}
}
}
```

```json
{
"jsonrpc": "2.0",
"id": 1,
"method": "textDocument/completion",
"params": {
"textDocument": {
"uri": "file://ROOT/completion-path-root/main.nix"
},
"position": {
"line": 0,
"character": 9
},
"context": {
"triggerKind": 1,
"triggerCharacter": "/"
}
}
}
```

```
CHECK: "id": 1,
CHECK-NEXT: "jsonrpc": "2.0",
CHECK-NEXT: "result": {
CHECK-NEXT: "isIncomplete": false,
CHECK-NEXT: "items": [
CHECK-NEXT: {
CHECK-NEXT: "data": "./",
CHECK-NEXT: "kind": 17,
CHECK-NEXT: "label": "foo",
CHECK-NEXT: "score": 0
CHECK-NEXT: },
CHECK-NEXT: {
CHECK-NEXT: "data": "./",
CHECK-NEXT: "kind": 17,
CHECK-NEXT: "label": "main.nix",
CHECK-NEXT: "score": 0
CHECK-NEXT: }
CHECK-NEXT: ]
CHECK-NEXT: }
```


```json
{"jsonrpc":"2.0","method":"exit"}
```
Loading