annotate clang-tools-extra/clangd/Selection.cpp @ 150:1d019706d866

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