1 //===--- Selection.cpp ----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "Selection.h"
10 #include "SourceCode.h"
11 #include "support/Logger.h"
12 #include "clang/AST/ASTTypeTraits.h"
13 #include "clang/AST/Decl.h"
14 #include "clang/AST/DeclCXX.h"
15 #include "clang/AST/Expr.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/AST/PrettyPrinter.h"
18 #include "clang/AST/RecursiveASTVisitor.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/Basic/OperatorKinds.h"
21 #include "clang/Basic/SourceLocation.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Basic/TokenKinds.h"
24 #include "clang/Lex/Lexer.h"
25 #include "clang/Tooling/Syntax/Tokens.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/Support/Casting.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <algorithm>
30 #include <string>
31 
32 namespace clang {
33 namespace clangd {
34 namespace {
35 using Node = SelectionTree::Node;
36 using ast_type_traits::DynTypedNode;
37 
38 // An IntervalSet maintains a set of disjoint subranges of an array.
39 //
40 // Initially, it contains the entire array.
41 //           [-----------------------------------------------------------]
42 //
43 // When a range is erased(), it will typically split the array in two.
44 //  Claim:                     [--------------------]
45 //  after:   [----------------]                      [-------------------]
46 //
47 // erase() returns the segments actually erased. Given the state above:
48 //  Claim:          [---------------------------------------]
49 //  Out:            [---------]                      [------]
50 //  After:   [-----]                                         [-----------]
51 //
52 // It is used to track (expanded) tokens not yet associated with an AST node.
53 // On traversing an AST node, its token range is erased from the unclaimed set.
54 // The tokens actually removed are associated with that node, and hit-tested
55 // against the selection to determine whether the node is selected.
56 template <typename T> class IntervalSet {
57 public:
58   IntervalSet(llvm::ArrayRef<T> Range) { UnclaimedRanges.insert(Range); }
59 
60   // Removes the elements of Claim from the set, modifying or removing ranges
61   // that overlap it.
62   // Returns the continuous subranges of Claim that were actually removed.
63   llvm::SmallVector<llvm::ArrayRef<T>, 4> erase(llvm::ArrayRef<T> Claim) {
64     llvm::SmallVector<llvm::ArrayRef<T>, 4> Out;
65     if (Claim.empty())
66       return Out;
67 
68     // General case:
69     // Claim:                   [-----------------]
70     // UnclaimedRanges: [-A-] [-B-] [-C-] [-D-] [-E-] [-F-] [-G-]
71     // Overlap:               ^first                  ^second
72     // Ranges C and D are fully included. Ranges B and E must be trimmed.
73     auto Overlap = std::make_pair(
74         UnclaimedRanges.lower_bound({Claim.begin(), Claim.begin()}), // C
75         UnclaimedRanges.lower_bound({Claim.end(), Claim.end()}));    // F
76     // Rewind to cover B.
77     if (Overlap.first != UnclaimedRanges.begin()) {
78       --Overlap.first;
79       // ...unless B isn't selected at all.
80       if (Overlap.first->end() <= Claim.begin())
81         ++Overlap.first;
82     }
83     if (Overlap.first == Overlap.second)
84       return Out;
85 
86     // First, copy all overlapping ranges into the output.
87     auto OutFirst = Out.insert(Out.end(), Overlap.first, Overlap.second);
88     // If any of the overlapping ranges were sliced by the claim, split them:
89     //  - restrict the returned range to the claimed part
90     //  - save the unclaimed part so it can be reinserted
91     llvm::ArrayRef<T> RemainingHead, RemainingTail;
92     if (Claim.begin() > OutFirst->begin()) {
93       RemainingHead = {OutFirst->begin(), Claim.begin()};
94       *OutFirst = {Claim.begin(), OutFirst->end()};
95     }
96     if (Claim.end() < Out.back().end()) {
97       RemainingTail = {Claim.end(), Out.back().end()};
98       Out.back() = {Out.back().begin(), Claim.end()};
99     }
100 
101     // Erase all the overlapping ranges (invalidating all iterators).
102     UnclaimedRanges.erase(Overlap.first, Overlap.second);
103     // Reinsert ranges that were merely trimmed.
104     if (!RemainingHead.empty())
105       UnclaimedRanges.insert(RemainingHead);
106     if (!RemainingTail.empty())
107       UnclaimedRanges.insert(RemainingTail);
108 
109     return Out;
110   }
111 
112 private:
113   using TokenRange = llvm::ArrayRef<T>;
114   struct RangeLess {
115     bool operator()(llvm::ArrayRef<T> L, llvm::ArrayRef<T> R) const {
116       return L.begin() < R.begin();
117     }
118   };
119 
120   // Disjoint sorted unclaimed ranges of expanded tokens.
121   std::set<llvm::ArrayRef<T>, RangeLess> UnclaimedRanges;
122 };
123 
124 // Sentinel value for the selectedness of a node where we've seen no tokens yet.
125 // This resolves to Unselected if no tokens are ever seen.
126 // But Unselected + Complete -> Partial, while NoTokens + Complete --> Complete.
127 // This value is never exposed publicly.
128 constexpr SelectionTree::Selection NoTokens =
129     static_cast<SelectionTree::Selection>(
130         static_cast<unsigned char>(SelectionTree::Complete + 1));
131 
132 // Nodes start with NoTokens, and then use this function to aggregate the
133 // selectedness as more tokens are found.
134 void update(SelectionTree::Selection &Result, SelectionTree::Selection New) {
135   if (New == NoTokens)
136     return;
137   if (Result == NoTokens)
138     Result = New;
139   else if (Result != New)
140     // Can only be completely selected (or unselected) if all tokens are.
141     Result = SelectionTree::Partial;
142 }
143 
144 // As well as comments, don't count semicolons as real tokens.
145 // They're not properly claimed as expr-statement is missing from the AST.
146 bool shouldIgnore(const syntax::Token &Tok) {
147   return Tok.kind() == tok::comment || Tok.kind() == tok::semi;
148 }
149 
150 // Determine whether 'Target' is the first expansion of the macro
151 // argument whose top-level spelling location is 'SpellingLoc'.
152 bool isFirstExpansion(FileID Target, SourceLocation SpellingLoc,
153                       const SourceManager &SM) {
154   SourceLocation Prev = SpellingLoc;
155   while (true) {
156     // If the arg is expanded multiple times, getMacroArgExpandedLocation()
157     // returns the first expansion.
158     SourceLocation Next = SM.getMacroArgExpandedLocation(Prev);
159     // So if we reach the target, target is the first-expansion of the
160     // first-expansion ...
161     if (SM.getFileID(Next) == Target)
162       return true;
163 
164     // Otherwise, if the FileID stops changing, we've reached the innermost
165     // macro expansion, and Target was on a different branch.
166     if (SM.getFileID(Next) == SM.getFileID(Prev))
167       return false;
168 
169     Prev = Next;
170   }
171   return false;
172 }
173 
174 // SelectionTester can determine whether a range of tokens from the PP-expanded
175 // stream (corresponding to an AST node) is considered selected.
176 //
177 // When the tokens result from macro expansions, the appropriate tokens in the
178 // main file are examined (macro invocation or args). Similarly for #includes.
179 // However, only the first expansion of a given spelled token is considered
180 // selected.
181 //
182 // It tests each token in the range (not just the endpoints) as contiguous
183 // expanded tokens may not have contiguous spellings (with macros).
184 //
185 // Non-token text, and tokens not modeled in the AST (comments, semicolons)
186 // are ignored when determining selectedness.
187 class SelectionTester {
188 public:
189   // The selection is offsets [SelBegin, SelEnd) in SelFile.
190   SelectionTester(const syntax::TokenBuffer &Buf, FileID SelFile,
191                   unsigned SelBegin, unsigned SelEnd, const SourceManager &SM)
192       : SelFile(SelFile), SM(SM) {
193     // Find all tokens (partially) selected in the file.
194     auto AllSpelledTokens = Buf.spelledTokens(SelFile);
195     const syntax::Token *SelFirst =
196         llvm::partition_point(AllSpelledTokens, [&](const syntax::Token &Tok) {
197           return SM.getFileOffset(Tok.endLocation()) <= SelBegin;
198         });
199     const syntax::Token *SelLimit = std::partition_point(
200         SelFirst, AllSpelledTokens.end(), [&](const syntax::Token &Tok) {
201           return SM.getFileOffset(Tok.location()) < SelEnd;
202         });
203     // Precompute selectedness and offset for selected spelled tokens.
204     for (const syntax::Token *T = SelFirst; T < SelLimit; ++T) {
205       if (shouldIgnore(*T))
206         continue;
207       SpelledTokens.emplace_back();
208       Tok &S = SpelledTokens.back();
209       S.Offset = SM.getFileOffset(T->location());
210       if (S.Offset >= SelBegin && S.Offset + T->length() <= SelEnd)
211         S.Selected = SelectionTree::Complete;
212       else
213         S.Selected = SelectionTree::Partial;
214     }
215   }
216 
217   // Test whether a consecutive range of tokens is selected.
218   // The tokens are taken from the expanded token stream.
219   SelectionTree::Selection
220   test(llvm::ArrayRef<syntax::Token> ExpandedTokens) const {
221     if (SpelledTokens.empty())
222       return NoTokens;
223     SelectionTree::Selection Result = NoTokens;
224     while (!ExpandedTokens.empty()) {
225       // Take consecutive tokens from the same context together for efficiency.
226       FileID FID = SM.getFileID(ExpandedTokens.front().location());
227       auto Batch = ExpandedTokens.take_while([&](const syntax::Token &T) {
228         return SM.getFileID(T.location()) == FID;
229       });
230       assert(!Batch.empty());
231       ExpandedTokens = ExpandedTokens.drop_front(Batch.size());
232 
233       update(Result, testChunk(FID, Batch));
234     }
235     return Result;
236   }
237 
238   // Cheap check whether any of the tokens in R might be selected.
239   // If it returns false, test() will return NoTokens or Unselected.
240   // If it returns true, test() may return any value.
241   bool mayHit(SourceRange R) const {
242     if (SpelledTokens.empty())
243       return false;
244     auto B = SM.getDecomposedLoc(R.getBegin());
245     auto E = SM.getDecomposedLoc(R.getEnd());
246     if (B.first == SelFile && E.first == SelFile)
247       if (E.second < SpelledTokens.front().Offset ||
248           B.second > SpelledTokens.back().Offset)
249         return false;
250     return true;
251   }
252 
253 private:
254   // Hit-test a consecutive range of tokens from a single file ID.
255   SelectionTree::Selection
256   testChunk(FileID FID, llvm::ArrayRef<syntax::Token> Batch) const {
257     assert(!Batch.empty());
258     SourceLocation StartLoc = Batch.front().location();
259     // There are several possible categories of FileID depending on how the
260     // preprocessor was used to generate these tokens:
261     //   main file, #included file, macro args, macro bodies.
262     // We need to identify the main-file tokens that represent Batch, and
263     // determine whether we want to exclusively claim them. Regular tokens
264     // represent one AST construct, but a macro invocation can represent many.
265 
266     // Handle tokens written directly in the main file.
267     if (FID == SelFile) {
268       return testTokenRange(SM.getFileOffset(Batch.front().location()),
269                             SM.getFileOffset(Batch.back().location()));
270     }
271 
272     // Handle tokens in another file #included into the main file.
273     // Check if the #include is selected, but don't claim it exclusively.
274     if (StartLoc.isFileID()) {
275       for (SourceLocation Loc = Batch.front().location(); Loc.isValid();
276            Loc = SM.getIncludeLoc(SM.getFileID(Loc))) {
277         if (SM.getFileID(Loc) == SelFile)
278           // FIXME: use whole #include directive, not just the filename string.
279           return testToken(SM.getFileOffset(Loc));
280       }
281       return NoTokens;
282     }
283 
284     assert(StartLoc.isMacroID());
285     // Handle tokens that were passed as a macro argument.
286     SourceLocation ArgStart = SM.getTopMacroCallerLoc(StartLoc);
287     if (SM.getFileID(ArgStart) == SelFile) {
288       if (isFirstExpansion(FID, ArgStart, SM)) {
289         SourceLocation ArgEnd =
290             SM.getTopMacroCallerLoc(Batch.back().location());
291         return testTokenRange(SM.getFileOffset(ArgStart),
292                               SM.getFileOffset(ArgEnd));
293       } else {
294         /* fall through and treat as part of the macro body */
295       }
296     }
297 
298     // Handle tokens produced by non-argument macro expansion.
299     // Check if the macro name is selected, don't claim it exclusively.
300     auto Expansion = SM.getDecomposedExpansionLoc(StartLoc);
301     if (Expansion.first == SelFile)
302       // FIXME: also check ( and ) for function-like macros?
303       return testToken(Expansion.second);
304     else
305       return NoTokens;
306   }
307 
308   // Is the closed token range [Begin, End] selected?
309   SelectionTree::Selection testTokenRange(unsigned Begin, unsigned End) const {
310     assert(Begin <= End);
311     // Outside the selection entirely?
312     if (End < SpelledTokens.front().Offset ||
313         Begin > SpelledTokens.back().Offset)
314       return SelectionTree::Unselected;
315 
316     // Compute range of tokens.
317     auto B = llvm::partition_point(
318         SpelledTokens, [&](const Tok &T) { return T.Offset < Begin; });
319     auto E = std::partition_point(
320         B, SpelledTokens.end(), [&](const Tok &T) { return T.Offset <= End; });
321 
322     // Aggregate selectedness of tokens in range.
323     bool ExtendsOutsideSelection = Begin < SpelledTokens.front().Offset ||
324                                    End > SpelledTokens.back().Offset;
325     SelectionTree::Selection Result =
326         ExtendsOutsideSelection ? SelectionTree::Unselected : NoTokens;
327     for (auto It = B; It != E; ++It)
328       update(Result, It->Selected);
329     return Result;
330   }
331 
332   // Is the token at `Offset` selected?
333   SelectionTree::Selection testToken(unsigned Offset) const {
334     // Outside the selection entirely?
335     if (Offset < SpelledTokens.front().Offset ||
336         Offset > SpelledTokens.back().Offset)
337       return SelectionTree::Unselected;
338     // Find the token, if it exists.
339     auto It = llvm::partition_point(
340         SpelledTokens, [&](const Tok &T) { return T.Offset < Offset; });
341     if (It != SpelledTokens.end() && It->Offset == Offset)
342       return It->Selected;
343     return NoTokens;
344   }
345 
346   struct Tok {
347     unsigned Offset;
348     SelectionTree::Selection Selected;
349   };
350   std::vector<Tok> SpelledTokens;
351   FileID SelFile;
352   const SourceManager &SM;
353 };
354 
355 // Show the type of a node for debugging.
356 void printNodeKind(llvm::raw_ostream &OS, const DynTypedNode &N) {
357   if (const TypeLoc *TL = N.get<TypeLoc>()) {
358     // TypeLoc is a hierarchy, but has only a single ASTNodeKind.
359     // Synthesize the name from the Type subclass (except for QualifiedTypeLoc).
360     if (TL->getTypeLocClass() == TypeLoc::Qualified)
361       OS << "QualifiedTypeLoc";
362     else
363       OS << TL->getType()->getTypeClassName() << "TypeLoc";
364   } else {
365     OS << N.getNodeKind().asStringRef();
366   }
367 }
368 
369 #ifndef NDEBUG
370 std::string printNodeToString(const DynTypedNode &N, const PrintingPolicy &PP) {
371   std::string S;
372   llvm::raw_string_ostream OS(S);
373   printNodeKind(OS, N);
374   OS << " ";
375   return std::move(OS.str());
376 }
377 #endif
378 
379 bool isImplicit(const Stmt *S) {
380   // Some Stmts are implicit and shouldn't be traversed, but there's no
381   // "implicit" attribute on Stmt/Expr.
382   // Unwrap implicit casts first if present (other nodes too?).
383   if (auto *ICE = llvm::dyn_cast<ImplicitCastExpr>(S))
384     S = ICE->getSubExprAsWritten();
385   // Implicit this in a MemberExpr is not filtered out by RecursiveASTVisitor.
386   // It would be nice if RAV handled this (!shouldTraverseImplicitCode()).
387   if (auto *CTI = llvm::dyn_cast<CXXThisExpr>(S))
388     if (CTI->isImplicit())
389       return true;
390   // Refs to operator() and [] are (almost?) always implicit as part of calls.
391   if (auto *DRE = llvm::dyn_cast<DeclRefExpr>(S)) {
392     if (auto *FD = llvm::dyn_cast<FunctionDecl>(DRE->getDecl())) {
393       switch (FD->getOverloadedOperator()) {
394       case OO_Call:
395       case OO_Subscript:
396         return true;
397       default:
398         break;
399       }
400     }
401   }
402   return false;
403 }
404 
405 // We find the selection by visiting written nodes in the AST, looking for nodes
406 // that intersect with the selected character range.
407 //
408 // While traversing, we maintain a parent stack. As nodes pop off the stack,
409 // we decide whether to keep them or not. To be kept, they must either be
410 // selected or contain some nodes that are.
411 //
412 // For simple cases (not inside macros) we prune subtrees that don't intersect.
413 class SelectionVisitor : public RecursiveASTVisitor<SelectionVisitor> {
414 public:
415   // Runs the visitor to gather selected nodes and their ancestors.
416   // If there is any selection, the root (TUDecl) is the first node.
417   static std::deque<Node> collect(ASTContext &AST,
418                                   const syntax::TokenBuffer &Tokens,
419                                   const PrintingPolicy &PP, unsigned Begin,
420                                   unsigned End, FileID File) {
421     SelectionVisitor V(AST, Tokens, PP, Begin, End, File);
422     V.TraverseAST(AST);
423     assert(V.Stack.size() == 1 && "Unpaired push/pop?");
424     assert(V.Stack.top() == &V.Nodes.front());
425     return std::move(V.Nodes);
426   }
427 
428   // We traverse all "well-behaved" nodes the same way:
429   //  - push the node onto the stack
430   //  - traverse its children recursively
431   //  - pop it from the stack
432   //  - hit testing: is intersection(node, selection) - union(children) empty?
433   //  - attach it to the tree if it or any children hit the selection
434   //
435   // Two categories of nodes are not "well-behaved":
436   //  - those without source range information, we don't record those
437   //  - those that can't be stored in DynTypedNode.
438   // We're missing some interesting things like Attr due to the latter.
439   bool TraverseDecl(Decl *X) {
440     if (X && isa<TranslationUnitDecl>(X))
441       return Base::TraverseDecl(X); // Already pushed by constructor.
442     // Base::TraverseDecl will suppress children, but not this node itself.
443     if (X && X->isImplicit())
444       return true;
445     return traverseNode(X, [&] { return Base::TraverseDecl(X); });
446   }
447   bool TraverseTypeLoc(TypeLoc X) {
448     return traverseNode(&X, [&] { return Base::TraverseTypeLoc(X); });
449   }
450   bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc X) {
451     return traverseNode(
452         &X, [&] { return Base::TraverseNestedNameSpecifierLoc(X); });
453   }
454   bool TraverseConstructorInitializer(CXXCtorInitializer *X) {
455     return traverseNode(
456         X, [&] { return Base::TraverseConstructorInitializer(X); });
457   }
458   // Stmt is the same, but this form allows the data recursion optimization.
459   bool dataTraverseStmtPre(Stmt *X) {
460     if (!X || isImplicit(X))
461       return false;
462     auto N = DynTypedNode::create(*X);
463     if (canSafelySkipNode(N))
464       return false;
465     push(std::move(N));
466     if (shouldSkipChildren(X)) {
467       pop();
468       return false;
469     }
470     return true;
471   }
472   bool dataTraverseStmtPost(Stmt *X) {
473     pop();
474     return true;
475   }
476   // QualifiedTypeLoc is handled strangely in RecursiveASTVisitor: the derived
477   // TraverseTypeLoc is not called for the inner UnqualTypeLoc.
478   // This means we'd never see 'int' in 'const int'! Work around that here.
479   // (The reason for the behavior is to avoid traversing the nested Type twice,
480   // but we ignore TraverseType anyway).
481   bool TraverseQualifiedTypeLoc(QualifiedTypeLoc QX) {
482     return traverseNode<TypeLoc>(
483         &QX, [&] { return TraverseTypeLoc(QX.getUnqualifiedLoc()); });
484   }
485   // Uninteresting parts of the AST that don't have locations within them.
486   bool TraverseNestedNameSpecifier(NestedNameSpecifier *) { return true; }
487   bool TraverseType(QualType) { return true; }
488 
489   // The DeclStmt for the loop variable claims to cover the whole range
490   // inside the parens, this causes the range-init expression to not be hit.
491   // Traverse the loop VarDecl instead, which has the right source range.
492   bool TraverseCXXForRangeStmt(CXXForRangeStmt *S) {
493     return traverseNode(S, [&] {
494       return TraverseStmt(S->getInit()) && TraverseDecl(S->getLoopVariable()) &&
495              TraverseStmt(S->getRangeInit()) && TraverseStmt(S->getBody());
496     });
497   }
498   // OpaqueValueExpr blocks traversal, we must explicitly traverse it.
499   bool TraverseOpaqueValueExpr(OpaqueValueExpr *E) {
500     return traverseNode(E, [&] { return TraverseStmt(E->getSourceExpr()); });
501   }
502   // We only want to traverse the *syntactic form* to understand the selection.
503   bool TraversePseudoObjectExpr(PseudoObjectExpr *E) {
504     return traverseNode(E, [&] { return TraverseStmt(E->getSyntacticForm()); });
505   }
506 
507 private:
508   using Base = RecursiveASTVisitor<SelectionVisitor>;
509 
510   SelectionVisitor(ASTContext &AST, const syntax::TokenBuffer &Tokens,
511                    const PrintingPolicy &PP, unsigned SelBegin, unsigned SelEnd,
512                    FileID SelFile)
513       : SM(AST.getSourceManager()), LangOpts(AST.getLangOpts()),
514 #ifndef NDEBUG
515         PrintPolicy(PP),
516 #endif
517         TokenBuf(Tokens), SelChecker(Tokens, SelFile, SelBegin, SelEnd, SM),
518         UnclaimedExpandedTokens(Tokens.expandedTokens()) {
519     // Ensure we have a node for the TU decl, regardless of traversal scope.
520     Nodes.emplace_back();
521     Nodes.back().ASTNode = DynTypedNode::create(*AST.getTranslationUnitDecl());
522     Nodes.back().Parent = nullptr;
523     Nodes.back().Selected = SelectionTree::Unselected;
524     Stack.push(&Nodes.back());
525   }
526 
527   // Generic case of TraverseFoo. Func should be the call to Base::TraverseFoo.
528   // Node is always a pointer so the generic code can handle any null checks.
529   template <typename T, typename Func>
530   bool traverseNode(T *Node, const Func &Body) {
531     if (Node == nullptr)
532       return true;
533     auto N = DynTypedNode::create(*Node);
534     if (canSafelySkipNode(N))
535       return true;
536     push(DynTypedNode::create(*Node));
537     bool Ret = Body();
538     pop();
539     return Ret;
540   }
541 
542   // HIT TESTING
543   //
544   // We do rough hit testing on the way down the tree to avoid traversing
545   // subtrees that don't touch the selection (canSafelySkipNode), but
546   // fine-grained hit-testing is mostly done on the way back up (in pop()).
547   // This means children get to claim parts of the selection first, and parents
548   // are only selected if they own tokens that no child owned.
549   //
550   // Nodes *usually* nest nicely: a child's getSourceRange() lies within the
551   // parent's, and a node (transitively) owns all tokens in its range.
552   //
553   // Exception 1: child range claims tokens that should be owned by the parent.
554   //              e.g. in `void foo(int);`, the FunctionTypeLoc should own
555   //              `void (int)` but the parent FunctionDecl should own `foo`.
556   // To handle this case, certain nodes claim small token ranges *before*
557   // their children are traversed. (see earlySourceRange).
558   //
559   // Exception 2: siblings both claim the same node.
560   //              e.g. `int x, y;` produces two sibling VarDecls.
561   //                    ~~~~~ x
562   //                    ~~~~~~~~ y
563   // Here the first ("leftmost") sibling claims the tokens it wants, and the
564   // other sibling gets what's left. So selecting "int" only includes the left
565   // VarDecl in the selection tree.
566 
567   // An optimization for a common case: nodes outside macro expansions that
568   // don't intersect the selection may be recursively skipped.
569   bool canSafelySkipNode(const DynTypedNode &N) {
570     SourceRange S = N.getSourceRange();
571     if (auto *TL = N.get<TypeLoc>()) {
572       // DeclTypeTypeLoc::getSourceRange() is incomplete, which would lead to
573       // failing
574       // to descend into the child expression.
575       // decltype(2+2);
576       // ~~~~~~~~~~~~~ <-- correct range
577       // ~~~~~~~~      <-- range reported by getSourceRange()
578       // ~~~~~~~~~~~~  <-- range with this hack(i.e, missing closing paren)
579       // FIXME: Alter DecltypeTypeLoc to contain parentheses locations and get
580       // rid of this patch.
581       if (auto DT = TL->getAs<DecltypeTypeLoc>())
582         S.setEnd(DT.getUnderlyingExpr()->getEndLoc());
583     }
584     if (!SelChecker.mayHit(S)) {
585       dlog("{1}skip: {0}", printNodeToString(N, PrintPolicy), indent());
586       dlog("{1}skipped range = {0}", S.printToString(SM), indent(1));
587       return true;
588     }
589     return false;
590   }
591 
592   // There are certain nodes we want to treat as leaves in the SelectionTree,
593   // although they do have children.
594   bool shouldSkipChildren(const Stmt *X) const {
595     // UserDefinedLiteral (e.g. 12_i) has two children (12 and _i).
596     // Unfortunately TokenBuffer sees 12_i as one token and can't split it.
597     // So we treat UserDefinedLiteral as a leaf node, owning the token.
598     return llvm::isa<UserDefinedLiteral>(X);
599   }
600 
601   // Pushes a node onto the ancestor stack. Pairs with pop().
602   // Performs early hit detection for some nodes (on the earlySourceRange).
603   void push(DynTypedNode Node) {
604     SourceRange Early = earlySourceRange(Node);
605     dlog("{1}push: {0}", printNodeToString(Node, PrintPolicy), indent());
606     Nodes.emplace_back();
607     Nodes.back().ASTNode = std::move(Node);
608     Nodes.back().Parent = Stack.top();
609     Nodes.back().Selected = NoTokens;
610     Stack.push(&Nodes.back());
611     claimRange(Early, Nodes.back().Selected);
612   }
613 
614   // Pops a node off the ancestor stack, and finalizes it. Pairs with push().
615   // Performs primary hit detection.
616   void pop() {
617     Node &N = *Stack.top();
618     dlog("{1}pop: {0}", printNodeToString(N.ASTNode, PrintPolicy), indent(-1));
619     claimRange(N.ASTNode.getSourceRange(), N.Selected);
620     if (N.Selected == NoTokens)
621       N.Selected = SelectionTree::Unselected;
622     if (N.Selected || !N.Children.empty()) {
623       // Attach to the tree.
624       N.Parent->Children.push_back(&N);
625     } else {
626       // Neither N any children are selected, it doesn't belong in the tree.
627       assert(&N == &Nodes.back());
628       Nodes.pop_back();
629     }
630     Stack.pop();
631   }
632 
633   // Returns the range of tokens that this node will claim directly, and
634   // is not available to the node's children.
635   // Usually empty, but sometimes children cover tokens but shouldn't own them.
636   SourceRange earlySourceRange(const DynTypedNode &N) {
637     if (const Decl *D = N.get<Decl>()) {
638       // We want constructor name to be claimed by TypeLoc not the constructor
639       // itself. Similar for deduction guides, we rather want to select the
640       // underlying TypeLoc.
641       // FIXME: Unfortunately this doesn't work, even though RecursiveASTVisitor
642       // traverses the underlying TypeLoc inside DeclarationName, it is null for
643       // constructors.
644       if (isa<CXXConstructorDecl>(D) || isa<CXXDeductionGuideDecl>(D))
645         return SourceRange();
646       // This will capture Field, Function, MSProperty, NonTypeTemplateParm and
647       // VarDecls. We want the name in the declarator to be claimed by the decl
648       // and not by any children. For example:
649       // void [[foo]]();
650       // int (*[[s]])();
651       // struct X { int [[hash]] [32]; [[operator]] int();}
652       if (const auto *DD = llvm::dyn_cast<DeclaratorDecl>(D))
653         return DD->getLocation();
654     } else if (const auto *CCI = N.get<CXXCtorInitializer>()) {
655       // : [[b_]](42)
656       return CCI->getMemberLocation();
657     }
658     return SourceRange();
659   }
660 
661   // Perform hit-testing of a complete Node against the selection.
662   // This runs for every node in the AST, and must be fast in common cases.
663   // This is usually called from pop(), so we can take children into account.
664   // The existing state of Result is relevant (early/late claims can interact).
665   void claimRange(SourceRange S, SelectionTree::Selection &Result) {
666     for (const auto &ClaimedRange :
667          UnclaimedExpandedTokens.erase(TokenBuf.expandedTokens(S)))
668       update(Result, SelChecker.test(ClaimedRange));
669 
670     if (Result && Result != NoTokens)
671       dlog("{1}hit selection: {0}", S.printToString(SM), indent());
672   }
673 
674   std::string indent(int Offset = 0) {
675     // Cast for signed arithmetic.
676     int Amount = int(Stack.size()) + Offset;
677     assert(Amount >= 0);
678     return std::string(Amount, ' ');
679   }
680 
681   SourceManager &SM;
682   const LangOptions &LangOpts;
683 #ifndef NDEBUG
684   const PrintingPolicy &PrintPolicy;
685 #endif
686   const syntax::TokenBuffer &TokenBuf;
687   std::stack<Node *> Stack;
688   SelectionTester SelChecker;
689   IntervalSet<syntax::Token> UnclaimedExpandedTokens;
690   std::deque<Node> Nodes; // Stable pointers as we add more nodes.
691 };
692 
693 } // namespace
694 
695 void SelectionTree::print(llvm::raw_ostream &OS, const SelectionTree::Node &N,
696                           int Indent) const {
697   if (N.Selected)
698     OS.indent(Indent - 1) << (N.Selected == SelectionTree::Complete ? '*'
699                                                                     : '.');
700   else
701     OS.indent(Indent);
702   printNodeKind(OS, N.ASTNode);
703   OS << ' ';
704   N.ASTNode.print(OS, PrintPolicy);
705   OS << "\n";
706   for (const Node *Child : N.Children)
707     print(OS, *Child, Indent + 2);
708 }
709 
710 std::string SelectionTree::Node::kind() const {
711   std::string S;
712   llvm::raw_string_ostream OS(S);
713   printNodeKind(OS, ASTNode);
714   return std::move(OS.str());
715 }
716 
717 // Decide which selections emulate a "point" query in between characters.
718 // If it's ambiguous (the neighboring characters are selectable tokens), returns
719 // both possibilities in preference order.
720 // Always returns at least one range - if no tokens touched, and empty range.
721 static llvm::SmallVector<std::pair<unsigned, unsigned>, 2>
722 pointBounds(unsigned Offset, const syntax::TokenBuffer &Tokens) {
723   const auto &SM = Tokens.sourceManager();
724   SourceLocation Loc = SM.getComposedLoc(SM.getMainFileID(), Offset);
725   llvm::SmallVector<std::pair<unsigned, unsigned>, 2> Result;
726   // Prefer right token over left.
727   for (const syntax::Token &Tok :
728        llvm::reverse(spelledTokensTouching(Loc, Tokens))) {
729     if (shouldIgnore(Tok))
730       continue;
731     unsigned Offset = Tokens.sourceManager().getFileOffset(Tok.location());
732     Result.emplace_back(Offset, Offset + Tok.length());
733   }
734   if (Result.empty())
735     Result.emplace_back(Offset, Offset);
736   return Result;
737 }
738 
739 bool SelectionTree::createEach(ASTContext &AST,
740                                const syntax::TokenBuffer &Tokens,
741                                unsigned Begin, unsigned End,
742                                llvm::function_ref<bool(SelectionTree)> Func) {
743   if (Begin != End)
744     return Func(SelectionTree(AST, Tokens, Begin, End));
745   for (std::pair<unsigned, unsigned> Bounds : pointBounds(Begin, Tokens))
746     if (Func(SelectionTree(AST, Tokens, Bounds.first, Bounds.second)))
747       return true;
748   return false;
749 }
750 
751 SelectionTree SelectionTree::createRight(ASTContext &AST,
752                                          const syntax::TokenBuffer &Tokens,
753                                          unsigned int Begin, unsigned int End) {
754   llvm::Optional<SelectionTree> Result;
755   createEach(AST, Tokens, Begin, End, [&](SelectionTree T) {
756     Result = std::move(T);
757     return true;
758   });
759   return std::move(*Result);
760 }
761 
762 SelectionTree::SelectionTree(ASTContext &AST, const syntax::TokenBuffer &Tokens,
763                              unsigned Begin, unsigned End)
764     : PrintPolicy(AST.getLangOpts()) {
765   // No fundamental reason the selection needs to be in the main file,
766   // but that's all clangd has needed so far.
767   const SourceManager &SM = AST.getSourceManager();
768   FileID FID = SM.getMainFileID();
769   PrintPolicy.TerseOutput = true;
770   PrintPolicy.IncludeNewlines = false;
771 
772   dlog("Computing selection for {0}",
773        SourceRange(SM.getComposedLoc(FID, Begin), SM.getComposedLoc(FID, End))
774            .printToString(SM));
775   Nodes = SelectionVisitor::collect(AST, Tokens, PrintPolicy, Begin, End, FID);
776   Root = Nodes.empty() ? nullptr : &Nodes.front();
777   dlog("Built selection tree\n{0}", *this);
778 }
779 
780 const Node *SelectionTree::commonAncestor() const {
781   const Node *Ancestor = Root;
782   while (Ancestor->Children.size() == 1 && !Ancestor->Selected)
783     Ancestor = Ancestor->Children.front();
784   // Returning nullptr here is a bit unprincipled, but it makes the API safer:
785   // the TranslationUnitDecl contains all of the preamble, so traversing it is a
786   // performance cliff. Callers can check for null and use root() if they want.
787   return Ancestor != Root ? Ancestor : nullptr;
788 }
789 
790 const DeclContext &SelectionTree::Node::getDeclContext() const {
791   for (const Node *CurrentNode = this; CurrentNode != nullptr;
792        CurrentNode = CurrentNode->Parent) {
793     if (const Decl *Current = CurrentNode->ASTNode.get<Decl>()) {
794       if (CurrentNode != this)
795         if (auto *DC = dyn_cast<DeclContext>(Current))
796           return *DC;
797       return *Current->getDeclContext();
798     }
799   }
800   llvm_unreachable("A tree must always be rooted at TranslationUnitDecl.");
801 }
802 
803 const SelectionTree::Node &SelectionTree::Node::ignoreImplicit() const {
804   if (Children.size() == 1 &&
805       Children.front()->ASTNode.getSourceRange() == ASTNode.getSourceRange())
806     return Children.front()->ignoreImplicit();
807   return *this;
808 }
809 
810 const SelectionTree::Node &SelectionTree::Node::outerImplicit() const {
811   if (Parent && Parent->ASTNode.getSourceRange() == ASTNode.getSourceRange())
812     return Parent->outerImplicit();
813   return *this;
814 }
815 
816 } // namespace clangd
817 } // namespace clang
818