Files
swift-mirror/lib/Sema/DerivedConformanceCaseIterable.cpp
Robert Widmann 75207cbe23 Allow Deriving Type Witnesses Across Files
A recent change to witness matching in #32578 suddenly made the
following construction illegal:

// File1.swift
enum MyEnumInAnotherFile { /**/ }

// File2.swift
extension MyEnumInAnotherFile {
  static var allCases: [MyEnumInAnotherFile] { /**/ }
}

Because it was no longer possible to derive the type witness for
`AllCases`. This is because, when inference ran before synthesis, we
would use the value witness to pick out the type witness and thus had no
need for synthesis. Now that we run synthesis first, we ought to just
allow deriving type witnesses across files, but still ban deriving value
witnesses. In general, if you can utter a type in a different file to
extend it, you should be able to see the requirements necessary to
derive a default type witness.

rdar://66279278, rdar://66279375, rdar://66279384, rdar://66279415, rdar://66279503
2020-07-29 12:10:26 -07:00

129 lines
4.3 KiB
C++

//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements implicit derivation of the CaseIterable protocol.
//
//===----------------------------------------------------------------------===//
#include "TypeChecker.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Types.h"
#include "llvm/Support/raw_ostream.h"
#include "DerivedConformances.h"
using namespace swift;
/// Common preconditions for CaseIterable.
static bool canDeriveConformance(NominalTypeDecl *type) {
// The type must be an enum.
auto enumDecl = dyn_cast<EnumDecl>(type);
if (!enumDecl)
return false;
// "Simple" enums without availability attributes can derive
// a CaseIterable conformance.
//
// FIXME: Lift the availability restriction.
return !enumDecl->hasPotentiallyUnavailableCaseValue()
&& enumDecl->hasOnlyCasesWithoutAssociatedValues();
}
/// Derive the implementation of allCases for a "simple" no-payload enum.
std::pair<BraceStmt *, bool>
deriveCaseIterable_enum_getter(AbstractFunctionDecl *funcDecl, void *) {
auto *parentDC = funcDecl->getDeclContext();
auto *parentEnum = parentDC->getSelfEnumDecl();
auto enumTy = parentDC->getDeclaredTypeInContext();
auto &C = parentDC->getASTContext();
SmallVector<Expr *, 8> elExprs;
for (EnumElementDecl *elt : parentEnum->getAllElements()) {
auto *base = TypeExpr::createImplicit(enumTy, C);
auto *apply = new (C) MemberRefExpr(base, SourceLoc(),
elt, DeclNameLoc(), /*implicit*/true);
elExprs.push_back(apply);
}
auto *arrayExpr = ArrayExpr::create(C, SourceLoc(), elExprs, {}, SourceLoc());
auto *returnStmt = new (C) ReturnStmt(SourceLoc(), arrayExpr);
auto *body = BraceStmt::create(C, SourceLoc(), ASTNode(returnStmt),
SourceLoc());
return { body, /*isTypeChecked=*/false };
}
static ArraySliceType *computeAllCasesType(NominalTypeDecl *enumDecl) {
auto enumType = enumDecl->getDeclaredInterfaceType();
if (!enumType || enumType->hasError())
return nullptr;
return ArraySliceType::get(enumType);
}
static Type deriveCaseIterable_AllCases(DerivedConformance &derived) {
// enum SomeEnum : CaseIterable {
// @derived
// typealias AllCases = [SomeEnum]
// }
auto *rawInterfaceType = computeAllCasesType(cast<EnumDecl>(derived.Nominal));
return derived.getConformanceContext()->mapTypeIntoContext(rawInterfaceType);
}
ValueDecl *DerivedConformance::deriveCaseIterable(ValueDecl *requirement) {
// Conformance can't be synthesized in an extension.
if (checkAndDiagnoseDisallowedContext(requirement))
return nullptr;
// Check that we can actually derive CaseIterable for this type.
if (!canDeriveConformance(Nominal))
return nullptr;
// Build the necessary decl.
if (requirement->getBaseName() != Context.Id_allCases) {
requirement->diagnose(diag::broken_case_iterable_requirement);
return nullptr;
}
// Define the property.
auto *returnTy = computeAllCasesType(Nominal);
VarDecl *propDecl;
PatternBindingDecl *pbDecl;
std::tie(propDecl, pbDecl) =
declareDerivedProperty(Context.Id_allCases, returnTy, returnTy,
/*isStatic=*/true, /*isFinal=*/true);
// Define the getter.
auto *getterDecl = addGetterToReadOnlyDerivedProperty(propDecl, returnTy);
getterDecl->setBodySynthesizer(&deriveCaseIterable_enum_getter);
addMembersToConformanceContext({propDecl, pbDecl});
return propDecl;
}
Type DerivedConformance::deriveCaseIterable(AssociatedTypeDecl *assocType) {
// Check that we can actually derive CaseIterable for this type.
if (!canDeriveConformance(Nominal))
return nullptr;
if (assocType->getName() == Context.Id_AllCases) {
return deriveCaseIterable_AllCases(*this);
}
Context.Diags.diagnose(assocType->getLoc(),
diag::broken_case_iterable_requirement);
return nullptr;
}