Skip to content

Commit be6d07c

Browse files
committed
[clangd] Reapply b60896f Fall back to selecting token-before-cursor if token-after-cursor fails.
This reverts commit b4b9706. Now avoiding expected<vector<selection>> in favor of expected<vector<unique_ptr<selection>>>
1 parent 335e21f commit be6d07c

14 files changed

+306
-135
lines changed

clang-tools-extra/clangd/ClangdServer.cpp

+51-22
Original file line numberDiff line numberDiff line change
@@ -395,15 +395,26 @@ void ClangdServer::rename(PathRef File, Position Pos, llvm::StringRef NewName,
395395
WorkScheduler.runWithAST("Rename", File, std::move(Action));
396396
}
397397

398-
static llvm::Expected<Tweak::Selection>
398+
// May generate several candidate selections, due to SelectionTree ambiguity.
399+
// vector of pointers because GCC doesn't like non-copyable Selection.
400+
static llvm::Expected<std::vector<std::unique_ptr<Tweak::Selection>>>
399401
tweakSelection(const Range &Sel, const InputsAndAST &AST) {
400402
auto Begin = positionToOffset(AST.Inputs.Contents, Sel.start);
401403
if (!Begin)
402404
return Begin.takeError();
403405
auto End = positionToOffset(AST.Inputs.Contents, Sel.end);
404406
if (!End)
405407
return End.takeError();
406-
return Tweak::Selection(AST.Inputs.Index, AST.AST, *Begin, *End);
408+
std::vector<std::unique_ptr<Tweak::Selection>> Result;
409+
SelectionTree::createEach(
410+
AST.AST.getASTContext(), AST.AST.getTokens(), *Begin, *End,
411+
[&](SelectionTree T) {
412+
Result.push_back(std::make_unique<Tweak::Selection>(
413+
AST.Inputs.Index, AST.AST, *Begin, *End, std::move(T)));
414+
return false;
415+
});
416+
assert(!Result.empty() && "Expected at least one SelectionTree");
417+
return Result;
407418
}
408419

409420
void ClangdServer::enumerateTweaks(PathRef File, Range Sel,
@@ -412,12 +423,21 @@ void ClangdServer::enumerateTweaks(PathRef File, Range Sel,
412423
this](Expected<InputsAndAST> InpAST) mutable {
413424
if (!InpAST)
414425
return CB(InpAST.takeError());
415-
auto Selection = tweakSelection(Sel, *InpAST);
416-
if (!Selection)
417-
return CB(Selection.takeError());
426+
auto Selections = tweakSelection(Sel, *InpAST);
427+
if (!Selections)
428+
return CB(Selections.takeError());
418429
std::vector<TweakRef> Res;
419-
for (auto &T : prepareTweaks(*Selection, TweakFilter))
420-
Res.push_back({T->id(), T->title(), T->intent()});
430+
// Don't allow a tweak to fire more than once across ambiguous selections.
431+
llvm::DenseSet<llvm::StringRef> PreparedTweaks;
432+
auto Filter = [&](const Tweak &T) {
433+
return TweakFilter(T) && !PreparedTweaks.count(T.id());
434+
};
435+
for (const auto &Sel : *Selections) {
436+
for (auto &T : prepareTweaks(*Sel, Filter)) {
437+
Res.push_back({T->id(), T->title(), T->intent()});
438+
PreparedTweaks.insert(T->id());
439+
}
440+
}
421441

422442
CB(std::move(Res));
423443
};
@@ -432,21 +452,30 @@ void ClangdServer::applyTweak(PathRef File, Range Sel, StringRef TweakID,
432452
FS = FSProvider.getFileSystem()](Expected<InputsAndAST> InpAST) mutable {
433453
if (!InpAST)
434454
return CB(InpAST.takeError());
435-
auto Selection = tweakSelection(Sel, *InpAST);
436-
if (!Selection)
437-
return CB(Selection.takeError());
438-
auto A = prepareTweak(TweakID, *Selection);
439-
if (!A)
440-
return CB(A.takeError());
441-
auto Effect = (*A)->apply(*Selection);
442-
if (!Effect)
443-
return CB(Effect.takeError());
444-
for (auto &It : Effect->ApplyEdits) {
445-
Edit &E = It.second;
446-
format::FormatStyle Style =
447-
getFormatStyleForFile(File, E.InitialCode, FS.get());
448-
if (llvm::Error Err = reformatEdit(E, Style))
449-
elog("Failed to format {0}: {1}", It.first(), std::move(Err));
455+
auto Selections = tweakSelection(Sel, *InpAST);
456+
if (!Selections)
457+
return CB(Selections.takeError());
458+
llvm::Optional<llvm::Expected<Tweak::Effect>> Effect;
459+
// Try each selection, take the first one that prepare()s.
460+
// If they all fail, Effect will hold get the last error.
461+
for (const auto &Selection : *Selections) {
462+
auto T = prepareTweak(TweakID, *Selection);
463+
if (T) {
464+
Effect = (*T)->apply(*Selection);
465+
break;
466+
}
467+
Effect = T.takeError();
468+
}
469+
assert(Effect.hasValue() && "Expected at least one selection");
470+
if (*Effect) {
471+
// Tweaks don't apply clang-format, do that centrally here.
472+
for (auto &It : (*Effect)->ApplyEdits) {
473+
Edit &E = It.second;
474+
format::FormatStyle Style =
475+
getFormatStyleForFile(File, E.InitialCode, FS.get());
476+
if (llvm::Error Err = reformatEdit(E, Style))
477+
elog("Failed to format {0}: {1}", It.first(), std::move(Err));
478+
}
450479
}
451480
return CB(std::move(*Effect));
452481
};

clang-tools-extra/clangd/Hover.cpp

+5-2
Original file line numberDiff line numberDiff line change
@@ -537,9 +537,12 @@ llvm::Optional<HoverInfo> getHover(ParsedAST &AST, Position Pos,
537537
llvm::consumeError(Offset.takeError());
538538
return llvm::None;
539539
}
540-
SelectionTree Selection(AST.getASTContext(), AST.getTokens(), *Offset);
540+
// Editors send the position on the left of the hovered character.
541+
// So our selection tree should be biased right. (Tested with VSCode).
542+
SelectionTree ST = SelectionTree::createRight(
543+
AST.getASTContext(), AST.getTokens(), *Offset, *Offset);
541544
std::vector<const Decl *> Result;
542-
if (const SelectionTree::Node *N = Selection.commonAncestor()) {
545+
if (const SelectionTree::Node *N = ST.commonAncestor()) {
543546
auto Decls = explicitReferenceTargets(N->ASTNode, DeclRelation::Alias);
544547
if (!Decls.empty()) {
545548
HI = getHoverContents(Decls.front(), Index);

clang-tools-extra/clangd/Selection.cpp

+49-27
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,11 @@ void update(SelectionTree::Selection &Result, SelectionTree::Selection New) {
142142
Result = SelectionTree::Partial;
143143
}
144144

145+
// As well as comments, don't count semicolons as real tokens.
146+
// They're not properly claimed as expr-statement is missing from the AST.
147+
bool shouldIgnore(const syntax::Token &Tok) {
148+
return Tok.kind() == tok::comment || Tok.kind() == tok::semi;
149+
}
145150

146151
// SelectionTester can determine whether a range of tokens from the PP-expanded
147152
// stream (corresponding to an AST node) is considered selected.
@@ -172,9 +177,7 @@ class SelectionTester {
172177
});
173178
// Precompute selectedness and offset for selected spelled tokens.
174179
for (const syntax::Token *T = SelFirst; T < SelLimit; ++T) {
175-
// As well as comments, don't count semicolons as real tokens.
176-
// They're not properly claimed as expr-statement is missing from the AST.
177-
if (T->kind() == tok::comment || T->kind() == tok::semi)
180+
if (shouldIgnore(*T))
178181
continue;
179182
SpelledTokens.emplace_back();
180183
Tok &S = SpelledTokens.back();
@@ -671,24 +674,49 @@ std::string SelectionTree::Node::kind() const {
671674
return std::move(OS.str());
672675
}
673676

674-
// Decide which selection emulates a "point" query in between characters.
675-
static std::pair<unsigned, unsigned> pointBounds(unsigned Offset, FileID FID,
676-
ASTContext &AST) {
677-
StringRef Buf = AST.getSourceManager().getBufferData(FID);
678-
// Edge-cases where the choice is forced.
679-
if (Buf.size() == 0)
680-
return {0, 0};
681-
if (Offset == 0)
682-
return {0, 1};
683-
if (Offset == Buf.size())
684-
return {Offset - 1, Offset};
685-
// We could choose either this byte or the previous. Usually we prefer the
686-
// character on the right of the cursor (or under a block cursor).
687-
// But if that's whitespace/semicolon, we likely want the token on the left.
688-
auto IsIgnoredChar = [](char C) { return isWhitespace(C) || C == ';'; };
689-
if (IsIgnoredChar(Buf[Offset]) && !IsIgnoredChar(Buf[Offset - 1]))
690-
return {Offset - 1, Offset};
691-
return {Offset, Offset + 1};
677+
// Decide which selections emulate a "point" query in between characters.
678+
// If it's ambiguous (the neighboring characters are selectable tokens), returns
679+
// both possibilities in preference order.
680+
// Always returns at least one range - if no tokens touched, and empty range.
681+
static llvm::SmallVector<std::pair<unsigned, unsigned>, 2>
682+
pointBounds(unsigned Offset, const syntax::TokenBuffer &Tokens) {
683+
const auto &SM = Tokens.sourceManager();
684+
SourceLocation Loc = SM.getComposedLoc(SM.getMainFileID(), Offset);
685+
llvm::SmallVector<std::pair<unsigned, unsigned>, 2> Result;
686+
// Prefer right token over left.
687+
for (const syntax::Token &Tok :
688+
llvm::reverse(spelledTokensTouching(Loc, Tokens))) {
689+
if (shouldIgnore(Tok))
690+
continue;
691+
unsigned Offset = Tokens.sourceManager().getFileOffset(Tok.location());
692+
Result.emplace_back(Offset, Offset + Tok.length());
693+
}
694+
if (Result.empty())
695+
Result.emplace_back(Offset, Offset);
696+
return Result;
697+
}
698+
699+
bool SelectionTree::createEach(ASTContext &AST,
700+
const syntax::TokenBuffer &Tokens,
701+
unsigned Begin, unsigned End,
702+
llvm::function_ref<bool(SelectionTree)> Func) {
703+
if (Begin != End)
704+
return Func(SelectionTree(AST, Tokens, Begin, End));
705+
for (std::pair<unsigned, unsigned> Bounds : pointBounds(Begin, Tokens))
706+
if (Func(SelectionTree(AST, Tokens, Bounds.first, Bounds.second)))
707+
return true;
708+
return false;
709+
}
710+
711+
SelectionTree SelectionTree::createRight(ASTContext &AST,
712+
const syntax::TokenBuffer &Tokens,
713+
unsigned int Begin, unsigned int End) {
714+
llvm::Optional<SelectionTree> Result;
715+
createEach(AST, Tokens, Begin, End, [&](SelectionTree T) {
716+
Result = std::move(T);
717+
return true;
718+
});
719+
return std::move(*Result);
692720
}
693721

694722
SelectionTree::SelectionTree(ASTContext &AST, const syntax::TokenBuffer &Tokens,
@@ -698,8 +726,6 @@ SelectionTree::SelectionTree(ASTContext &AST, const syntax::TokenBuffer &Tokens,
698726
// but that's all clangd has needed so far.
699727
const SourceManager &SM = AST.getSourceManager();
700728
FileID FID = SM.getMainFileID();
701-
if (Begin == End)
702-
std::tie(Begin, End) = pointBounds(Begin, FID, AST);
703729
PrintPolicy.TerseOutput = true;
704730
PrintPolicy.IncludeNewlines = false;
705731

@@ -711,10 +737,6 @@ SelectionTree::SelectionTree(ASTContext &AST, const syntax::TokenBuffer &Tokens,
711737
dlog("Built selection tree\n{0}", *this);
712738
}
713739

714-
SelectionTree::SelectionTree(ASTContext &AST, const syntax::TokenBuffer &Tokens,
715-
unsigned Offset)
716-
: SelectionTree(AST, Tokens, Offset, Offset) {}
717-
718740
const Node *SelectionTree::commonAncestor() const {
719741
const Node *Ancestor = Root;
720742
while (Ancestor->Children.size() == 1 && !Ancestor->Selected)

clang-tools-extra/clangd/Selection.h

+39-10
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,14 @@
2929
// - we determine which low-level nodes are partly or completely covered
3030
// by the selection.
3131
// - we expose a tree of the selected nodes and their lexical parents.
32+
//
33+
// Sadly LSP specifies locations as being between characters, and this causes
34+
// some ambiguities we cannot cleanly resolve:
35+
// lhs+rhs // targeting '+' or 'lhs'?
36+
// ^ // in GUI editors, double-clicking 'lhs' yields this position!
37+
//
38+
// The best we can do in these cases is try both, which leads to the awkward
39+
// SelectionTree::createEach() API.
3240
//===----------------------------------------------------------------------===//
3341

3442
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_SELECTION_H
@@ -64,16 +72,32 @@ namespace clangd {
6472
// point back into the AST it was constructed with.
6573
class SelectionTree {
6674
public:
67-
// Creates a selection tree at the given byte offset in the main file.
68-
// This is approximately equivalent to a range of one character.
69-
// (Usually, the character to the right of Offset, sometimes to the left).
70-
SelectionTree(ASTContext &AST, const syntax::TokenBuffer &Tokens,
71-
unsigned Offset);
72-
// Creates a selection tree for the given range in the main file.
73-
// The range includes bytes [Start, End).
74-
// If Start == End, uses the same heuristics as SelectionTree(AST, Start).
75-
SelectionTree(ASTContext &AST, const syntax::TokenBuffer &Tokens,
76-
unsigned Start, unsigned End);
75+
// Create selection trees for the given range, and pass them to Func.
76+
//
77+
// There may be multiple possible selection trees:
78+
// - if the range is empty and borders two tokens, a tree for the right token
79+
// and a tree for the left token will be yielded.
80+
// - Func should return true on success (stop) and false on failure (continue)
81+
//
82+
// Always yields at least one tree. If no tokens are touched, it is empty.
83+
static bool createEach(ASTContext &AST, const syntax::TokenBuffer &Tokens,
84+
unsigned Begin, unsigned End,
85+
llvm::function_ref<bool(SelectionTree)> Func);
86+
87+
// Create a selection tree for the given range.
88+
//
89+
// Where ambiguous (range is empty and borders two tokens), prefer the token
90+
// on the right.
91+
static SelectionTree createRight(ASTContext &AST,
92+
const syntax::TokenBuffer &Tokens,
93+
unsigned Begin, unsigned End);
94+
95+
// Copies are no good - contain pointers to other nodes.
96+
SelectionTree(const SelectionTree &) = delete;
97+
SelectionTree &operator=(const SelectionTree &) = delete;
98+
// Moves are OK though - internal storage is pointer-stable when moved.
99+
SelectionTree(SelectionTree &&) = default;
100+
SelectionTree &operator=(SelectionTree &&) = default;
77101

78102
// Describes to what extent an AST node is covered by the selection.
79103
enum Selection : unsigned char {
@@ -121,6 +145,11 @@ class SelectionTree {
121145
const Node &root() const { return *Root; }
122146

123147
private:
148+
// Creates a selection tree for the given range in the main file.
149+
// The range includes bytes [Start, End).
150+
SelectionTree(ASTContext &AST, const syntax::TokenBuffer &Tokens,
151+
unsigned Start, unsigned End);
152+
124153
std::deque<Node> Nodes; // Stable-pointer storage.
125154
const Node *Root;
126155
clang::PrintingPolicy PrintPolicy;

clang-tools-extra/clangd/SemanticSelection.cpp

+2-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@ llvm::Expected<std::vector<Range>> getSemanticRanges(ParsedAST &AST,
3939
}
4040

4141
// Get node under the cursor.
42-
SelectionTree ST(AST.getASTContext(), AST.getTokens(), *Offset);
42+
SelectionTree ST = SelectionTree::createRight(
43+
AST.getASTContext(), AST.getTokens(), *Offset, *Offset);
4344
for (const auto *Node = ST.commonAncestor(); Node != nullptr;
4445
Node = Node->Parent) {
4546
if (const Decl *D = Node->ASTNode.get<Decl>()) {

0 commit comments

Comments
 (0)