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
|
//===--- ASTScopeImpl.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 common functions of the 49 ontology.
///
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTScope.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTWalker.h"
#include "swift/Bridging/ASTGen.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.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/NullablePtr.h"
#include "swift/Basic/STLExtras.h"
#include "llvm/Support/Compiler.h"
#include <algorithm>
using namespace swift;
using namespace ast_scope;
#pragma mark ASTScope
class LoggingASTScopeDeclConsumer
: public namelookup::AbstractASTScopeDeclConsumer {
private:
const int shouldLookInMembers = 0b10;
namelookup::AbstractASTScopeDeclConsumer *originalConsumer;
public:
mutable SmallVector<BridgedConsumedLookupResult> recordedElements;
LoggingASTScopeDeclConsumer(
namelookup::AbstractASTScopeDeclConsumer *consumer)
: originalConsumer(consumer) {}
~LoggingASTScopeDeclConsumer() = default;
/// Called for every ValueDecl visible from the lookup.
///
/// Takes an array in order to batch the consumption before setting
/// IndexOfFirstOuterResult when necessary.
///
/// Additionally, each name is logged to `recordedElements` and
/// can be later used in validation of `SwiftLexicalLookup` result.
///
/// \param baseDC either a type context or the local context of a
/// `self` parameter declaration. See LookupResult for a discussion
/// of type -vs- instance lookup results.
///
/// \return true if the lookup should be stopped at this point.
bool consume(ArrayRef<ValueDecl *> values,
NullablePtr<DeclContext> baseDC = nullptr) override {
bool endOfLookup = originalConsumer->consume(values, baseDC);
for (auto value : values) {
if (auto sourceLoc = value->getLoc()) {
recordedElements.push_back(BridgedConsumedLookupResult(
value->getBaseIdentifier(), sourceLoc, endOfLookup));
} else {
// If sourceLoc is unavailable, use location of it's parent.
recordedElements.push_back(BridgedConsumedLookupResult(
value->getBaseIdentifier(),
value->getDeclContext()->getAsDecl()->getLoc(), endOfLookup));
}
}
return endOfLookup;
};
/// Look for members of a nominal type or extension scope.
///
/// Each call is recorded in `recordedElements` with a special flag set.
/// It can be later used in validation of `SwiftLexicalLookup` result.
///
/// \return true if the lookup should be stopped at this point.
bool lookInMembers(const DeclContext *scopeDC) const override {
bool endOfLookup = originalConsumer->lookInMembers(scopeDC);
if (auto *extDecl = dyn_cast<ExtensionDecl>(scopeDC)) {
recordedElements.push_back(BridgedConsumedLookupResult(
Identifier(), extDecl->getExtendedTypeRepr()->getLoc(),
shouldLookInMembers + endOfLookup));
} else {
recordedElements.push_back(BridgedConsumedLookupResult(
scopeDC->getSelfNominalTypeDecl()->getBaseIdentifier(),
scopeDC->getAsDecl()->getLoc(), shouldLookInMembers + endOfLookup));
}
return endOfLookup;
};
/// Called for local VarDecls that might not yet be in scope.
///
/// Note that the set of VarDecls visited here are going to be a
/// superset of those visited in consume().
bool consumePossiblyNotInScope(ArrayRef<VarDecl *> values) override {
bool result = originalConsumer->consumePossiblyNotInScope(values);
return result;
}
/// Called right before looking at the parent scope of a BraceStmt.
///
/// \return true if the lookup should be stopped at this point.
bool finishLookupInBraceStmt(BraceStmt *stmt) override {
return originalConsumer->finishLookupInBraceStmt(stmt);
}
#ifndef NDEBUG
void startingNextLookupStep() override {
originalConsumer->startingNextLookupStep();
}
void finishingLookup(std::string input) const override {
originalConsumer->finishingLookup(input);
}
bool isTargetLookup() const override {
return originalConsumer->isTargetLookup();
}
#endif
};
void ASTScope::unqualifiedLookup(
SourceFile *SF, SourceLoc loc,
namelookup::AbstractASTScopeDeclConsumer &consumer) {
if (loc.isValid()) {
SF = SF->getParentModule()->getSourceFileContainingLocation(loc);
}
if (auto *s = SF->getASTContext().Stats)
++s->getFrontendCounters().NumASTScopeLookups;
#if SWIFT_BUILD_SWIFT_SYNTAX
// Perform validation of SwiftLexicalLookup if option
// Feature::UnqualifiedLookupValidation is enabled and lookup was not
// performed in a macro.
if (SF->getASTContext().LangOpts.hasFeature(
Feature::UnqualifiedLookupValidation) &&
!SF->getEnclosingSourceFile()) {
LoggingASTScopeDeclConsumer loggingASTScopeDeclConsumer =
LoggingASTScopeDeclConsumer(&consumer);
ASTScopeImpl::unqualifiedLookup(SF, loc, loggingASTScopeDeclConsumer);
bool passed = swift_ASTGen_validateUnqualifiedLookup(
SF->getExportedSourceFile(), SF->getASTContext(), loc,
loggingASTScopeDeclConsumer.finishLookupInBraceStmt(nullptr),
BridgedArrayRef(loggingASTScopeDeclConsumer.recordedElements.data(),
loggingASTScopeDeclConsumer.recordedElements.size()));
if (!passed) {
SF->getASTContext().Diags.diagnose(loc, diag::lookup_outputs_dont_match);
}
} else {
ASTScopeImpl::unqualifiedLookup(SF, loc, consumer);
}
#else
ASTScopeImpl::unqualifiedLookup(SF, loc, consumer);
#endif
}
llvm::SmallVector<LabeledStmt *, 4> ASTScope::lookupLabeledStmts(
SourceFile *sourceFile, SourceLoc loc) {
return ASTScopeImpl::lookupLabeledStmts(sourceFile, loc);
}
std::pair<CaseStmt *, CaseStmt *> ASTScope::lookupFallthroughSourceAndDest(
SourceFile *sourceFile, SourceLoc loc) {
return ASTScopeImpl::lookupFallthroughSourceAndDest(sourceFile, loc);
}
void ASTScope::lookupEnclosingMacroScope(
SourceFile *sourceFile, SourceLoc loc,
llvm::function_ref<bool(PotentialMacro)> body) {
return ASTScopeImpl::lookupEnclosingMacroScope(sourceFile, loc, body);
}
ABIAttr *ASTScope::lookupEnclosingABIAttributeScope(
SourceFile *sourceFile, SourceLoc loc) {
return ASTScopeImpl::lookupEnclosingABIAttributeScope(sourceFile, loc);
}
CatchNode ASTScope::lookupCatchNode(ModuleDecl *module, SourceLoc loc) {
return ASTScopeImpl::lookupCatchNode(module, loc);
}
#if SWIFT_COMPILER_IS_MSVC
#pragma warning(supress: 4996)
#endif
void ASTScope::dump() const { impl->dump(); }
void ASTScope::print(llvm::raw_ostream &out) const { impl->print(out); }
void ASTScope::dumpOneScopeMapLocation(std::pair<unsigned, unsigned> lineCol) {
impl->dumpOneScopeMapLocation(lineCol);
}
#pragma mark ASTScopeImpl
const PatternBindingEntry &AbstractPatternEntryScope::getPatternEntry() const {
return decl->getPatternList()[patternEntryIndex];
}
Pattern *AbstractPatternEntryScope::getPattern() const {
return getPatternEntry().getPattern();
}
NullablePtr<AbstractClosureExpr> BraceStmtScope::parentClosureIfAny() const {
if (auto parent = getParent()) {
if (auto closureScope = dyn_cast<ClosureParametersScope>(parent.get()))
return closureScope->closureExpr;
}
return nullptr;
}
std::string ASTScopeImpl::getClassName() const {
// GenericTypeOrExtensionScope provides a custom implementation that deals
// with declaration names and "portions".
if (auto generic = dyn_cast<GenericTypeOrExtensionScope>(this))
return generic->getClassName();
switch (getKind()) {
#define SCOPE_NODE(Name) case ScopeKind::Name: return #Name "Scope";
#include "swift/AST/ASTScopeNodes.def"
}
}
std::string GenericTypeOrExtensionScope::getClassName() const {
return declKindName() + portionName() + "Scope";
}
NullablePtr<Decl> ASTScopeImpl::getDeclIfAny() const {
switch (getKind()) {
// Declaration scope nodes extract the decl directly.
#define DECL_SCOPE_NODE(Name) \
case ScopeKind::Name: return cast<Name##Scope>(this)->getDecl();
#define SCOPE_NODE(Name)
#include "swift/AST/ASTScopeNodes.def"
// Everything else returns nullptr.
#define DECL_SCOPE_NODE(Name)
#define SCOPE_NODE(Name) case ScopeKind::Name:
#include "swift/AST/ASTScopeNodes.def"
return nullptr;
}
}
NullablePtr<Stmt> ASTScopeImpl::getStmtIfAny() const {
switch (getKind()) {
// Statement scope nodes extract the statement directly.
#define STMT_SCOPE_NODE(Name) \
case ScopeKind::Name: return cast<Name##Scope>(this)->getStmt();
#define SCOPE_NODE(Name)
#include "swift/AST/ASTScopeNodes.def"
// Everything else returns nullptr.
#define STMT_SCOPE_NODE(Name)
#define SCOPE_NODE(Name) case ScopeKind::Name:
#include "swift/AST/ASTScopeNodes.def"
return nullptr;
}
}
NullablePtr<Expr> ASTScopeImpl::getExprIfAny() const {
switch (getKind()) {
// Expression scope nodes extract the statement directly.
#define EXPR_SCOPE_NODE(Name) \
case ScopeKind::Name: return cast<Name##Scope>(this)->getExpr();
#define SCOPE_NODE(Name)
#include "swift/AST/ASTScopeNodes.def"
// Everything else returns nullptr.
#define EXPR_SCOPE_NODE(Name)
#define SCOPE_NODE(Name) case ScopeKind::Name:
#include "swift/AST/ASTScopeNodes.def"
return nullptr;
}
}
bool ASTScopeImpl::isDeclAttribute() const {
switch (getKind()) {
#define DECL_ATTRIBUTE_SCOPE_NODE(Name) \
case ScopeKind::Name: return true;
#define SCOPE_NODE(Name)
#include "swift/AST/ASTScopeNodes.def"
#define DECL_ATTRIBUTE_SCOPE_NODE(Name)
#define SCOPE_NODE(Name) case ScopeKind::Name:
#include "swift/AST/ASTScopeNodes.def"
return false;
}
}
SourceManager &ASTScopeImpl::getSourceManager() const {
return getASTContext().SourceMgr;
}
Stmt *LabeledConditionalStmtScope::getStmt() const {
return getLabeledConditionalStmt();
}
#pragma mark getLabeledConditionalStmt
LabeledConditionalStmt *IfStmtScope::getLabeledConditionalStmt() const {
return stmt;
}
LabeledConditionalStmt *WhileStmtScope::getLabeledConditionalStmt() const {
return stmt;
}
LabeledConditionalStmt *GuardStmtScope::getLabeledConditionalStmt() const {
return stmt;
}
#pragma mark getASTContext
ASTContext &ASTScopeImpl::getASTContext() const {
if (auto d = getDeclIfAny())
return d.get()->getASTContext();
if (auto sfScope = dyn_cast<ASTSourceFileScope>(this))
return sfScope->SF->getASTContext();
return getParent().get()->getASTContext();
}
#pragma mark getSourceFile
const SourceFile *ASTScopeImpl::getSourceFile() const {
if (auto sourceFileScope = dyn_cast<ASTSourceFileScope>(this))
return sourceFileScope->SF;
return getParent().get()->getSourceFile();
}
SourceRange ExtensionScope::getBraces() const { return decl->getBraces(); }
SourceRange NominalTypeScope::getBraces() const { return decl->getBraces(); }
NullablePtr<NominalTypeDecl>
ExtensionScope::getCorrespondingNominalTypeDecl() const {
return decl->getExtendedNominal();
}
void ASTScopeImpl::preOrderDo(function_ref<void(ASTScopeImpl *)> fn) {
fn(this);
preOrderChildrenDo(fn);
}
void ASTScopeImpl::preOrderChildrenDo(function_ref<void(ASTScopeImpl *)> fn) {
for (auto *child : getChildren())
child->preOrderDo(fn);
}
void ASTScopeImpl::postOrderDo(function_ref<void(ASTScopeImpl *)> fn) {
for (auto *child : getChildren())
child->postOrderDo(fn);
fn(this);
}
|