- Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathASTScopeSourceRange.cpp
414 lines (351 loc) · 14 KB
/
ASTScopeSourceRange.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//===--- ASTScopeSourceRange.cpp - Swift Object-Oriented AST Scope --------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// This file implements the source range queries for the ASTScopeImpl ontology.
///
//===----------------------------------------------------------------------===//
#include"swift/AST/ASTScope.h"
#include"swift/AST/ASTContext.h"
#include"swift/AST/ASTWalker.h"
#include"swift/AST/Decl.h"
#include"swift/AST/Expr.h"
#include"swift/AST/GenericParamList.h"
#include"swift/AST/Initializer.h"
#include"swift/AST/LazyResolver.h"
#include"swift/AST/Module.h"
#include"swift/AST/ParameterList.h"
#include"swift/AST/Pattern.h"
#include"swift/AST/SourceFile.h"
#include"swift/AST/Stmt.h"
#include"swift/AST/TypeRepr.h"
#include"swift/Basic/Assertions.h"
#include"swift/Basic/STLExtras.h"
#include"swift/Parse/Lexer.h"
#include"llvm/Support/Compiler.h"
#include<algorithm>
usingnamespaceswift;
usingnamespaceast_scope;
static SourceLoc getLocAfterExtendedNominal(const ExtensionDecl *);
voidASTScopeImpl::checkSourceRangeBeforeAddingChild(ASTScopeImpl *child,
const ASTContext &ctx) const {
// Ignore attributes on extensions, currently they exist outside of the
// extension's source range due to the way we've setup the scope for
// extension binding.
// FIXME: We ought to fix the source range for extension scopes.
if (isa<ExtensionScope>(this) && child->isDeclAttribute())
return;
// Ignore debugger bindings - they're a special mix of user code and implicit
// wrapper code that is too difficult to check for consistency.
if (auto d = getDeclIfAny().getPtrOrNull())
if (auto *PBD = dyn_cast<PatternBindingDecl>(d))
if (PBD->isDebuggerBinding())
return;
auto &sourceMgr = ctx.SourceMgr;
auto range = getCharSourceRangeOfScope(sourceMgr);
auto containedInParent = [&](SourceRange childCharRange) {
// HACK: For code completion. Handle replaced range.
// Note that the replaced SourceRanges here are already disguised
// CharSourceRanges, we don't need to adjust them. We use `rangeContains`
// since we're only interested in comparing within a single buffer.
for (constauto &pair : sourceMgr.getReplacedRanges()) {
if (sourceMgr.rangeContains(range, pair.first) &&
sourceMgr.rangeContains(pair.second, childCharRange))
returntrue;
}
return sourceMgr.encloses(range, childCharRange);
};
auto childCharRange = child->getCharSourceRangeOfScope(sourceMgr);
if (!containedInParent(childCharRange)) {
abortWithVerificationError([&](llvm::raw_ostream &out) {
out << "child not contained in its parent:\n";
child->print(out);
out << "\n***Parent node***\n";
this->print(out);
});
}
if (!storedChildren.empty()) {
auto previousChild = storedChildren.back();
auto endOfPreviousChild = previousChild->getCharSourceRangeOfScope(
sourceMgr).End;
if (!sourceMgr.isAtOrBefore(endOfPreviousChild, childCharRange.Start)) {
abortWithVerificationError([&](llvm::raw_ostream &out) {
out << "child overlaps previous child:\n";
child->print(out);
out << "\n***Previous child\n";
previousChild->print(out);
out << "\n***Parent node***\n";
this->print(out);
});
}
}
}
#pragma mark getSourceRangeOfThisASTNode
SourceRange SpecializeAttributeScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
return specializeAttr->getRange();
}
SourceRange DifferentiableAttributeScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
return differentiableAttr->getRange();
}
SourceRange FunctionBodyScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
// If this function body scope is synthesized for a body macro, use the
// real source range.
if (getChildren().size() == 1 && isa<ASTSourceFileScope>(getChildren()[0])) {
return decl->getBodySourceRange();
}
return decl->getOriginalBodySourceRange();
}
SourceRange TopLevelCodeScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
returnSourceRange(decl->getStartLoc(), endLoc);
}
SourceRange SubscriptDeclScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
return decl->getSourceRangeIncludingAttrs();
}
SourceRange MacroDeclScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
return decl->getSourceRangeIncludingAttrs();
}
SourceRange MacroDefinitionScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
return definition->getSourceRange();
}
SourceRange MacroExpansionDeclScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
return decl->getSourceRangeIncludingAttrs();
}
SourceRange
EnumElementScope::getSourceRangeOfThisASTNode(constbool omitAssertions) const {
return decl->getSourceRange();
}
SourceRange AbstractStmtScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
returngetStmt()->getSourceRange();
}
SourceRange DefaultArgumentInitializerScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
return decl->getStructuralDefaultExpr()->getSourceRange();
}
SourceRange PatternEntryDeclScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
SourceRange range = getPatternEntry().getSourceRange();
if (endLoc.has_value())
range.End = *endLoc;
return range;
}
SourceRange PatternEntryInitializerScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
// TODO: Don't remove the initializer in the rest of the compiler:
// Search for "When the initializer is removed we don't actually clear the
// pointer" because we do!
return initAsWrittenWhenCreated->getSourceRange();
}
SourceRange GenericParamScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
// We want to ensure the extended type is not part of the generic
// parameter scope.
if (autoconst *const ext = dyn_cast<ExtensionDecl>(holder)) {
returnSourceRange(getLocAfterExtendedNominal(ext), ext->getEndLoc());
}
// For a variable, the generic parameter is visible throughout the pattern
// binding entry.
if (auto var = dyn_cast<VarDecl>(holder)) {
if (auto patternBinding = var->getParentPatternBinding()) {
unsignedindex = patternBinding->getPatternEntryIndexForVarDecl(var);
return patternBinding->getPatternList()[index].getSourceRange();
}
}
// For all other declarations, generic parameters are visible everywhere.
return holder->getSourceRange();
}
SourceRange ASTSourceFileScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
auto bufferID = SF->getBufferID();
auto charRange = getSourceManager().getRangeForBuffer(bufferID);
returnSourceRange(charRange.getStart(), charRange.getEnd());
}
SourceRange GenericTypeOrExtensionScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
return portion->getChildlessSourceRangeOf(this, omitAssertions);
}
SourceRange GenericTypeOrExtensionWholePortion::getChildlessSourceRangeOf(
const GenericTypeOrExtensionScope *scope, constbool omitAssertions) const {
auto *d = scope->getDecl();
auto r = d->getSourceRangeIncludingAttrs();
if (r.Start.isValid()) {
ASTScopeAssert(r.End.isValid(), "Start valid imples end valid.");
return scope->moveStartPastExtendedNominal(r);
}
return d->getSourceRange();
}
SourceRange
ExtensionScope::moveStartPastExtendedNominal(const SourceRange sr) const {
constauto afterExtendedNominal = getLocAfterExtendedNominal(decl);
// Illegal code can have an endLoc that is before the end of the
// ExtendedNominal
if (getSourceManager().isBeforeInBuffer(sr.End, afterExtendedNominal)) {
// Must not have the source range returned include the extended nominal
returnSourceRange(sr.Start, sr.Start);
}
returnSourceRange(afterExtendedNominal, sr.End);
}
SourceRange
GenericTypeScope::moveStartPastExtendedNominal(const SourceRange sr) const {
// There is no extended nominal
return sr;
}
SourceRange GenericTypeOrExtensionWherePortion::getChildlessSourceRangeOf(
const GenericTypeOrExtensionScope *scope, constbool omitAssertions) const {
return scope->getGenericContext()->getTrailingWhereClause()->getSourceRange();
}
SourceRange IterableTypeBodyPortion::getChildlessSourceRangeOf(
const GenericTypeOrExtensionScope *scope, constbool omitAssertions) const {
auto *d = scope->getDecl();
if (auto *nt = dyn_cast<NominalTypeDecl>(d))
return nt->getBraces();
if (auto *e = dyn_cast<ExtensionDecl>(d))
return e->getBraces();
if (omitAssertions)
returnSourceRange();
ASTScope_unreachable("No body!");
}
SourceRange AbstractFunctionDeclScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
// For a get/put accessor all of the parameters are implicit, so start
// them at the start location of the accessor.
auto r = decl->getSourceRangeIncludingAttrs();
if (r.Start.isValid()) {
ASTScopeAssert(r.End.isValid(), "Start valid imples end valid.");
return r;
}
return decl->getOriginalBodySourceRange();
}
SourceRange ParameterListScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
return params->getSourceRange();
}
SourceRange ForEachPatternScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
// The scope of the pattern extends from the 'where' expression (if present)
// until the end of the body.
if (stmt->getWhere())
returnSourceRange(stmt->getWhere()->getStartLoc(),
stmt->getBody()->getEndLoc());
// Otherwise, scope of the pattern covers the body.
return stmt->getBody()->getSourceRange();
}
SourceRange
CaseLabelItemScope::getSourceRangeOfThisASTNode(constbool omitAssertions) const {
return item.getGuardExpr()->getSourceRange();
}
SourceRange
CaseStmtBodyScope::getSourceRangeOfThisASTNode(constbool omitAssertions) const {
return stmt->getBody()->getSourceRange();
}
SourceRange
BraceStmtScope::getSourceRangeOfThisASTNode(constbool omitAssertions) const {
// The brace statements that represent closures start their scope at the
// 'in' keyword, when present.
if (auto anyClosure = parentClosureIfAny()) {
if (auto closure = dyn_cast<ClosureExpr>(parentClosureIfAny().get())) {
if (closure->getInLoc().isValid()) {
returnSourceRange(closure->getInLoc(), endLoc);
}
}
}
returnSourceRange(stmt->getStartLoc(), endLoc);
}
SourceRange ConditionalClauseInitializerScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
return initializer->getSourceRange();
}
SourceRange ConditionalClausePatternUseScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
returnSourceRange(sec.getInitializer()->getStartLoc(), endLoc);
}
SourceRange
CaptureListScope::getSourceRangeOfThisASTNode(constbool omitAssertions) const {
if (auto autoClosure = dyn_cast<AutoClosureExpr>(expr->getClosureBody())) {
return autoClosure->getSourceRange();
}
auto closureExpr = cast<ClosureExpr>(expr->getClosureBody());
if (!omitAssertions)
ASTScopeAssert(closureExpr->getInLoc().isValid(),
"We don't create these if no in loc");
returnSourceRange(closureExpr->getInLoc(), closureExpr->getEndLoc());
}
SourceRange ClosureParametersScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
if (auto autoClosure = dyn_cast<AutoClosureExpr>(closureExpr)) {
return autoClosure->getSourceRange();
}
auto explicitClosureExpr = cast<ClosureExpr>(closureExpr);
if (explicitClosureExpr->getInLoc().isValid()) {
returnSourceRange(explicitClosureExpr->getInLoc(),
explicitClosureExpr->getEndLoc());
}
return explicitClosureExpr->getSourceRange();
}
SourceRange CustomAttributeScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
return attr->getRange();
}
SourceRange ABIAttributeScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
return attr->getRange();
}
SourceRange GuardStmtScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
returnSourceRange(getStmt()->getStartLoc(), endLoc);
}
SourceRange GuardStmtBodyScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
return body->getSourceRange();
}
#pragma mark source range caching
SourceRange
ASTScopeImpl::getCharSourceRangeOfScope(SourceManager &SM,
bool omitAssertions) const {
if (!isCharSourceRangeCached()) {
auto range = getSourceRangeOfThisASTNode(omitAssertions);
ASTScopeAssert(range.isValid(), "scope has invalid source range");
ASTScopeAssert(SM.isBefore(range.Start, range.End) ||
range.Start == range.End,
"scope source range ends before start");
range.End = Lexer::getLocForEndOfToken(SM, range.End);
cachedCharSourceRange = range;
}
return *cachedCharSourceRange;
}
boolASTScopeImpl::isCharSourceRangeCached() const {
return cachedCharSourceRange.has_value();
}
SourceLoc getLocAfterExtendedNominal(const ExtensionDecl *const ext) {
constauto *const etr = ext->getExtendedTypeRepr();
if (!etr)
return ext->getStartLoc();
constauto &SM = ext->getASTContext().SourceMgr;
returnLexer::getCharSourceRangeFromSourceRange(SM, etr->getSourceRange())
.getEnd();
}
SourceLoc ast_scope::extractNearestSourceLoc(
std::tuple<ASTScopeImpl *, ScopeCreator *> scopeAndCreator) {
const ASTScopeImpl *scope = std::get<0>(scopeAndCreator);
return scope->getSourceRangeOfThisASTNode().Start;
}
SourceRange TryScope::getSourceRangeOfThisASTNode(
constbool omitAssertions) const {
returnSourceRange(expr->getStartLoc(), endLoc);
}