clang-tools  14.0.0git
Selection.cpp
Go to the documentation of this file.
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.
292  test(llvm::ArrayRef<syntax::Token> ExpandedTokens) const {
293  if (ExpandedTokens.empty())
294  return NoTokens;
295  if (SelectedSpelled.empty())
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()) {
307  }
308 
309  SelectionTree::Selection Result = NoTokens;
310  while (!ExpandedTokens.empty()) {
311  // Take consecutive tokens from the same context together for efficiency.
312  SourceLocation Start = ExpandedTokens.front().location();
313  FileID FID = SM.getFileID(Start);
314  // Comparing SourceLocations against bounds is cheaper than getFileID().
315  SourceLocation Limit = SM.getComposedLoc(FID, SM.getFileIDSize(FID));
316  auto Batch = ExpandedTokens.take_while([&](const syntax::Token &T) {
317  return T.location() >= Start && T.location() < Limit;
318  });
319  assert(!Batch.empty());
320  ExpandedTokens = ExpandedTokens.drop_front(Batch.size());
321 
322  update(Result, testChunk(FID, Batch));
323  }
324  return Result;
325  }
326 
327  // Cheap check whether any of the tokens in R might be selected.
328  // If it returns false, test() will return NoTokens or Unselected.
329  // If it returns true, test() may return any value.
330  bool mayHit(SourceRange R) const {
331  if (SelectedSpelled.empty() || MaybeSelectedExpanded.empty())
332  return false;
333  // If the node starts after the selection ends, it is not selected.
334  // Tokens a macro location might claim are >= its expansion start.
335  // So if the expansion start > last selected token, we can prune it.
336  // (This is particularly helpful for GTest's TEST macro).
337  if (auto B = offsetInSelFile(getExpansionStart(R.getBegin())))
338  if (*B > SelectedSpelled.back().Offset)
339  return false;
340  // If the node ends before the selection begins, it is not selected.
341  SourceLocation EndLoc = R.getEnd();
342  while (EndLoc.isMacroID())
343  EndLoc = SM.getImmediateExpansionRange(EndLoc).getEnd();
344  // In the rare case that the expansion range is a char range, EndLoc is
345  // ~one token too far to the right. We may fail to prune, that's OK.
346  if (auto E = offsetInSelFile(EndLoc))
347  if (*E < SelectedSpelled.front().Offset)
348  return false;
349  return true;
350  }
351 
352 private:
353  // Plausible expanded tokens that might be affected by the selection.
354  // This is an overestimate, it may contain tokens that are not selected.
355  // The point is to allow cheap pruning in test()
356  llvm::ArrayRef<syntax::Token>
357  computeMaybeSelectedExpandedTokens(const syntax::TokenBuffer &Toks) {
358  if (SelectedSpelled.empty())
359  return {};
360 
361  auto LastAffectedToken = [&](SourceLocation Loc) {
362  auto Offset = offsetInSelFile(Loc);
363  while (Loc.isValid() && !Offset) {
364  Loc = Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getEnd()
365  : SM.getIncludeLoc(SM.getFileID(Loc));
366  Offset = offsetInSelFile(Loc);
367  }
368  return Offset;
369  };
370  auto FirstAffectedToken = [&](SourceLocation Loc) {
371  auto Offset = offsetInSelFile(Loc);
372  while (Loc.isValid() && !Offset) {
373  Loc = Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
374  : SM.getIncludeLoc(SM.getFileID(Loc));
375  Offset = offsetInSelFile(Loc);
376  }
377  return Offset;
378  };
379 
380  const syntax::Token *Start = llvm::partition_point(
381  Toks.expandedTokens(),
382  [&, First = SelectedSpelled.front().Offset](const syntax::Token &Tok) {
383  if (Tok.kind() == tok::eof)
384  return false;
385  // Implausible if upperbound(Tok) < First.
386  if (auto Offset = LastAffectedToken(Tok.location()))
387  return *Offset < First;
388  // A prefix of the expanded tokens may be from an an implicit
389  // inclusion (e.g. preamble patch, or command-line -include).
390  return true;
391  });
392 
393  bool EndInvalid = false;
394  const syntax::Token *End = std::partition_point(
395  Start, Toks.expandedTokens().end(),
396  [&, Last = SelectedSpelled.back().Offset](const syntax::Token &Tok) {
397  if (Tok.kind() == tok::eof)
398  return false;
399  // Plausible if lowerbound(Tok) <= Last.
400  if (auto Offset = FirstAffectedToken(Tok.location()))
401  return *Offset <= Last;
402  // Shouldn't happen: once we've seen tokens traceable to the main
403  // file, there shouldn't be any more implicit inclusions.
404  assert(false && "Expanded token could not be resolved to main file!");
405  EndInvalid = true;
406  return true; // conservatively assume this token can overlap
407  });
408  if (EndInvalid)
409  End = Toks.expandedTokens().end();
410 
411  return llvm::makeArrayRef(Start, End);
412  }
413 
414  // Hit-test a consecutive range of tokens from a single file ID.
416  testChunk(FileID FID, llvm::ArrayRef<syntax::Token> Batch) const {
417  assert(!Batch.empty());
418  SourceLocation StartLoc = Batch.front().location();
419  // There are several possible categories of FileID depending on how the
420  // preprocessor was used to generate these tokens:
421  // main file, #included file, macro args, macro bodies.
422  // We need to identify the main-file tokens that represent Batch, and
423  // determine whether we want to exclusively claim them. Regular tokens
424  // represent one AST construct, but a macro invocation can represent many.
425 
426  // Handle tokens written directly in the main file.
427  if (FID == SelFile) {
428  return testTokenRange(*offsetInSelFile(Batch.front().location()),
429  *offsetInSelFile(Batch.back().location()));
430  }
431 
432  // Handle tokens in another file #included into the main file.
433  // Check if the #include is selected, but don't claim it exclusively.
434  if (StartLoc.isFileID()) {
435  for (SourceLocation Loc = Batch.front().location(); Loc.isValid();
436  Loc = SM.getIncludeLoc(SM.getFileID(Loc))) {
437  if (auto Offset = offsetInSelFile(Loc))
438  // FIXME: use whole #include directive, not just the filename string.
439  return testToken(*Offset);
440  }
441  return NoTokens;
442  }
443 
444  assert(StartLoc.isMacroID());
445  // Handle tokens that were passed as a macro argument.
446  SourceLocation ArgStart = SM.getTopMacroCallerLoc(StartLoc);
447  if (auto ArgOffset = offsetInSelFile(ArgStart)) {
448  if (isFirstExpansion(FID, ArgStart, SM)) {
449  SourceLocation ArgEnd =
450  SM.getTopMacroCallerLoc(Batch.back().location());
451  return testTokenRange(*ArgOffset, *offsetInSelFile(ArgEnd));
452  } else { // NOLINT(llvm-else-after-return)
453  /* fall through and treat as part of the macro body */
454  }
455  }
456 
457  // Handle tokens produced by non-argument macro expansion.
458  // Check if the macro name is selected, don't claim it exclusively.
459  if (auto ExpansionOffset = offsetInSelFile(getExpansionStart(StartLoc)))
460  // FIXME: also check ( and ) for function-like macros?
461  return testToken(*ExpansionOffset);
462  return NoTokens;
463  }
464 
465  // Is the closed token range [Begin, End] selected?
466  SelectionTree::Selection testTokenRange(unsigned Begin, unsigned End) const {
467  assert(Begin <= End);
468  // Outside the selection entirely?
469  if (End < SelectedSpelled.front().Offset ||
470  Begin > SelectedSpelled.back().Offset)
472 
473  // Compute range of tokens.
474  auto B = llvm::partition_point(
475  SelectedSpelled, [&](const Tok &T) { return T.Offset < Begin; });
476  auto E = std::partition_point(B, SelectedSpelled.end(), [&](const Tok &T) {
477  return T.Offset <= End;
478  });
479 
480  // Aggregate selectedness of tokens in range.
481  bool ExtendsOutsideSelection = Begin < SelectedSpelled.front().Offset ||
482  End > SelectedSpelled.back().Offset;
483  SelectionTree::Selection Result =
484  ExtendsOutsideSelection ? SelectionTree::Unselected : NoTokens;
485  for (auto It = B; It != E; ++It)
486  update(Result, It->Selected);
487  return Result;
488  }
489 
490  // Is the token at `Offset` selected?
491  SelectionTree::Selection testToken(unsigned Offset) const {
492  // Outside the selection entirely?
493  if (Offset < SelectedSpelled.front().Offset ||
494  Offset > SelectedSpelled.back().Offset)
496  // Find the token, if it exists.
497  auto It = llvm::partition_point(
498  SelectedSpelled, [&](const Tok &T) { return T.Offset < Offset; });
499  if (It != SelectedSpelled.end() && It->Offset == Offset)
500  return It->Selected;
501  return NoTokens;
502  }
503 
504  // Decomposes Loc and returns the offset if the file ID is SelFile.
505  llvm::Optional<unsigned> offsetInSelFile(SourceLocation Loc) const {
506  // Decoding Loc with SM.getDecomposedLoc is relatively expensive.
507  // But SourceLocations for a file are numerically contiguous, so we
508  // can use cheap integer operations instead.
509  if (Loc < SelFileBounds.getBegin() || Loc >= SelFileBounds.getEnd())
510  return llvm::None;
511  // FIXME: subtracting getRawEncoding() is dubious, move this logic into SM.
512  return Loc.getRawEncoding() - SelFileBounds.getBegin().getRawEncoding();
513  }
514 
515  SourceLocation getExpansionStart(SourceLocation Loc) const {
516  while (Loc.isMacroID())
517  Loc = SM.getImmediateExpansionRange(Loc).getBegin();
518  return Loc;
519  }
520 
521  struct Tok {
522  unsigned Offset;
524  };
525  std::vector<Tok> SelectedSpelled;
526  llvm::ArrayRef<syntax::Token> MaybeSelectedExpanded;
527  FileID SelFile;
528  SourceRange SelFileBounds;
529  const SourceManager &SM;
530 };
531 
532 // Show the type of a node for debugging.
533 void printNodeKind(llvm::raw_ostream &OS, const DynTypedNode &N) {
534  if (const TypeLoc *TL = N.get<TypeLoc>()) {
535  // TypeLoc is a hierarchy, but has only a single ASTNodeKind.
536  // Synthesize the name from the Type subclass (except for QualifiedTypeLoc).
537  if (TL->getTypeLocClass() == TypeLoc::Qualified)
538  OS << "QualifiedTypeLoc";
539  else
540  OS << TL->getType()->getTypeClassName() << "TypeLoc";
541  } else {
542  OS << N.getNodeKind().asStringRef();
543  }
544 }
545 
546 #ifndef NDEBUG
547 std::string printNodeToString(const DynTypedNode &N, const PrintingPolicy &PP) {
548  std::string S;
549  llvm::raw_string_ostream OS(S);
550  printNodeKind(OS, N);
551  return std::move(OS.str());
552 }
553 #endif
554 
555 bool isImplicit(const Stmt *S) {
556  // Some Stmts are implicit and shouldn't be traversed, but there's no
557  // "implicit" attribute on Stmt/Expr.
558  // Unwrap implicit casts first if present (other nodes too?).
559  if (auto *ICE = llvm::dyn_cast<ImplicitCastExpr>(S))
560  S = ICE->getSubExprAsWritten();
561  // Implicit this in a MemberExpr is not filtered out by RecursiveASTVisitor.
562  // It would be nice if RAV handled this (!shouldTraverseImplicitCode()).
563  if (auto *CTI = llvm::dyn_cast<CXXThisExpr>(S))
564  if (CTI->isImplicit())
565  return true;
566  // Make sure implicit access of anonymous structs don't end up owning tokens.
567  if (auto *ME = llvm::dyn_cast<MemberExpr>(S)) {
568  if (auto *FD = llvm::dyn_cast<FieldDecl>(ME->getMemberDecl()))
569  if (FD->isAnonymousStructOrUnion())
570  // If Base is an implicit CXXThis, then the whole MemberExpr has no
571  // tokens. If it's a normal e.g. DeclRef, we treat the MemberExpr like
572  // an implicit cast.
573  return isImplicit(ME->getBase());
574  }
575  // Refs to operator() and [] are (almost?) always implicit as part of calls.
576  if (auto *DRE = llvm::dyn_cast<DeclRefExpr>(S)) {
577  if (auto *FD = llvm::dyn_cast<FunctionDecl>(DRE->getDecl())) {
578  switch (FD->getOverloadedOperator()) {
579  case OO_Call:
580  case OO_Subscript:
581  return true;
582  default:
583  break;
584  }
585  }
586  }
587  return false;
588 }
589 
590 // We find the selection by visiting written nodes in the AST, looking for nodes
591 // that intersect with the selected character range.
592 //
593 // While traversing, we maintain a parent stack. As nodes pop off the stack,
594 // we decide whether to keep them or not. To be kept, they must either be
595 // selected or contain some nodes that are.
596 //
597 // For simple cases (not inside macros) we prune subtrees that don't intersect.
598 class SelectionVisitor : public RecursiveASTVisitor<SelectionVisitor> {
599 public:
600  // Runs the visitor to gather selected nodes and their ancestors.
601  // If there is any selection, the root (TUDecl) is the first node.
602  static std::deque<Node> collect(ASTContext &AST,
603  const syntax::TokenBuffer &Tokens,
604  const PrintingPolicy &PP, unsigned Begin,
605  unsigned End, FileID File) {
606  SelectionVisitor V(AST, Tokens, PP, Begin, End, File);
607  V.TraverseAST(AST);
608  assert(V.Stack.size() == 1 && "Unpaired push/pop?");
609  assert(V.Stack.top() == &V.Nodes.front());
610  return std::move(V.Nodes);
611  }
612 
613  // We traverse all "well-behaved" nodes the same way:
614  // - push the node onto the stack
615  // - traverse its children recursively
616  // - pop it from the stack
617  // - hit testing: is intersection(node, selection) - union(children) empty?
618  // - attach it to the tree if it or any children hit the selection
619  //
620  // Two categories of nodes are not "well-behaved":
621  // - those without source range information, we don't record those
622  // - those that can't be stored in DynTypedNode.
623  bool TraverseDecl(Decl *X) {
624  if (llvm::isa_and_nonnull<TranslationUnitDecl>(X))
625  return Base::TraverseDecl(X); // Already pushed by constructor.
626  // Base::TraverseDecl will suppress children, but not this node itself.
627  if (X && X->isImplicit())
628  return true;
629  return traverseNode(X, [&] { return Base::TraverseDecl(X); });
630  }
631  bool TraverseTypeLoc(TypeLoc X) {
632  return traverseNode(&X, [&] { return Base::TraverseTypeLoc(X); });
633  }
634  bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &X) {
635  return traverseNode(&X,
636  [&] { return Base::TraverseTemplateArgumentLoc(X); });
637  }
638  bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc X) {
639  return traverseNode(
640  &X, [&] { return Base::TraverseNestedNameSpecifierLoc(X); });
641  }
642  bool TraverseConstructorInitializer(CXXCtorInitializer *X) {
643  return traverseNode(
644  X, [&] { return Base::TraverseConstructorInitializer(X); });
645  }
646  bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &X) {
647  return traverseNode(&X, [&] { return Base::TraverseCXXBaseSpecifier(X); });
648  }
649  bool TraverseAttr(Attr *X) {
650  return traverseNode(X, [&] { return Base::TraverseAttr(X); });
651  }
652  // Stmt is the same, but this form allows the data recursion optimization.
653  bool dataTraverseStmtPre(Stmt *X) {
654  if (!X || isImplicit(X))
655  return false;
656  auto N = DynTypedNode::create(*X);
657  if (canSafelySkipNode(N))
658  return false;
659  push(std::move(N));
660  if (shouldSkipChildren(X)) {
661  pop();
662  return false;
663  }
664  return true;
665  }
666  bool dataTraverseStmtPost(Stmt *X) {
667  pop();
668  return true;
669  }
670  // QualifiedTypeLoc is handled strangely in RecursiveASTVisitor: the derived
671  // TraverseTypeLoc is not called for the inner UnqualTypeLoc.
672  // This means we'd never see 'int' in 'const int'! Work around that here.
673  // (The reason for the behavior is to avoid traversing the nested Type twice,
674  // but we ignore TraverseType anyway).
675  bool TraverseQualifiedTypeLoc(QualifiedTypeLoc QX) {
676  return traverseNode<TypeLoc>(
677  &QX, [&] { return TraverseTypeLoc(QX.getUnqualifiedLoc()); });
678  }
679  // Uninteresting parts of the AST that don't have locations within them.
680  bool TraverseNestedNameSpecifier(NestedNameSpecifier *) { return true; }
681  bool TraverseType(QualType) { return true; }
682 
683  // The DeclStmt for the loop variable claims to cover the whole range
684  // inside the parens, this causes the range-init expression to not be hit.
685  // Traverse the loop VarDecl instead, which has the right source range.
686  bool TraverseCXXForRangeStmt(CXXForRangeStmt *S) {
687  return traverseNode(S, [&] {
688  return TraverseStmt(S->getInit()) && TraverseDecl(S->getLoopVariable()) &&
689  TraverseStmt(S->getRangeInit()) && TraverseStmt(S->getBody());
690  });
691  }
692  // OpaqueValueExpr blocks traversal, we must explicitly traverse it.
693  bool TraverseOpaqueValueExpr(OpaqueValueExpr *E) {
694  return traverseNode(E, [&] { return TraverseStmt(E->getSourceExpr()); });
695  }
696  // We only want to traverse the *syntactic form* to understand the selection.
697  bool TraversePseudoObjectExpr(PseudoObjectExpr *E) {
698  return traverseNode(E, [&] { return TraverseStmt(E->getSyntacticForm()); });
699  }
700 
701 private:
703 
704  SelectionVisitor(ASTContext &AST, const syntax::TokenBuffer &Tokens,
705  const PrintingPolicy &PP, unsigned SelBegin, unsigned SelEnd,
706  FileID SelFile)
707  : SM(AST.getSourceManager()), LangOpts(AST.getLangOpts()),
708 #ifndef NDEBUG
709  PrintPolicy(PP),
710 #endif
711  TokenBuf(Tokens), SelChecker(Tokens, SelFile, SelBegin, SelEnd, SM),
712  UnclaimedExpandedTokens(Tokens.expandedTokens()) {
713  // Ensure we have a node for the TU decl, regardless of traversal scope.
714  Nodes.emplace_back();
715  Nodes.back().ASTNode = DynTypedNode::create(*AST.getTranslationUnitDecl());
716  Nodes.back().Parent = nullptr;
717  Nodes.back().Selected = SelectionTree::Unselected;
718  Stack.push(&Nodes.back());
719  }
720 
721  // Generic case of TraverseFoo. Func should be the call to Base::TraverseFoo.
722  // Node is always a pointer so the generic code can handle any null checks.
723  template <typename T, typename Func>
724  bool traverseNode(T *Node, const Func &Body) {
725  if (Node == nullptr)
726  return true;
727  auto N = DynTypedNode::create(*Node);
728  if (canSafelySkipNode(N))
729  return true;
730  push(DynTypedNode::create(*Node));
731  bool Ret = Body();
732  pop();
733  return Ret;
734  }
735 
736  // HIT TESTING
737  //
738  // We do rough hit testing on the way down the tree to avoid traversing
739  // subtrees that don't touch the selection (canSafelySkipNode), but
740  // fine-grained hit-testing is mostly done on the way back up (in pop()).
741  // This means children get to claim parts of the selection first, and parents
742  // are only selected if they own tokens that no child owned.
743  //
744  // Nodes *usually* nest nicely: a child's getSourceRange() lies within the
745  // parent's, and a node (transitively) owns all tokens in its range.
746  //
747  // Exception 1: when declarators nest, *inner* declarator is the *outer* type.
748  // e.g. void foo[5](int) is an array of functions.
749  // To handle this case, declarators are careful to only claim the tokens they
750  // own, rather than claim a range and rely on claim ordering.
751  //
752  // Exception 2: siblings both claim the same node.
753  // e.g. `int x, y;` produces two sibling VarDecls.
754  // ~~~~~ x
755  // ~~~~~~~~ y
756  // Here the first ("leftmost") sibling claims the tokens it wants, and the
757  // other sibling gets what's left. So selecting "int" only includes the left
758  // VarDecl in the selection tree.
759 
760  // An optimization for a common case: nodes outside macro expansions that
761  // don't intersect the selection may be recursively skipped.
762  bool canSafelySkipNode(const DynTypedNode &N) {
763  SourceRange S = getSourceRange(N);
764  if (auto *TL = N.get<TypeLoc>()) {
765  // FIXME: TypeLoc::getBeginLoc()/getEndLoc() are pretty fragile
766  // heuristics. We should consider only pruning critical TypeLoc nodes, to
767  // be more robust.
768 
769  // AttributedTypeLoc may point to the attribute's range, NOT the modified
770  // type's range.
771  if (auto AT = TL->getAs<AttributedTypeLoc>())
772  S = AT.getModifiedLoc().getSourceRange();
773  }
774  // SourceRange often doesn't manage to accurately cover attributes.
775  // Fortunately, attributes are rare.
776  if (llvm::any_of(getAttributes(N),
777  [](const Attr *A) { return !A->isImplicit(); }))
778  return false;
779  if (!SelChecker.mayHit(S)) {
780  dlog("{2}skip: {0} {1}", printNodeToString(N, PrintPolicy),
781  S.printToString(SM), indent());
782  return true;
783  }
784  return false;
785  }
786 
787  // There are certain nodes we want to treat as leaves in the SelectionTree,
788  // although they do have children.
789  bool shouldSkipChildren(const Stmt *X) const {
790  // UserDefinedLiteral (e.g. 12_i) has two children (12 and _i).
791  // Unfortunately TokenBuffer sees 12_i as one token and can't split it.
792  // So we treat UserDefinedLiteral as a leaf node, owning the token.
793  return llvm::isa<UserDefinedLiteral>(X);
794  }
795 
796  // Pushes a node onto the ancestor stack. Pairs with pop().
797  // Performs early hit detection for some nodes (on the earlySourceRange).
798  void push(DynTypedNode Node) {
799  SourceRange Early = earlySourceRange(Node);
800  dlog("{2}push: {0} {1}", printNodeToString(Node, PrintPolicy),
801  Node.getSourceRange().printToString(SM), indent());
802  Nodes.emplace_back();
803  Nodes.back().ASTNode = std::move(Node);
804  Nodes.back().Parent = Stack.top();
805  Nodes.back().Selected = NoTokens;
806  Stack.push(&Nodes.back());
807  claimRange(Early, Nodes.back().Selected);
808  }
809 
810  // Pops a node off the ancestor stack, and finalizes it. Pairs with push().
811  // Performs primary hit detection.
812  void pop() {
813  Node &N = *Stack.top();
814  dlog("{1}pop: {0}", printNodeToString(N.ASTNode, PrintPolicy), indent(-1));
815  claimTokensFor(N.ASTNode, N.Selected);
816  if (N.Selected == NoTokens)
817  N.Selected = SelectionTree::Unselected;
818  if (N.Selected || !N.Children.empty()) {
819  // Attach to the tree.
820  N.Parent->Children.push_back(&N);
821  } else {
822  // Neither N any children are selected, it doesn't belong in the tree.
823  assert(&N == &Nodes.back());
824  Nodes.pop_back();
825  }
826  Stack.pop();
827  }
828 
829  // Returns the range of tokens that this node will claim directly, and
830  // is not available to the node's children.
831  // Usually empty, but sometimes children cover tokens but shouldn't own them.
832  SourceRange earlySourceRange(const DynTypedNode &N) {
833  if (const Decl *D = N.get<Decl>()) {
834  // We want the name in the var-decl to be claimed by the decl itself and
835  // not by any children. Ususally, we don't need this, because source
836  // ranges of children are not overlapped with their parent's.
837  // An exception is lambda captured var decl, where AutoTypeLoc is
838  // overlapped with the name loc.
839  // auto fun = [bar = foo]() { ... }
840  // ~~~~~~~~~ VarDecl
841  // ~~~ |- AutoTypeLoc
842  if (const auto *DD = llvm::dyn_cast<VarDecl>(D))
843  return DD->getLocation();
844  }
845 
846  return SourceRange();
847  }
848 
849  // Claim tokens for N, after processing its children.
850  // By default this claims all unclaimed tokens in getSourceRange().
851  // We override this if we want to claim fewer tokens (e.g. there are gaps).
852  void claimTokensFor(const DynTypedNode &N, SelectionTree::Selection &Result) {
853  // CXXConstructExpr often shows implicit construction, like `string s;`.
854  // Don't associate any tokens with it unless there's some syntax like {}.
855  // This prevents it from claiming 's', its primary location.
856  if (const auto *CCE = N.get<CXXConstructExpr>()) {
857  claimRange(CCE->getParenOrBraceRange(), Result);
858  return;
859  }
860  // ExprWithCleanups is always implicit. It often wraps CXXConstructExpr.
861  // Prevent it claiming 's' in the case above.
862  if (N.get<ExprWithCleanups>())
863  return;
864 
865  // Declarators nest "inside out", with parent types inside child ones.
866  // Instead of claiming the whole range (clobbering parent tokens), carefully
867  // claim the tokens owned by this node and non-declarator children.
868  // (We could manipulate traversal order instead, but this is easier).
869  //
870  // Non-declarator types nest normally, and are handled like other nodes.
871  //
872  // Example:
873  // Vec<R<int>(*[2])(A<char>)> is a Vec of arrays of pointers to functions,
874  // which accept A<char> and return R<int>.
875  // The TypeLoc hierarchy:
876  // Vec<R<int>(*[2])(A<char>)> m;
877  // Vec<#####################> TemplateSpecialization Vec
878  // --------[2]---------- `-Array
879  // -------*------------- `-Pointer
880  // ------(----)--------- `-Paren
881  // ------------(#######) `-Function
882  // R<###> |-TemplateSpecialization R
883  // int | `-Builtin int
884  // A<####> `-TemplateSpecialization A
885  // char `-Builtin char
886  //
887  // In each row
888  // --- represents unclaimed parts of the SourceRange.
889  // ### represents parts that children already claimed.
890  if (const auto *TL = N.get<TypeLoc>()) {
891  if (auto PTL = TL->getAs<ParenTypeLoc>()) {
892  claimRange(PTL.getLParenLoc(), Result);
893  claimRange(PTL.getRParenLoc(), Result);
894  return;
895  }
896  if (auto ATL = TL->getAs<ArrayTypeLoc>()) {
897  claimRange(ATL.getBracketsRange(), Result);
898  return;
899  }
900  if (auto PTL = TL->getAs<PointerTypeLoc>()) {
901  claimRange(PTL.getStarLoc(), Result);
902  return;
903  }
904  if (auto FTL = TL->getAs<FunctionTypeLoc>()) {
905  claimRange(SourceRange(FTL.getLParenLoc(), FTL.getEndLoc()), Result);
906  return;
907  }
908  }
909  claimRange(getSourceRange(N), Result);
910  }
911 
912  // Perform hit-testing of a complete Node against the selection.
913  // This runs for every node in the AST, and must be fast in common cases.
914  // This is usually called from pop(), so we can take children into account.
915  // The existing state of Result is relevant.
916  void claimRange(SourceRange S, SelectionTree::Selection &Result) {
917  for (const auto &ClaimedRange :
918  UnclaimedExpandedTokens.erase(TokenBuf.expandedTokens(S)))
919  update(Result, SelChecker.test(ClaimedRange));
920 
921  if (Result && Result != NoTokens)
922  dlog("{1}hit selection: {0}", S.printToString(SM), indent());
923  }
924 
925  std::string indent(int Offset = 0) {
926  // Cast for signed arithmetic.
927  int Amount = int(Stack.size()) + Offset;
928  assert(Amount >= 0);
929  return std::string(Amount, ' ');
930  }
931 
932  SourceManager &SM;
933  const LangOptions &LangOpts;
934 #ifndef NDEBUG
935  const PrintingPolicy &PrintPolicy;
936 #endif
937  const syntax::TokenBuffer &TokenBuf;
938  std::stack<Node *> Stack;
939  SelectionTester SelChecker;
940  IntervalSet<syntax::Token> UnclaimedExpandedTokens;
941  std::deque<Node> Nodes; // Stable pointers as we add more nodes.
942 };
943 
944 } // namespace
945 
946 llvm::SmallString<256> abbreviatedString(DynTypedNode N,
947  const PrintingPolicy &PP) {
948  llvm::SmallString<256> Result;
949  {
950  llvm::raw_svector_ostream OS(Result);
951  N.print(OS, PP);
952  }
953  auto Pos = Result.find('\n');
954  if (Pos != llvm::StringRef::npos) {
955  bool MoreText = !llvm::all_of(Result.str().drop_front(Pos), llvm::isSpace);
956  Result.resize(Pos);
957  if (MoreText)
958  Result.append(" …");
959  }
960  return Result;
961 }
962 
963 void SelectionTree::print(llvm::raw_ostream &OS, const SelectionTree::Node &N,
964  int Indent) const {
965  if (N.Selected)
966  OS.indent(Indent - 1) << (N.Selected == SelectionTree::Complete ? '*'
967  : '.');
968  else
969  OS.indent(Indent);
970  printNodeKind(OS, N.ASTNode);
971  OS << ' ' << abbreviatedString(N.ASTNode, PrintPolicy) << "\n";
972  for (const Node *Child : N.Children)
973  print(OS, *Child, Indent + 2);
974 }
975 
976 std::string SelectionTree::Node::kind() const {
977  std::string S;
978  llvm::raw_string_ostream OS(S);
979  printNodeKind(OS, ASTNode);
980  return std::move(OS.str());
981 }
982 
983 // Decide which selections emulate a "point" query in between characters.
984 // If it's ambiguous (the neighboring characters are selectable tokens), returns
985 // both possibilities in preference order.
986 // Always returns at least one range - if no tokens touched, and empty range.
987 static llvm::SmallVector<std::pair<unsigned, unsigned>, 2>
988 pointBounds(unsigned Offset, const syntax::TokenBuffer &Tokens) {
989  const auto &SM = Tokens.sourceManager();
990  SourceLocation Loc = SM.getComposedLoc(SM.getMainFileID(), Offset);
991  llvm::SmallVector<std::pair<unsigned, unsigned>, 2> Result;
992  // Prefer right token over left.
993  for (const syntax::Token &Tok :
994  llvm::reverse(spelledTokensTouching(Loc, Tokens))) {
995  if (shouldIgnore(Tok))
996  continue;
997  unsigned Offset = Tokens.sourceManager().getFileOffset(Tok.location());
998  Result.emplace_back(Offset, Offset + Tok.length());
999  }
1000  if (Result.empty())
1001  Result.emplace_back(Offset, Offset);
1002  return Result;
1003 }
1004 
1005 bool SelectionTree::createEach(ASTContext &AST,
1006  const syntax::TokenBuffer &Tokens,
1007  unsigned Begin, unsigned End,
1008  llvm::function_ref<bool(SelectionTree)> Func) {
1009  if (Begin != End)
1010  return Func(SelectionTree(AST, Tokens, Begin, End));
1011  for (std::pair<unsigned, unsigned> Bounds : pointBounds(Begin, Tokens))
1012  if (Func(SelectionTree(AST, Tokens, Bounds.first, Bounds.second)))
1013  return true;
1014  return false;
1015 }
1016 
1018  const syntax::TokenBuffer &Tokens,
1019  unsigned int Begin, unsigned int End) {
1020  llvm::Optional<SelectionTree> Result;
1021  createEach(AST, Tokens, Begin, End, [&](SelectionTree T) {
1022  Result = std::move(T);
1023  return true;
1024  });
1025  return std::move(*Result);
1026 }
1027 
1028 SelectionTree::SelectionTree(ASTContext &AST, const syntax::TokenBuffer &Tokens,
1029  unsigned Begin, unsigned End)
1030  : PrintPolicy(AST.getLangOpts()) {
1031  // No fundamental reason the selection needs to be in the main file,
1032  // but that's all clangd has needed so far.
1033  const SourceManager &SM = AST.getSourceManager();
1034  FileID FID = SM.getMainFileID();
1035  PrintPolicy.TerseOutput = true;
1036  PrintPolicy.IncludeNewlines = false;
1037 
1038  dlog("Computing selection for {0}",
1039  SourceRange(SM.getComposedLoc(FID, Begin), SM.getComposedLoc(FID, End))
1040  .printToString(SM));
1041  Nodes = SelectionVisitor::collect(AST, Tokens, PrintPolicy, Begin, End, FID);
1042  Root = Nodes.empty() ? nullptr : &Nodes.front();
1043  recordMetrics(*this, AST.getLangOpts());
1044  dlog("Built selection tree\n{0}", *this);
1045 }
1046 
1048  const Node *Ancestor = Root;
1049  while (Ancestor->Children.size() == 1 && !Ancestor->Selected)
1050  Ancestor = Ancestor->Children.front();
1051  // Returning nullptr here is a bit unprincipled, but it makes the API safer:
1052  // the TranslationUnitDecl contains all of the preamble, so traversing it is a
1053  // performance cliff. Callers can check for null and use root() if they want.
1054  return Ancestor != Root ? Ancestor : nullptr;
1055 }
1056 
1057 const DeclContext &SelectionTree::Node::getDeclContext() const {
1058  for (const Node *CurrentNode = this; CurrentNode != nullptr;
1059  CurrentNode = CurrentNode->Parent) {
1060  if (const Decl *Current = CurrentNode->ASTNode.get<Decl>()) {
1061  if (CurrentNode != this)
1062  if (auto *DC = dyn_cast<DeclContext>(Current))
1063  return *DC;
1064  return *Current->getLexicalDeclContext();
1065  }
1066  }
1067  llvm_unreachable("A tree must always be rooted at TranslationUnitDecl.");
1068 }
1069 
1071  if (Children.size() == 1 &&
1072  getSourceRange(Children.front()->ASTNode) == getSourceRange(ASTNode))
1073  return Children.front()->ignoreImplicit();
1074  return *this;
1075 }
1076 
1078  if (Parent && getSourceRange(Parent->ASTNode) == getSourceRange(ASTNode))
1079  return Parent->outerImplicit();
1080  return *this;
1081 }
1082 
1083 } // namespace clangd
1084 } // namespace clang
dlog
#define dlog(...)
Definition: Logger.h:102
Range
CharSourceRange Range
SourceRange for the file name.
Definition: IncludeOrderCheck.cpp:38
Loc
SourceLocation Loc
Definition: KernelNameRestrictionCheck.cpp:45
Base
std::unique_ptr< GlobalCompilationDatabase > Base
Definition: GlobalCompilationDatabaseTests.cpp:89
clang::clangd::SelectionTree::Node::kind
std::string kind() const
Definition: Selection.cpp:976
RecursiveASTVisitor
Selection.h
E
const Expr * E
Definition: AvoidBindCheck.cpp:88
clang::clangd::SelectionTree::Node::ignoreImplicit
const Node & ignoreImplicit() const
Definition: Selection.cpp:1070
clang::clangd::SelectionTree::createEach
static bool createEach(ASTContext &AST, const syntax::TokenBuffer &Tokens, unsigned Begin, unsigned End, llvm::function_ref< bool(SelectionTree)> Func)
Definition: Selection.cpp:1005
clang::clangd::SelectionTree::Node::Selected
Selection Selected
Definition: Selection.h:130
clang::clangd::pointBounds
static llvm::SmallVector< std::pair< unsigned, unsigned >, 2 > pointBounds(unsigned Offset, const syntax::TokenBuffer &Tokens)
Definition: Selection.cpp:988
clang::clangd::X
static URISchemeRegistry::Add< TestScheme > X(TestScheme::Scheme, "Test schema")
Trace.h
Selected
SelectionTree::Selection Selected
Definition: Selection.cpp:523
clang::clangd::SelectionTree::Node::outerImplicit
const Node & outerImplicit() const
Definition: Selection.cpp:1077
Target
std::string Target
Definition: QueryDriverDatabase.cpp:64
clang::clangd::SelectionTree::Node::ASTNode
DynTypedNode ASTNode
Definition: Selection.h:128
clang::clangd::SelectionTree::Complete
@ Complete
Definition: Selection.h:118
test
Definition: test.py:1
Children
std::vector< std::unique_ptr< HTMLNode > > Children
Definition: HTMLGenerator.cpp:91
ns1::ns2::A
@ A
Definition: CategoricalFeature.h:3
ns1::ns2::D
@ D
Definition: CategoricalFeature.h:3
clang::clangd::SelectionTree::Node::Children
llvm::SmallVector< const Node * > Children
Definition: Selection.h:126
Offset
unsigned Offset
Definition: Selection.cpp:522
clang::clangd::abbreviatedString
llvm::SmallString< 256 > abbreviatedString(DynTypedNode N, const PrintingPolicy &PP)
Definition: Selection.cpp:946
Decl
const FunctionDecl * Decl
Definition: AvoidBindCheck.cpp:100
clang::clangd::SelectionTree::createRight
static SelectionTree createRight(ASTContext &AST, const syntax::TokenBuffer &Tokens, unsigned Begin, unsigned End)
Definition: Selection.cpp:1017
clang::clangd::trace::enabled
bool enabled()
Returns true if there is an active tracer.
Definition: Trace.cpp:284
Logger.h
Bounds
PreambleBounds Bounds
Definition: Preamble.cpp:240
clang::clangd::trace::Metric::Distribution
@ Distribution
A distribution of values with a meaningful mean and count.
Definition: Trace.h:52
clang::clangd::SelectionTree
Definition: Selection.h:76
clang::clangd::SelectionTree::Node
Definition: Selection.h:122
clang::tidy::bugprone::PP
static Preprocessor * PP
Definition: BadSignalToKillThreadCheck.cpp:29
clang::clangd::SelectionTree::Node::Parent
Node * Parent
Definition: Selection.h:124
Parent
const Node * Parent
Definition: ExtractFunction.cpp:152
clang::clangd::SelectionTree::commonAncestor
const Node * commonAncestor() const
Definition: Selection.cpp:1047
clang::clangd::SelectionTree::SelectionTree
SelectionTree(const SelectionTree &)=delete
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
OS
llvm::raw_string_ostream OS
Definition: TraceTests.cpp:163
clang::clangd::SelectionTree::Unselected
@ Unselected
Definition: Selection.h:114
Pos
Position Pos
Definition: SourceCode.cpp:657
clang::clangd::SelectionTree::Partial
@ Partial
Definition: Selection.h:116
ns1::ns2::B
@ B
Definition: CategoricalFeature.h:3
Out
CompiledFragmentImpl & Out
Definition: ConfigCompile.cpp:100
clang::clangd::getAttributes
std::vector< const Attr * > getAttributes(const DynTypedNode &N)
Return attributes attached directly to a node.
Definition: AST.cpp:504
clang::clangd::SelectionTree::Node::getDeclContext
const DeclContext & getDeclContext() const
Definition: Selection.cpp:1057
clang::clangd::ASTNode
Simplified description of a clang AST node.
Definition: Protocol.h:1782
AST.h
clang::clangd::SelectionTree::Selection
Selection
Definition: Selection.h:106