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 "AST.h"
11 #include "support/Logger.h"
12 #include "support/Trace.h"
13 #include "clang/AST/ASTTypeTraits.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/Expr.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/AST/PrettyPrinter.h"
19 #include "clang/AST/RecursiveASTVisitor.h"
20 #include "clang/AST/TypeLoc.h"
21 #include "clang/Basic/OperatorKinds.h"
22 #include "clang/Basic/SourceLocation.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "clang/Basic/TokenKinds.h"
25 #include "clang/Lex/Lexer.h"
26 #include "clang/Tooling/Syntax/Tokens.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <algorithm>
33 #include <string>
34 
35 namespace clang {
36 namespace clangd {
37 namespace {
38 using Node = SelectionTree::Node;
39 
40 // Measure the fraction of selections that were enabled by recovery AST.
41 void recordMetrics(const SelectionTree &S, const LangOptions &Lang) {
42   if (!trace::enabled())
43     return;
44   const char *LanguageLabel = Lang.CPlusPlus ? "C++" : Lang.ObjC ? "ObjC" : "C";
45   static constexpr trace::Metric SelectionUsedRecovery(
46       "selection_recovery", trace::Metric::Distribution, "language");
47   static constexpr trace::Metric RecoveryType(
48       "selection_recovery_type", trace::Metric::Distribution, "language");
49   const auto *Common = S.commonAncestor();
50   for (const auto *N = Common; N; N = N->Parent) {
51     if (const auto *RE = N->ASTNode.get<RecoveryExpr>()) {
52       SelectionUsedRecovery.record(1, LanguageLabel); // used recovery ast.
53       RecoveryType.record(RE->isTypeDependent() ? 0 : 1, LanguageLabel);
54       return;
55     }
56   }
57   if (Common)
58     SelectionUsedRecovery.record(0, LanguageLabel); // unused.
59 }
60 
61 // Return the range covering a node and all its children.
62 SourceRange getSourceRange(const DynTypedNode &N) {
63   // MemberExprs to implicitly access anonymous fields should not claim any
64   // tokens for themselves. Given:
65   //   struct A { struct { int b; }; };
66   // The clang AST reports the following nodes for an access to b:
67   //   A().b;
68   //   [----] MemberExpr, base = A().<anonymous>, member = b
69   //   [----] MemberExpr: base = A(), member = <anonymous>
70   //   [-]    CXXConstructExpr
71   // For our purposes, we don't want the second MemberExpr to own any tokens,
72   // so we reduce its range to match the CXXConstructExpr.
73   // (It's not clear that changing the clang AST would be correct in general).
74   if (const auto *ME = N.get<MemberExpr>()) {
75     if (!ME->getMemberDecl()->getDeclName())
76       return ME->getBase()
77                  ? getSourceRange(DynTypedNode::create(*ME->getBase()))
78                  : SourceRange();
79   }
80   return N.getSourceRange();
81 }
82 
83 // An IntervalSet maintains a set of disjoint subranges of an array.
84 //
85 // Initially, it contains the entire array.
86 //           [-----------------------------------------------------------]
87 //
88 // When a range is erased(), it will typically split the array in two.
89 //  Claim:                     [--------------------]
90 //  after:   [----------------]                      [-------------------]
91 //
92 // erase() returns the segments actually erased. Given the state above:
93 //  Claim:          [---------------------------------------]
94 //  Out:            [---------]                      [------]
95 //  After:   [-----]                                         [-----------]
96 //
97 // It is used to track (expanded) tokens not yet associated with an AST node.
98 // On traversing an AST node, its token range is erased from the unclaimed set.
99 // The tokens actually removed are associated with that node, and hit-tested
100 // against the selection to determine whether the node is selected.
101 template <typename T> class IntervalSet {
102 public:
103   IntervalSet(llvm::ArrayRef<T> Range) { UnclaimedRanges.insert(Range); }
104 
105   // Removes the elements of Claim from the set, modifying or removing ranges
106   // that overlap it.
107   // Returns the continuous subranges of Claim that were actually removed.
108   llvm::SmallVector<llvm::ArrayRef<T>> erase(llvm::ArrayRef<T> Claim) {
109     llvm::SmallVector<llvm::ArrayRef<T>> Out;
110     if (Claim.empty())
111       return Out;
112 
113     // General case:
114     // Claim:                   [-----------------]
115     // UnclaimedRanges: [-A-] [-B-] [-C-] [-D-] [-E-] [-F-] [-G-]
116     // Overlap:               ^first                  ^second
117     // Ranges C and D are fully included. Ranges B and E must be trimmed.
118     auto Overlap = std::make_pair(
119         UnclaimedRanges.lower_bound({Claim.begin(), Claim.begin()}), // C
120         UnclaimedRanges.lower_bound({Claim.end(), Claim.end()}));    // F
121     // Rewind to cover B.
122     if (Overlap.first != UnclaimedRanges.begin()) {
123       --Overlap.first;
124       // ...unless B isn't selected at all.
125       if (Overlap.first->end() <= Claim.begin())
126         ++Overlap.first;
127     }
128     if (Overlap.first == Overlap.second)
129       return Out;
130 
131     // First, copy all overlapping ranges into the output.
132     auto OutFirst = Out.insert(Out.end(), Overlap.first, Overlap.second);
133     // If any of the overlapping ranges were sliced by the claim, split them:
134     //  - restrict the returned range to the claimed part
135     //  - save the unclaimed part so it can be reinserted
136     llvm::ArrayRef<T> RemainingHead, RemainingTail;
137     if (Claim.begin() > OutFirst->begin()) {
138       RemainingHead = {OutFirst->begin(), Claim.begin()};
139       *OutFirst = {Claim.begin(), OutFirst->end()};
140     }
141     if (Claim.end() < Out.back().end()) {
142       RemainingTail = {Claim.end(), Out.back().end()};
143       Out.back() = {Out.back().begin(), Claim.end()};
144     }
145 
146     // Erase all the overlapping ranges (invalidating all iterators).
147     UnclaimedRanges.erase(Overlap.first, Overlap.second);
148     // Reinsert ranges that were merely trimmed.
149     if (!RemainingHead.empty())
150       UnclaimedRanges.insert(RemainingHead);
151     if (!RemainingTail.empty())
152       UnclaimedRanges.insert(RemainingTail);
153 
154     return Out;
155   }
156 
157 private:
158   using TokenRange = llvm::ArrayRef<T>;
159   struct RangeLess {
160     bool operator()(llvm::ArrayRef<T> L, llvm::ArrayRef<T> R) const {
161       return L.begin() < R.begin();
162     }
163   };
164 
165   // Disjoint sorted unclaimed ranges of expanded tokens.
166   std::set<llvm::ArrayRef<T>, RangeLess> UnclaimedRanges;
167 };
168 
169 // Sentinel value for the selectedness of a node where we've seen no tokens yet.
170 // This resolves to Unselected if no tokens are ever seen.
171 // But Unselected + Complete -> Partial, while NoTokens + Complete --> Complete.
172 // This value is never exposed publicly.
173 constexpr SelectionTree::Selection NoTokens =
174     static_cast<SelectionTree::Selection>(
175         static_cast<unsigned char>(SelectionTree::Complete + 1));
176 
177 // Nodes start with NoTokens, and then use this function to aggregate the
178 // selectedness as more tokens are found.
179 void update(SelectionTree::Selection &Result, SelectionTree::Selection New) {
180   if (New == NoTokens)
181     return;
182   if (Result == NoTokens)
183     Result = New;
184   else if (Result != New)
185     // Can only be completely selected (or unselected) if all tokens are.
186     Result = SelectionTree::Partial;
187 }
188 
189 // As well as comments, don't count semicolons as real tokens.
190 // They're not properly claimed as expr-statement is missing from the AST.
191 bool shouldIgnore(const syntax::Token &Tok) {
192   switch (Tok.kind()) {
193     // Even "attached" comments are not considered part of a node's range.
194     case tok::comment:
195     // The AST doesn't directly store locations for terminating semicolons.
196     case tok::semi:
197     // We don't have locations for cvr-qualifiers: see QualifiedTypeLoc.
198     case tok::kw_const:
199     case tok::kw_volatile:
200     case tok::kw_restrict:
201       return true;
202     default:
203       return false;
204   }
205 }
206 
207 // Determine whether 'Target' is the first expansion of the macro
208 // argument whose top-level spelling location is 'SpellingLoc'.
209 bool isFirstExpansion(FileID Target, SourceLocation SpellingLoc,
210                       const SourceManager &SM) {
211   SourceLocation Prev = SpellingLoc;
212   while (true) {
213     // If the arg is expanded multiple times, getMacroArgExpandedLocation()
214     // returns the first expansion.
215     SourceLocation Next = SM.getMacroArgExpandedLocation(Prev);
216     // So if we reach the target, target is the first-expansion of the
217     // first-expansion ...
218     if (SM.getFileID(Next) == Target)
219       return true;
220 
221     // Otherwise, if the FileID stops changing, we've reached the innermost
222     // macro expansion, and Target was on a different branch.
223     if (SM.getFileID(Next) == SM.getFileID(Prev))
224       return false;
225 
226     Prev = Next;
227   }
228   return false;
229 }
230 
231 // SelectionTester can determine whether a range of tokens from the PP-expanded
232 // stream (corresponding to an AST node) is considered selected.
233 //
234 // When the tokens result from macro expansions, the appropriate tokens in the
235 // main file are examined (macro invocation or args). Similarly for #includes.
236 // However, only the first expansion of a given spelled token is considered
237 // selected.
238 //
239 // It tests each token in the range (not just the endpoints) as contiguous
240 // expanded tokens may not have contiguous spellings (with macros).
241 //
242 // Non-token text, and tokens not modeled in the AST (comments, semicolons)
243 // are ignored when determining selectedness.
244 class SelectionTester {
245 public:
246   // The selection is offsets [SelBegin, SelEnd) in SelFile.
247   SelectionTester(const syntax::TokenBuffer &Buf, FileID SelFile,
248                   unsigned SelBegin, unsigned SelEnd, const SourceManager &SM)
249       : SelFile(SelFile), SelFileBounds(SM.getLocForStartOfFile(SelFile),
250                                         SM.getLocForEndOfFile(SelFile)),
251         SM(SM) {
252     // Find all tokens (partially) selected in the file.
253     auto AllSpelledTokens = Buf.spelledTokens(SelFile);
254     const syntax::Token *SelFirst =
255         llvm::partition_point(AllSpelledTokens, [&](const syntax::Token &Tok) {
256           return SM.getFileOffset(Tok.endLocation()) <= SelBegin;
257         });
258     const syntax::Token *SelLimit = std::partition_point(
259         SelFirst, AllSpelledTokens.end(), [&](const syntax::Token &Tok) {
260           return SM.getFileOffset(Tok.location()) < SelEnd;
261         });
262     auto Sel = llvm::makeArrayRef(SelFirst, SelLimit);
263     // Find which of these are preprocessed to nothing and should be ignored.
264     llvm::BitVector PPIgnored(Sel.size(), false);
265     for (const syntax::TokenBuffer::Expansion &X :
266          Buf.expansionsOverlapping(Sel)) {
267       if (X.Expanded.empty()) {
268         for (const syntax::Token &Tok : X.Spelled) {
269           if (&Tok >= SelFirst && &Tok < SelLimit)
270             PPIgnored[&Tok - SelFirst] = true;
271         }
272       }
273     }
274     // Precompute selectedness and offset for selected spelled tokens.
275     for (unsigned I = 0; I < Sel.size(); ++I) {
276       if (shouldIgnore(Sel[I]) || PPIgnored[I])
277         continue;
278       SelectedSpelled.emplace_back();
279       Tok &S = SelectedSpelled.back();
280       S.Offset = SM.getFileOffset(Sel[I].location());
281       if (S.Offset >= SelBegin && S.Offset + Sel[I].length() <= SelEnd)
282         S.Selected = SelectionTree::Complete;
283       else
284         S.Selected = SelectionTree::Partial;
285     }
286     MaybeSelectedExpanded = computeMaybeSelectedExpandedTokens(Buf);
287   }
288 
289   // Test whether a consecutive range of tokens is selected.
290   // The tokens are taken from the expanded token stream.
291   SelectionTree::Selection
292   test(llvm::ArrayRef<syntax::Token> ExpandedTokens) const {
293     if (ExpandedTokens.empty())
294       return NoTokens;
295     if (SelectedSpelled.empty())
296       return SelectionTree::Unselected;
297     // Cheap (pointer) check whether any of the tokens could touch selection.
298     // In most cases, the node's overall source range touches ExpandedTokens,
299     // or we would have failed mayHit(). However now we're only considering
300     // the *unclaimed* spans of expanded tokens.
301     // This is a significant performance improvement when a lot of nodes
302     // surround the selection, including when generated by macros.
303     if (MaybeSelectedExpanded.empty() ||
304         &ExpandedTokens.front() > &MaybeSelectedExpanded.back() ||
305         &ExpandedTokens.back() < &MaybeSelectedExpanded.front()) {
306       return SelectionTree::Unselected;
307     }
308 
309     // The eof token is used as a sentinel.
310     // In general, source range from an AST node should not claim the eof token,
311     // but it could occur for unmatched-bracket cases.
312     // FIXME: fix it in TokenBuffer, expandedTokens(SourceRange) should not
313     // return the eof token.
314     if (ExpandedTokens.back().kind() == tok::eof)
315       ExpandedTokens = ExpandedTokens.drop_back();
316 
317     SelectionTree::Selection Result = NoTokens;
318     while (!ExpandedTokens.empty()) {
319       // Take consecutive tokens from the same context together for efficiency.
320       SourceLocation Start = ExpandedTokens.front().location();
321       FileID FID = SM.getFileID(Start);
322       // Comparing SourceLocations against bounds is cheaper than getFileID().
323       SourceLocation Limit = SM.getComposedLoc(FID, SM.getFileIDSize(FID));
324       auto Batch = ExpandedTokens.take_while([&](const syntax::Token &T) {
325         return T.location() >= Start && T.location() < Limit;
326       });
327       assert(!Batch.empty());
328       ExpandedTokens = ExpandedTokens.drop_front(Batch.size());
329 
330       update(Result, testChunk(FID, Batch));
331     }
332     return Result;
333   }
334 
335   // Cheap check whether any of the tokens in R might be selected.
336   // If it returns false, test() will return NoTokens or Unselected.
337   // If it returns true, test() may return any value.
338   bool mayHit(SourceRange R) const {
339     if (SelectedSpelled.empty() || MaybeSelectedExpanded.empty())
340       return false;
341     // If the node starts after the selection ends, it is not selected.
342     // Tokens a macro location might claim are >= its expansion start.
343     // So if the expansion start > last selected token, we can prune it.
344     // (This is particularly helpful for GTest's TEST macro).
345     if (auto B = offsetInSelFile(getExpansionStart(R.getBegin())))
346       if (*B > SelectedSpelled.back().Offset)
347         return false;
348     // If the node ends before the selection begins, it is not selected.
349     SourceLocation EndLoc = R.getEnd();
350     while (EndLoc.isMacroID())
351       EndLoc = SM.getImmediateExpansionRange(EndLoc).getEnd();
352     // In the rare case that the expansion range is a char range, EndLoc is
353     // ~one token too far to the right. We may fail to prune, that's OK.
354     if (auto E = offsetInSelFile(EndLoc))
355       if (*E < SelectedSpelled.front().Offset)
356         return false;
357     return true;
358   }
359 
360 private:
361   // Plausible expanded tokens that might be affected by the selection.
362   // This is an overestimate, it may contain tokens that are not selected.
363   // The point is to allow cheap pruning in test()
364   llvm::ArrayRef<syntax::Token>
365   computeMaybeSelectedExpandedTokens(const syntax::TokenBuffer &Toks) {
366     if (SelectedSpelled.empty())
367       return {};
368 
369     auto LastAffectedToken = [&](SourceLocation Loc) {
370       auto Offset = offsetInSelFile(Loc);
371       while (Loc.isValid() && !Offset) {
372         Loc = Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getEnd()
373                               : SM.getIncludeLoc(SM.getFileID(Loc));
374         Offset = offsetInSelFile(Loc);
375       }
376       return Offset;
377     };
378     auto FirstAffectedToken = [&](SourceLocation Loc) {
379       auto Offset = offsetInSelFile(Loc);
380       while (Loc.isValid() && !Offset) {
381         Loc = Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
382                               : SM.getIncludeLoc(SM.getFileID(Loc));
383         Offset = offsetInSelFile(Loc);
384       }
385       return Offset;
386     };
387 
388     const syntax::Token *Start = llvm::partition_point(
389         Toks.expandedTokens(),
390         [&, First = SelectedSpelled.front().Offset](const syntax::Token &Tok) {
391           if (Tok.kind() == tok::eof)
392             return false;
393           // Implausible if upperbound(Tok) < First.
394           if (auto Offset = LastAffectedToken(Tok.location()))
395             return *Offset < First;
396           // A prefix of the expanded tokens may be from an an implicit
397           // inclusion (e.g. preamble patch, or command-line -include).
398           return true;
399         });
400 
401     bool EndInvalid = false;
402     const syntax::Token *End = std::partition_point(
403         Start, Toks.expandedTokens().end(),
404         [&, Last = SelectedSpelled.back().Offset](const syntax::Token &Tok) {
405           if (Tok.kind() == tok::eof)
406             return false;
407           // Plausible if lowerbound(Tok) <= Last.
408           if (auto Offset = FirstAffectedToken(Tok.location()))
409             return *Offset <= Last;
410           // Shouldn't happen: once we've seen tokens traceable to the main
411           // file, there shouldn't be any more implicit inclusions.
412           assert(false && "Expanded token could not be resolved to main file!");
413           EndInvalid = true;
414           return true; // conservatively assume this token can overlap
415         });
416     if (EndInvalid)
417       End = Toks.expandedTokens().end();
418 
419     return llvm::makeArrayRef(Start, End);
420   }
421 
422   // Hit-test a consecutive range of tokens from a single file ID.
423   SelectionTree::Selection
424   testChunk(FileID FID, llvm::ArrayRef<syntax::Token> Batch) const {
425     assert(!Batch.empty());
426     SourceLocation StartLoc = Batch.front().location();
427     // There are several possible categories of FileID depending on how the
428     // preprocessor was used to generate these tokens:
429     //   main file, #included file, macro args, macro bodies.
430     // We need to identify the main-file tokens that represent Batch, and
431     // determine whether we want to exclusively claim them. Regular tokens
432     // represent one AST construct, but a macro invocation can represent many.
433 
434     // Handle tokens written directly in the main file.
435     if (FID == SelFile) {
436       return testTokenRange(*offsetInSelFile(Batch.front().location()),
437                             *offsetInSelFile(Batch.back().location()));
438     }
439 
440     // Handle tokens in another file #included into the main file.
441     // Check if the #include is selected, but don't claim it exclusively.
442     if (StartLoc.isFileID()) {
443       for (SourceLocation Loc = Batch.front().location(); Loc.isValid();
444            Loc = SM.getIncludeLoc(SM.getFileID(Loc))) {
445         if (auto Offset = offsetInSelFile(Loc))
446           // FIXME: use whole #include directive, not just the filename string.
447           return testToken(*Offset);
448       }
449       return NoTokens;
450     }
451 
452     assert(StartLoc.isMacroID());
453     // Handle tokens that were passed as a macro argument.
454     SourceLocation ArgStart = SM.getTopMacroCallerLoc(StartLoc);
455     if (auto ArgOffset = offsetInSelFile(ArgStart)) {
456       if (isFirstExpansion(FID, ArgStart, SM)) {
457         SourceLocation ArgEnd =
458             SM.getTopMacroCallerLoc(Batch.back().location());
459         return testTokenRange(*ArgOffset, *offsetInSelFile(ArgEnd));
460       } else { // NOLINT(llvm-else-after-return)
461         /* fall through and treat as part of the macro body */
462       }
463     }
464 
465     // Handle tokens produced by non-argument macro expansion.
466     // Check if the macro name is selected, don't claim it exclusively.
467     if (auto ExpansionOffset = offsetInSelFile(getExpansionStart(StartLoc)))
468       // FIXME: also check ( and ) for function-like macros?
469       return testToken(*ExpansionOffset);
470     return NoTokens;
471   }
472 
473   // Is the closed token range [Begin, End] selected?
474   SelectionTree::Selection testTokenRange(unsigned Begin, unsigned End) const {
475     assert(Begin <= End);
476     // Outside the selection entirely?
477     if (End < SelectedSpelled.front().Offset ||
478         Begin > SelectedSpelled.back().Offset)
479       return SelectionTree::Unselected;
480 
481     // Compute range of tokens.
482     auto B = llvm::partition_point(
483         SelectedSpelled, [&](const Tok &T) { return T.Offset < Begin; });
484     auto E = std::partition_point(B, SelectedSpelled.end(), [&](const Tok &T) {
485       return T.Offset <= End;
486     });
487 
488     // Aggregate selectedness of tokens in range.
489     bool ExtendsOutsideSelection = Begin < SelectedSpelled.front().Offset ||
490                                    End > SelectedSpelled.back().Offset;
491     SelectionTree::Selection Result =
492         ExtendsOutsideSelection ? SelectionTree::Unselected : NoTokens;
493     for (auto It = B; It != E; ++It)
494       update(Result, It->Selected);
495     return Result;
496   }
497 
498   // Is the token at `Offset` selected?
499   SelectionTree::Selection testToken(unsigned Offset) const {
500     // Outside the selection entirely?
501     if (Offset < SelectedSpelled.front().Offset ||
502         Offset > SelectedSpelled.back().Offset)
503       return SelectionTree::Unselected;
504     // Find the token, if it exists.
505     auto It = llvm::partition_point(
506         SelectedSpelled, [&](const Tok &T) { return T.Offset < Offset; });
507     if (It != SelectedSpelled.end() && It->Offset == Offset)
508       return It->Selected;
509     return NoTokens;
510   }
511 
512   // Decomposes Loc and returns the offset if the file ID is SelFile.
513   llvm::Optional<unsigned> offsetInSelFile(SourceLocation Loc) const {
514     // Decoding Loc with SM.getDecomposedLoc is relatively expensive.
515     // But SourceLocations for a file are numerically contiguous, so we
516     // can use cheap integer operations instead.
517     if (Loc < SelFileBounds.getBegin() || Loc >= SelFileBounds.getEnd())
518       return llvm::None;
519     // FIXME: subtracting getRawEncoding() is dubious, move this logic into SM.
520     return Loc.getRawEncoding() - SelFileBounds.getBegin().getRawEncoding();
521   }
522 
523   SourceLocation getExpansionStart(SourceLocation Loc) const {
524     while (Loc.isMacroID())
525       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
526     return Loc;
527   }
528 
529   struct Tok {
530     unsigned Offset;
531     SelectionTree::Selection Selected;
532   };
533   std::vector<Tok> SelectedSpelled;
534   llvm::ArrayRef<syntax::Token> MaybeSelectedExpanded;
535   FileID SelFile;
536   SourceRange SelFileBounds;
537   const SourceManager &SM;
538 };
539 
540 // Show the type of a node for debugging.
541 void printNodeKind(llvm::raw_ostream &OS, const DynTypedNode &N) {
542   if (const TypeLoc *TL = N.get<TypeLoc>()) {
543     // TypeLoc is a hierarchy, but has only a single ASTNodeKind.
544     // Synthesize the name from the Type subclass (except for QualifiedTypeLoc).
545     if (TL->getTypeLocClass() == TypeLoc::Qualified)
546       OS << "QualifiedTypeLoc";
547     else
548       OS << TL->getType()->getTypeClassName() << "TypeLoc";
549   } else {
550     OS << N.getNodeKind().asStringRef();
551   }
552 }
553 
554 #ifndef NDEBUG
555 std::string printNodeToString(const DynTypedNode &N, const PrintingPolicy &PP) {
556   std::string S;
557   llvm::raw_string_ostream OS(S);
558   printNodeKind(OS, N);
559   return std::move(OS.str());
560 }
561 #endif
562 
563 bool isImplicit(const Stmt *S) {
564   // Some Stmts are implicit and shouldn't be traversed, but there's no
565   // "implicit" attribute on Stmt/Expr.
566   // Unwrap implicit casts first if present (other nodes too?).
567   if (auto *ICE = llvm::dyn_cast<ImplicitCastExpr>(S))
568     S = ICE->getSubExprAsWritten();
569   // Implicit this in a MemberExpr is not filtered out by RecursiveASTVisitor.
570   // It would be nice if RAV handled this (!shouldTraverseImplicitCode()).
571   if (auto *CTI = llvm::dyn_cast<CXXThisExpr>(S))
572     if (CTI->isImplicit())
573       return true;
574   // Make sure implicit access of anonymous structs don't end up owning tokens.
575   if (auto *ME = llvm::dyn_cast<MemberExpr>(S)) {
576     if (auto *FD = llvm::dyn_cast<FieldDecl>(ME->getMemberDecl()))
577       if (FD->isAnonymousStructOrUnion())
578         // If Base is an implicit CXXThis, then the whole MemberExpr has no
579         // tokens. If it's a normal e.g. DeclRef, we treat the MemberExpr like
580         // an implicit cast.
581         return isImplicit(ME->getBase());
582   }
583   // Refs to operator() and [] are (almost?) always implicit as part of calls.
584   if (auto *DRE = llvm::dyn_cast<DeclRefExpr>(S)) {
585     if (auto *FD = llvm::dyn_cast<FunctionDecl>(DRE->getDecl())) {
586       switch (FD->getOverloadedOperator()) {
587       case OO_Call:
588       case OO_Subscript:
589         return true;
590       default:
591         break;
592       }
593     }
594   }
595   return false;
596 }
597 
598 // We find the selection by visiting written nodes in the AST, looking for nodes
599 // that intersect with the selected character range.
600 //
601 // While traversing, we maintain a parent stack. As nodes pop off the stack,
602 // we decide whether to keep them or not. To be kept, they must either be
603 // selected or contain some nodes that are.
604 //
605 // For simple cases (not inside macros) we prune subtrees that don't intersect.
606 class SelectionVisitor : public RecursiveASTVisitor<SelectionVisitor> {
607 public:
608   // Runs the visitor to gather selected nodes and their ancestors.
609   // If there is any selection, the root (TUDecl) is the first node.
610   static std::deque<Node> collect(ASTContext &AST,
611                                   const syntax::TokenBuffer &Tokens,
612                                   const PrintingPolicy &PP, unsigned Begin,
613                                   unsigned End, FileID File) {
614     SelectionVisitor V(AST, Tokens, PP, Begin, End, File);
615     V.TraverseAST(AST);
616     assert(V.Stack.size() == 1 && "Unpaired push/pop?");
617     assert(V.Stack.top() == &V.Nodes.front());
618     return std::move(V.Nodes);
619   }
620 
621   // We traverse all "well-behaved" nodes the same way:
622   //  - push the node onto the stack
623   //  - traverse its children recursively
624   //  - pop it from the stack
625   //  - hit testing: is intersection(node, selection) - union(children) empty?
626   //  - attach it to the tree if it or any children hit the selection
627   //
628   // Two categories of nodes are not "well-behaved":
629   //  - those without source range information, we don't record those
630   //  - those that can't be stored in DynTypedNode.
631   bool TraverseDecl(Decl *X) {
632     if (llvm::isa_and_nonnull<TranslationUnitDecl>(X))
633       return Base::TraverseDecl(X); // Already pushed by constructor.
634     // Base::TraverseDecl will suppress children, but not this node itself.
635     if (X && X->isImplicit())
636       return true;
637     return traverseNode(X, [&] { return Base::TraverseDecl(X); });
638   }
639   bool TraverseTypeLoc(TypeLoc X) {
640     return traverseNode(&X, [&] { return Base::TraverseTypeLoc(X); });
641   }
642   bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &X) {
643     return traverseNode(&X,
644                         [&] { return Base::TraverseTemplateArgumentLoc(X); });
645   }
646   bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc X) {
647     return traverseNode(
648         &X, [&] { return Base::TraverseNestedNameSpecifierLoc(X); });
649   }
650   bool TraverseConstructorInitializer(CXXCtorInitializer *X) {
651     return traverseNode(
652         X, [&] { return Base::TraverseConstructorInitializer(X); });
653   }
654   bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &X) {
655     return traverseNode(&X, [&] { return Base::TraverseCXXBaseSpecifier(X); });
656   }
657   bool TraverseAttr(Attr *X) {
658     return traverseNode(X, [&] { return Base::TraverseAttr(X); });
659   }
660   // Stmt is the same, but this form allows the data recursion optimization.
661   bool dataTraverseStmtPre(Stmt *X) {
662     if (!X || isImplicit(X))
663       return false;
664     auto N = DynTypedNode::create(*X);
665     if (canSafelySkipNode(N))
666       return false;
667     push(std::move(N));
668     if (shouldSkipChildren(X)) {
669       pop();
670       return false;
671     }
672     return true;
673   }
674   bool dataTraverseStmtPost(Stmt *X) {
675     pop();
676     return true;
677   }
678   // QualifiedTypeLoc is handled strangely in RecursiveASTVisitor: the derived
679   // TraverseTypeLoc is not called for the inner UnqualTypeLoc.
680   // This means we'd never see 'int' in 'const int'! Work around that here.
681   // (The reason for the behavior is to avoid traversing the nested Type twice,
682   // but we ignore TraverseType anyway).
683   bool TraverseQualifiedTypeLoc(QualifiedTypeLoc QX) {
684     return traverseNode<TypeLoc>(
685         &QX, [&] { return TraverseTypeLoc(QX.getUnqualifiedLoc()); });
686   }
687   // Uninteresting parts of the AST that don't have locations within them.
688   bool TraverseNestedNameSpecifier(NestedNameSpecifier *) { return true; }
689   bool TraverseType(QualType) { return true; }
690 
691   // The DeclStmt for the loop variable claims to cover the whole range
692   // inside the parens, this causes the range-init expression to not be hit.
693   // Traverse the loop VarDecl instead, which has the right source range.
694   bool TraverseCXXForRangeStmt(CXXForRangeStmt *S) {
695     return traverseNode(S, [&] {
696       return TraverseStmt(S->getInit()) && TraverseDecl(S->getLoopVariable()) &&
697              TraverseStmt(S->getRangeInit()) && TraverseStmt(S->getBody());
698     });
699   }
700   // OpaqueValueExpr blocks traversal, we must explicitly traverse it.
701   bool TraverseOpaqueValueExpr(OpaqueValueExpr *E) {
702     return traverseNode(E, [&] { return TraverseStmt(E->getSourceExpr()); });
703   }
704   // We only want to traverse the *syntactic form* to understand the selection.
705   bool TraversePseudoObjectExpr(PseudoObjectExpr *E) {
706     return traverseNode(E, [&] { return TraverseStmt(E->getSyntacticForm()); });
707   }
708 
709 private:
710   using Base = RecursiveASTVisitor<SelectionVisitor>;
711 
712   SelectionVisitor(ASTContext &AST, const syntax::TokenBuffer &Tokens,
713                    const PrintingPolicy &PP, unsigned SelBegin, unsigned SelEnd,
714                    FileID SelFile)
715       : SM(AST.getSourceManager()), LangOpts(AST.getLangOpts()),
716 #ifndef NDEBUG
717         PrintPolicy(PP),
718 #endif
719         TokenBuf(Tokens), SelChecker(Tokens, SelFile, SelBegin, SelEnd, SM),
720         UnclaimedExpandedTokens(Tokens.expandedTokens()) {
721     // Ensure we have a node for the TU decl, regardless of traversal scope.
722     Nodes.emplace_back();
723     Nodes.back().ASTNode = DynTypedNode::create(*AST.getTranslationUnitDecl());
724     Nodes.back().Parent = nullptr;
725     Nodes.back().Selected = SelectionTree::Unselected;
726     Stack.push(&Nodes.back());
727   }
728 
729   // Generic case of TraverseFoo. Func should be the call to Base::TraverseFoo.
730   // Node is always a pointer so the generic code can handle any null checks.
731   template <typename T, typename Func>
732   bool traverseNode(T *Node, const Func &Body) {
733     if (Node == nullptr)
734       return true;
735     auto N = DynTypedNode::create(*Node);
736     if (canSafelySkipNode(N))
737       return true;
738     push(DynTypedNode::create(*Node));
739     bool Ret = Body();
740     pop();
741     return Ret;
742   }
743 
744   // HIT TESTING
745   //
746   // We do rough hit testing on the way down the tree to avoid traversing
747   // subtrees that don't touch the selection (canSafelySkipNode), but
748   // fine-grained hit-testing is mostly done on the way back up (in pop()).
749   // This means children get to claim parts of the selection first, and parents
750   // are only selected if they own tokens that no child owned.
751   //
752   // Nodes *usually* nest nicely: a child's getSourceRange() lies within the
753   // parent's, and a node (transitively) owns all tokens in its range.
754   //
755   // Exception 1: when declarators nest, *inner* declarator is the *outer* type.
756   //              e.g. void foo[5](int) is an array of functions.
757   // To handle this case, declarators are careful to only claim the tokens they
758   // own, rather than claim a range and rely on claim ordering.
759   //
760   // Exception 2: siblings both claim the same node.
761   //              e.g. `int x, y;` produces two sibling VarDecls.
762   //                    ~~~~~ x
763   //                    ~~~~~~~~ y
764   // Here the first ("leftmost") sibling claims the tokens it wants, and the
765   // other sibling gets what's left. So selecting "int" only includes the left
766   // VarDecl in the selection tree.
767 
768   // An optimization for a common case: nodes outside macro expansions that
769   // don't intersect the selection may be recursively skipped.
770   bool canSafelySkipNode(const DynTypedNode &N) {
771     SourceRange S = getSourceRange(N);
772     if (auto *TL = N.get<TypeLoc>()) {
773       // FIXME: TypeLoc::getBeginLoc()/getEndLoc() are pretty fragile
774       // heuristics. We should consider only pruning critical TypeLoc nodes, to
775       // be more robust.
776 
777       // AttributedTypeLoc may point to the attribute's range, NOT the modified
778       // type's range.
779       if (auto AT = TL->getAs<AttributedTypeLoc>())
780         S = AT.getModifiedLoc().getSourceRange();
781     }
782     // SourceRange often doesn't manage to accurately cover attributes.
783     // Fortunately, attributes are rare.
784     if (llvm::any_of(getAttributes(N),
785                      [](const Attr *A) { return !A->isImplicit(); }))
786       return false;
787     if (!SelChecker.mayHit(S)) {
788       dlog("{2}skip: {0} {1}", printNodeToString(N, PrintPolicy),
789            S.printToString(SM), indent());
790       return true;
791     }
792     return false;
793   }
794 
795   // There are certain nodes we want to treat as leaves in the SelectionTree,
796   // although they do have children.
797   bool shouldSkipChildren(const Stmt *X) const {
798     // UserDefinedLiteral (e.g. 12_i) has two children (12 and _i).
799     // Unfortunately TokenBuffer sees 12_i as one token and can't split it.
800     // So we treat UserDefinedLiteral as a leaf node, owning the token.
801     return llvm::isa<UserDefinedLiteral>(X);
802   }
803 
804   // Pushes a node onto the ancestor stack. Pairs with pop().
805   // Performs early hit detection for some nodes (on the earlySourceRange).
806   void push(DynTypedNode Node) {
807     SourceRange Early = earlySourceRange(Node);
808     dlog("{2}push: {0} {1}", printNodeToString(Node, PrintPolicy),
809          Node.getSourceRange().printToString(SM), indent());
810     Nodes.emplace_back();
811     Nodes.back().ASTNode = std::move(Node);
812     Nodes.back().Parent = Stack.top();
813     Nodes.back().Selected = NoTokens;
814     Stack.push(&Nodes.back());
815     claimRange(Early, Nodes.back().Selected);
816   }
817 
818   // Pops a node off the ancestor stack, and finalizes it. Pairs with push().
819   // Performs primary hit detection.
820   void pop() {
821     Node &N = *Stack.top();
822     dlog("{1}pop: {0}", printNodeToString(N.ASTNode, PrintPolicy), indent(-1));
823     claimTokensFor(N.ASTNode, N.Selected);
824     if (N.Selected == NoTokens)
825       N.Selected = SelectionTree::Unselected;
826     if (N.Selected || !N.Children.empty()) {
827       // Attach to the tree.
828       N.Parent->Children.push_back(&N);
829     } else {
830       // Neither N any children are selected, it doesn't belong in the tree.
831       assert(&N == &Nodes.back());
832       Nodes.pop_back();
833     }
834     Stack.pop();
835   }
836 
837   // Returns the range of tokens that this node will claim directly, and
838   // is not available to the node's children.
839   // Usually empty, but sometimes children cover tokens but shouldn't own them.
840   SourceRange earlySourceRange(const DynTypedNode &N) {
841     if (const Decl *D = N.get<Decl>()) {
842       // We want the name in the var-decl to be claimed by the decl itself and
843       // not by any children. Ususally, we don't need this, because source
844       // ranges of children are not overlapped with their parent's.
845       // An exception is lambda captured var decl, where AutoTypeLoc is
846       // overlapped with the name loc.
847       //    auto fun = [bar = foo]() { ... }
848       //                ~~~~~~~~~   VarDecl
849       //                ~~~         |- AutoTypeLoc
850       if (const auto *DD = llvm::dyn_cast<VarDecl>(D))
851         return DD->getLocation();
852     }
853 
854     return SourceRange();
855   }
856 
857   // Claim tokens for N, after processing its children.
858   // By default this claims all unclaimed tokens in getSourceRange().
859   // We override this if we want to claim fewer tokens (e.g. there are gaps).
860   void claimTokensFor(const DynTypedNode &N, SelectionTree::Selection &Result) {
861     // CXXConstructExpr often shows implicit construction, like `string s;`.
862     // Don't associate any tokens with it unless there's some syntax like {}.
863     // This prevents it from claiming 's', its primary location.
864     if (const auto *CCE = N.get<CXXConstructExpr>()) {
865       claimRange(CCE->getParenOrBraceRange(), Result);
866       return;
867     }
868     // ExprWithCleanups is always implicit. It often wraps CXXConstructExpr.
869     // Prevent it claiming 's' in the case above.
870     if (N.get<ExprWithCleanups>())
871       return;
872 
873     // Declarators nest "inside out", with parent types inside child ones.
874     // Instead of claiming the whole range (clobbering parent tokens), carefully
875     // claim the tokens owned by this node and non-declarator children.
876     // (We could manipulate traversal order instead, but this is easier).
877     //
878     // Non-declarator types nest normally, and are handled like other nodes.
879     //
880     // Example:
881     //   Vec<R<int>(*[2])(A<char>)> is a Vec of arrays of pointers to functions,
882     //                              which accept A<char> and return R<int>.
883     // The TypeLoc hierarchy:
884     //   Vec<R<int>(*[2])(A<char>)> m;
885     //   Vec<#####################>      TemplateSpecialization Vec
886     //       --------[2]----------       `-Array
887     //       -------*-------------         `-Pointer
888     //       ------(----)---------           `-Paren
889     //       ------------(#######)             `-Function
890     //       R<###>                              |-TemplateSpecialization R
891     //         int                               | `-Builtin int
892     //                    A<####>                `-TemplateSpecialization A
893     //                      char                   `-Builtin char
894     //
895     // In each row
896     //   --- represents unclaimed parts of the SourceRange.
897     //   ### represents parts that children already claimed.
898     if (const auto *TL = N.get<TypeLoc>()) {
899       if (auto PTL = TL->getAs<ParenTypeLoc>()) {
900         claimRange(PTL.getLParenLoc(), Result);
901         claimRange(PTL.getRParenLoc(), Result);
902         return;
903       }
904       if (auto ATL = TL->getAs<ArrayTypeLoc>()) {
905         claimRange(ATL.getBracketsRange(), Result);
906         return;
907       }
908       if (auto PTL = TL->getAs<PointerTypeLoc>()) {
909         claimRange(PTL.getStarLoc(), Result);
910         return;
911       }
912       if (auto FTL = TL->getAs<FunctionTypeLoc>()) {
913         claimRange(SourceRange(FTL.getLParenLoc(), FTL.getEndLoc()), Result);
914         return;
915       }
916     }
917     claimRange(getSourceRange(N), Result);
918   }
919 
920   // Perform hit-testing of a complete Node against the selection.
921   // This runs for every node in the AST, and must be fast in common cases.
922   // This is usually called from pop(), so we can take children into account.
923   // The existing state of Result is relevant.
924   void claimRange(SourceRange S, SelectionTree::Selection &Result) {
925     for (const auto &ClaimedRange :
926          UnclaimedExpandedTokens.erase(TokenBuf.expandedTokens(S)))
927       update(Result, SelChecker.test(ClaimedRange));
928 
929     if (Result && Result != NoTokens)
930       dlog("{1}hit selection: {0}", S.printToString(SM), indent());
931   }
932 
933   std::string indent(int Offset = 0) {
934     // Cast for signed arithmetic.
935     int Amount = int(Stack.size()) + Offset;
936     assert(Amount >= 0);
937     return std::string(Amount, ' ');
938   }
939 
940   SourceManager &SM;
941   const LangOptions &LangOpts;
942 #ifndef NDEBUG
943   const PrintingPolicy &PrintPolicy;
944 #endif
945   const syntax::TokenBuffer &TokenBuf;
946   std::stack<Node *> Stack;
947   SelectionTester SelChecker;
948   IntervalSet<syntax::Token> UnclaimedExpandedTokens;
949   std::deque<Node> Nodes; // Stable pointers as we add more nodes.
950 };
951 
952 } // namespace
953 
954 llvm::SmallString<256> abbreviatedString(DynTypedNode N,
955                                          const PrintingPolicy &PP) {
956   llvm::SmallString<256> Result;
957   {
958     llvm::raw_svector_ostream OS(Result);
959     N.print(OS, PP);
960   }
961   auto Pos = Result.find('\n');
962   if (Pos != llvm::StringRef::npos) {
963     bool MoreText = !llvm::all_of(Result.str().drop_front(Pos), llvm::isSpace);
964     Result.resize(Pos);
965     if (MoreText)
966       Result.append(" …");
967   }
968   return Result;
969 }
970 
971 void SelectionTree::print(llvm::raw_ostream &OS, const SelectionTree::Node &N,
972                           int Indent) const {
973   if (N.Selected)
974     OS.indent(Indent - 1) << (N.Selected == SelectionTree::Complete ? '*'
975                                                                     : '.');
976   else
977     OS.indent(Indent);
978   printNodeKind(OS, N.ASTNode);
979   OS << ' ' << abbreviatedString(N.ASTNode, PrintPolicy) << "\n";
980   for (const Node *Child : N.Children)
981     print(OS, *Child, Indent + 2);
982 }
983 
984 std::string SelectionTree::Node::kind() const {
985   std::string S;
986   llvm::raw_string_ostream OS(S);
987   printNodeKind(OS, ASTNode);
988   return std::move(OS.str());
989 }
990 
991 // Decide which selections emulate a "point" query in between characters.
992 // If it's ambiguous (the neighboring characters are selectable tokens), returns
993 // both possibilities in preference order.
994 // Always returns at least one range - if no tokens touched, and empty range.
995 static llvm::SmallVector<std::pair<unsigned, unsigned>, 2>
996 pointBounds(unsigned Offset, const syntax::TokenBuffer &Tokens) {
997   const auto &SM = Tokens.sourceManager();
998   SourceLocation Loc = SM.getComposedLoc(SM.getMainFileID(), Offset);
999   llvm::SmallVector<std::pair<unsigned, unsigned>, 2> Result;
1000   // Prefer right token over left.
1001   for (const syntax::Token &Tok :
1002        llvm::reverse(spelledTokensTouching(Loc, Tokens))) {
1003     if (shouldIgnore(Tok))
1004       continue;
1005     unsigned Offset = Tokens.sourceManager().getFileOffset(Tok.location());
1006     Result.emplace_back(Offset, Offset + Tok.length());
1007   }
1008   if (Result.empty())
1009     Result.emplace_back(Offset, Offset);
1010   return Result;
1011 }
1012 
1013 bool SelectionTree::createEach(ASTContext &AST,
1014                                const syntax::TokenBuffer &Tokens,
1015                                unsigned Begin, unsigned End,
1016                                llvm::function_ref<bool(SelectionTree)> Func) {
1017   if (Begin != End)
1018     return Func(SelectionTree(AST, Tokens, Begin, End));
1019   for (std::pair<unsigned, unsigned> Bounds : pointBounds(Begin, Tokens))
1020     if (Func(SelectionTree(AST, Tokens, Bounds.first, Bounds.second)))
1021       return true;
1022   return false;
1023 }
1024 
1025 SelectionTree SelectionTree::createRight(ASTContext &AST,
1026                                          const syntax::TokenBuffer &Tokens,
1027                                          unsigned int Begin, unsigned int End) {
1028   llvm::Optional<SelectionTree> Result;
1029   createEach(AST, Tokens, Begin, End, [&](SelectionTree T) {
1030     Result = std::move(T);
1031     return true;
1032   });
1033   return std::move(*Result);
1034 }
1035 
1036 SelectionTree::SelectionTree(ASTContext &AST, const syntax::TokenBuffer &Tokens,
1037                              unsigned Begin, unsigned End)
1038     : PrintPolicy(AST.getLangOpts()) {
1039   // No fundamental reason the selection needs to be in the main file,
1040   // but that's all clangd has needed so far.
1041   const SourceManager &SM = AST.getSourceManager();
1042   FileID FID = SM.getMainFileID();
1043   PrintPolicy.TerseOutput = true;
1044   PrintPolicy.IncludeNewlines = false;
1045 
1046   dlog("Computing selection for {0}",
1047        SourceRange(SM.getComposedLoc(FID, Begin), SM.getComposedLoc(FID, End))
1048            .printToString(SM));
1049   Nodes = SelectionVisitor::collect(AST, Tokens, PrintPolicy, Begin, End, FID);
1050   Root = Nodes.empty() ? nullptr : &Nodes.front();
1051   recordMetrics(*this, AST.getLangOpts());
1052   dlog("Built selection tree\n{0}", *this);
1053 }
1054 
1055 const Node *SelectionTree::commonAncestor() const {
1056   const Node *Ancestor = Root;
1057   while (Ancestor->Children.size() == 1 && !Ancestor->Selected)
1058     Ancestor = Ancestor->Children.front();
1059   // Returning nullptr here is a bit unprincipled, but it makes the API safer:
1060   // the TranslationUnitDecl contains all of the preamble, so traversing it is a
1061   // performance cliff. Callers can check for null and use root() if they want.
1062   return Ancestor != Root ? Ancestor : nullptr;
1063 }
1064 
1065 const DeclContext &SelectionTree::Node::getDeclContext() const {
1066   for (const Node *CurrentNode = this; CurrentNode != nullptr;
1067        CurrentNode = CurrentNode->Parent) {
1068     if (const Decl *Current = CurrentNode->ASTNode.get<Decl>()) {
1069       if (CurrentNode != this)
1070         if (auto *DC = dyn_cast<DeclContext>(Current))
1071           return *DC;
1072       return *Current->getLexicalDeclContext();
1073     }
1074   }
1075   llvm_unreachable("A tree must always be rooted at TranslationUnitDecl.");
1076 }
1077 
1078 const SelectionTree::Node &SelectionTree::Node::ignoreImplicit() const {
1079   if (Children.size() == 1 &&
1080       getSourceRange(Children.front()->ASTNode) == getSourceRange(ASTNode))
1081     return Children.front()->ignoreImplicit();
1082   return *this;
1083 }
1084 
1085 const SelectionTree::Node &SelectionTree::Node::outerImplicit() const {
1086   if (Parent && getSourceRange(Parent->ASTNode) == getSourceRange(ASTNode))
1087     return Parent->outerImplicit();
1088   return *this;
1089 }
1090 
1091 } // namespace clangd
1092 } // namespace clang
1093