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