Skip to content

TypeCheckType: Make ExistentialAny warn rather than error until Swift 7 #78347

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions include/swift/AST/Decl.h
Original file line number Diff line number Diff line change
Expand Up @@ -5542,12 +5542,6 @@ class ProtocolDecl final : public NominalTypeDecl {
/// value requirement.
bool hasSelfOrAssociatedTypeRequirements() const;

/// Determine whether an existential type constrained by this protocol must
/// be written using `any` syntax.
///
/// \Note This method takes language feature state into account.
bool existentialRequiresAny() const;

/// Returns a list of protocol requirements that must be assessed to
/// determine a concrete's conformance effect polymorphism kind.
PolymorphicEffectRequirementList getPolymorphicEffectRequirements(
Expand Down
1 change: 1 addition & 0 deletions include/swift/AST/DiagnosticGroups.def
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ GROUP(DeprecatedDeclaration, "DeprecatedDeclaration.md")
GROUP(Unsafe, "Unsafe.md")
GROUP(UnknownWarningGroup, "UnknownWarningGroup.md")
GROUP(PreconcurrencyImport, "PreconcurrencyImport.md")
GROUP(ExistentialAny, "ExistentialAny.md")

#define UNDEFINE_DIAGNOSTIC_GROUPS_MACROS
#include "swift/AST/DefineDiagnosticGroupsMacros.h"
11 changes: 6 additions & 5 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -5825,11 +5825,12 @@ ERROR(any_not_existential,none,
ERROR(incorrect_optional_any,none,
"optional 'any' type must be written %0",
(Type))
ERROR(existential_requires_any,none,
"use of %select{protocol |}2%0 as a type must be written %1",
(Type, Type, bool))
ERROR(inverse_requires_any,none,
"constraint that suppresses conformance requires 'any'", ())

GROUPED_ERROR(existential_requires_any,ExistentialAny,none,
"use of %select{protocol |}2%0 as a type must be written %1",
(Type, Type, bool))
GROUPED_ERROR(inverse_requires_any,ExistentialAny,none,
"constraint that suppresses conformance requires 'any'", ())

ERROR(nonisolated_mutable_storage,none,
"'nonisolated' cannot be applied to mutable stored properties",
Expand Down
7 changes: 0 additions & 7 deletions lib/AST/Decl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6884,13 +6884,6 @@ bool ProtocolDecl::hasSelfOrAssociatedTypeRequirements() const {
resultForCycle);
}

bool ProtocolDecl::existentialRequiresAny() const {
if (getASTContext().LangOpts.hasFeature(Feature::ExistentialAny))
return true;

return hasSelfOrAssociatedTypeRequirements();
}

ArrayRef<AssociatedTypeDecl *>
ProtocolDecl::getPrimaryAssociatedTypes() const {
return evaluateOrDefault(getASTContext().evaluator,
Expand Down
189 changes: 116 additions & 73 deletions lib/Sema/TypeCheckType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6161,18 +6161,18 @@ namespace {
/// written syntax.
class ExistentialTypeSyntaxChecker : public ASTWalker {
ASTContext &Ctx;
bool checkStatements;
const bool checkStatements;
bool hitTopStmt;
bool warnUntilSwift7;
const bool downgradeErrorsToWarnings;

unsigned exprCount = 0;
llvm::SmallVector<TypeRepr *, 4> reprStack;

public:
ExistentialTypeSyntaxChecker(ASTContext &ctx, bool checkStatements,
bool warnUntilSwift7 = false)
bool downgradeErrorsToWarnings = false)
: Ctx(ctx), checkStatements(checkStatements), hitTopStmt(false),
warnUntilSwift7(warnUntilSwift7) {}
downgradeErrorsToWarnings(downgradeErrorsToWarnings) {}

MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::ArgumentsAndExpansion;
Expand Down Expand Up @@ -6205,7 +6205,7 @@ class ExistentialTypeSyntaxChecker : public ASTWalker {
}

PostWalkAction walkToTypeReprPost(TypeRepr *T) override {
assert(reprStack.back() == T);
ASSERT(reprStack.back() == T);
reprStack.pop_back();
return Action::Continue();
}
Expand Down Expand Up @@ -6329,14 +6329,13 @@ class ExistentialTypeSyntaxChecker : public ASTWalker {
diag.fixItReplace(replacementT->getSourceRange(), fix);
}

/// Returns a Boolean value indicating whether the type representation being
/// visited, assuming it is a constraint type demanding `any` or `some`, is
/// missing either keyword.
bool isAnyOrSomeMissing() const {
assert(isa<DeclRefTypeRepr>(reprStack.back()));
/// Returns a Boolean value indicating whether the currently visited
/// `DeclRefTypeRepr` node has a `some` or `any` keyword that applies to it.
bool currentNodeHasAnyOrSomeKeyword() const {
ASSERT(isa<DeclRefTypeRepr>(reprStack.back()));

if (reprStack.size() < 2) {
return true;
return false;
}

auto it = reprStack.end() - 1;
Expand All @@ -6346,7 +6345,7 @@ class ExistentialTypeSyntaxChecker : public ASTWalker {
break;
}

// Look through parens, inverses, metatypes, and compositions.
// Look through parens, inverses, `.Type` metatypes, and compositions.
if ((*it)->isParenType() || isa<InverseTypeRepr>(*it) ||
isa<CompositionTypeRepr>(*it) || isa<MetatypeTypeRepr>(*it)) {
continue;
Expand All @@ -6355,84 +6354,128 @@ class ExistentialTypeSyntaxChecker : public ASTWalker {
break;
}

return !(isa<OpaqueReturnTypeRepr>(*it) || isa<ExistentialTypeRepr>(*it));
return isa<OpaqueReturnTypeRepr>(*it) || isa<ExistentialTypeRepr>(*it);
}

void checkDeclRefTypeRepr(DeclRefTypeRepr *T) const {
assert(!T->isInvalid());
/// Returns the behavior with which to diagnose a missing `any` or `some`
/// keyword.
///
/// \param constraintTy The constraint type that is missing the keyword.
/// \param isInverted Whether the constraint type is an object of an `~`
/// inversion.
static DiagnosticBehavior getDiagnosticBehaviorForMissingAnyOrSomeKeyword(
Type constraintTy, bool isInverted, ASTContext &ctx) {
// `Any` and `AnyObject` are always exempt from `any` syntax.
if (constraintTy->isAny() || constraintTy->isAnyObject()) {
return DiagnosticBehavior::Ignore;
}

// If the type is inverted, a missing `any` or `some` is an error.
if (isInverted) {
return DiagnosticBehavior::Error;
}

// If one of the protocols is inverted, a missing `any` or `some` is
// an error.
if (auto *PCT = constraintTy->getAs<ProtocolCompositionType>()) {
if (!PCT->getInverses().empty()) {
return DiagnosticBehavior::Error;
}
}

// If one of the protocols has "Self or associated type" requirements,
// a missing `any` or `some` is an error.
auto layout = constraintTy->getExistentialLayout();
for (auto *protoDecl : layout.getProtocols()) {
if (protoDecl->hasSelfOrAssociatedTypeRequirements()) {
return DiagnosticBehavior::Error;
}
}

if (ctx.LangOpts.hasFeature(Feature::ExistentialAny)) {
// For anything else, a missing `any` or `some` is a warning if this
// feature is enabled.
return DiagnosticBehavior::Warning;
}

return DiagnosticBehavior::Ignore;
}

void checkDeclRefTypeRepr(DeclRefTypeRepr *T) const {
if (Ctx.LangOpts.hasFeature(Feature::ImplicitSome)) {
return;
}

// Backtrack the stack, looking just through parentheses and metatypes. If
// we find an inverse (which always requires `any`), diagnose it specially.
if (reprStack.size() > 1) {
auto *decl = T->getBoundDecl();
if (!decl) {
return;
}

if (!isa<ProtocolDecl>(decl) && !isa<TypeAliasDecl>(decl)) {
return;
}

// If there is already an `any` or `some` that applies to this node,
// move on.
if (currentNodeHasAnyOrSomeKeyword()) {
return;
}

const auto type = decl->getDeclaredInterfaceType();

// A type alias may need to be prefixed with `any` only if it stands for a
// constraint type.
if (isa<TypeAliasDecl>(decl) && !type->isConstraintType()) {
return;
}

// First, consider the possibility of the current node being an object of
// an inversion, e.g. `~(Copyable)`.
// Climb up the stack, looking just through parentheses and `.Type`
// metatypes.
// If we find an inversion, we will diagnose it specially.
InverseTypeRepr *const outerInversion = [&] {
if (reprStack.size() < 2) {
return (InverseTypeRepr *)nullptr;
}

auto it = reprStack.end() - 2;
while (it != reprStack.begin() &&
((*it)->isParenType() || isa<MetatypeTypeRepr>(*it))) {
--it;
continue;
}

if (auto *inverse = dyn_cast<InverseTypeRepr>(*it);
inverse && isAnyOrSomeMissing()) {
auto diag = Ctx.Diags.diagnose(inverse->getTildeLoc(),
diag::inverse_requires_any);
diag.warnUntilSwiftVersionIf(warnUntilSwift7, 7);
emitInsertAnyFixit(diag, T);
return;
}
}
return dyn_cast<InverseTypeRepr>(*it);
}();

auto *decl = T->getBoundDecl();
if (!decl) {
DiagnosticBehavior behavior =
this->getDiagnosticBehaviorForMissingAnyOrSomeKeyword(
type, /*isInverted=*/outerInversion, this->Ctx);

if (behavior == DiagnosticBehavior::Ignore) {
return;
}

if (auto *proto = dyn_cast<ProtocolDecl>(decl)) {
if (proto->existentialRequiresAny() && isAnyOrSomeMissing()) {
auto diag =
Ctx.Diags.diagnose(T->getNameLoc(), diag::existential_requires_any,
proto->getDeclaredInterfaceType(),
proto->getDeclaredExistentialType(),
/*isAlias=*/false);
diag.warnUntilSwiftVersionIf(warnUntilSwift7, 7);
emitInsertAnyFixit(diag, T);
}
} else if (auto *alias = dyn_cast<TypeAliasDecl>(decl)) {
auto type = Type(alias->getDeclaredInterfaceType()->getDesugaredType());

// If this is a type alias to a constraint type, the type
// alias name must be prefixed with 'any' to be used as an
// existential type.
if (type->isConstraintType() && !type->isAny() && !type->isAnyObject()) {
bool diagnose = false;

// Look for protocol members that require 'any'.
auto layout = type->getExistentialLayout();
for (auto *protoDecl : layout.getProtocols()) {
if (protoDecl->existentialRequiresAny()) {
diagnose = true;
break;
}
}
// If we were asked to downgrade errors, respect it.
if (behavior == DiagnosticBehavior::Error &&
this->downgradeErrorsToWarnings) {
behavior = DiagnosticBehavior::Warning;
}

// If inverses are present, require 'any' too.
if (auto *PCT = type->getAs<ProtocolCompositionType>())
diagnose |= !PCT->getInverses().empty();

if (diagnose && isAnyOrSomeMissing()) {
auto diag = Ctx.Diags.diagnose(
T->getNameLoc(), diag::existential_requires_any,
alias->getDeclaredInterfaceType(),
ExistentialType::get(alias->getDeclaredInterfaceType()),
/*isAlias=*/true);
diag.warnUntilSwiftVersionIf(warnUntilSwift7, 7);
emitInsertAnyFixit(diag, T);
}
}
std::optional<InFlightDiagnostic> diag;
if (outerInversion) {
diag.emplace(Ctx.Diags.diagnose(outerInversion->getTildeLoc(),
diag::inverse_requires_any));
} else {
diag.emplace(Ctx.Diags.diagnose(T->getNameLoc(),
diag::existential_requires_any, type,
ExistentialType::get(type),
/*isAlias=*/isa<TypeAliasDecl>(decl)));
}

diag->limitBehaviorUntilSwiftVersion(behavior, 7);
emitInsertAnyFixit(*diag, T);
}

public:
Expand Down Expand Up @@ -6510,12 +6553,12 @@ void TypeChecker::checkExistentialTypes(ASTContext &ctx, Stmt *stmt,

// Previously we missed this diagnostic on 'catch' statements, downgrade
// to a warning until Swift 7.
auto downgradeUntilSwift7 = false;
auto downgradeErrorsToWarnings = false;
if (auto *CS = dyn_cast<CaseStmt>(stmt))
downgradeUntilSwift7 = CS->getParentKind() == CaseParentKind::DoCatch;
downgradeErrorsToWarnings = CS->getParentKind() == CaseParentKind::DoCatch;

ExistentialTypeSyntaxChecker checker(ctx, /*checkStatements=*/true,
downgradeUntilSwift7);
downgradeErrorsToWarnings);
stmt->walk(checker);
}

Expand Down
6 changes: 3 additions & 3 deletions test/decl/protocol/protocols.swift
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,9 @@ struct DoesNotConform : Up {
// Circular protocols

protocol CircleMiddle : CircleStart { func circle_middle() }
// expected-note@-1 3 {{protocol 'CircleMiddle' declared here}}
protocol CircleStart : CircleEnd { func circle_start() } // expected-error 3 {{protocol 'CircleStart' refines itself}}
protocol CircleEnd : CircleMiddle { func circle_end()} // expected-note 3 {{protocol 'CircleEnd' declared here}}
// expected-note@-1 2 {{protocol 'CircleMiddle' declared here}}
protocol CircleStart : CircleEnd { func circle_start() } // expected-error 2 {{protocol 'CircleStart' refines itself}}
protocol CircleEnd : CircleMiddle { func circle_end()} // expected-note 2 {{protocol 'CircleEnd' declared here}}

protocol CircleEntry : CircleTrivial { }
protocol CircleTrivial : CircleTrivial { } // expected-error {{protocol 'CircleTrivial' refines itself}}
Expand Down
25 changes: 15 additions & 10 deletions test/type/explicit_existential.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// RUN: %target-typecheck-verify-swift -verify-additional-prefix default-swift-mode-
// RUN: %target-typecheck-verify-swift -swift-version 6 -verify-additional-prefix swift-6-
// RUN: %target-typecheck-verify-swift -enable-upcoming-feature ExistentialAny -verify-additional-prefix explicit-any- -verify-additional-prefix default-swift-mode-
// RUN: %target-typecheck-verify-swift -enable-experimental-feature ExistentialAny -verify-additional-prefix explicit-any- -verify-additional-prefix default-swift-mode-
// RUN: %target-typecheck-verify-swift -print-diagnostic-groups -enable-upcoming-feature ExistentialAny -verify-additional-prefix explicit-any- -verify-additional-prefix default-swift-mode-
// RUN: %target-typecheck-verify-swift -print-diagnostic-groups -enable-experimental-feature ExistentialAny -verify-additional-prefix explicit-any- -verify-additional-prefix default-swift-mode-

// REQUIRES: swift_feature_ExistentialAny

Expand All @@ -18,8 +18,10 @@ protocol Bar {
}

class Bistro {
convenience init(_: Bar){ self.init()} // expected-explicit-any-error{{use of protocol 'Bar' as a type must be written 'any Bar'}}{{23-26=any Bar}}
class func returnBar() -> Bar {} // expected-explicit-any-error {{use of protocol 'Bar' as a type must be written 'any Bar'}}{{29-32=any Bar}}
convenience init(_: Bar){ self.init()}
// expected-explicit-any-warning@-1 {{use of protocol 'Bar' as a type must be written 'any Bar'; this will be an error in a future Swift language mode [ExistentialAny]}}{{23-26=any Bar}}
class func returnBar() -> Bar {}
// expected-explicit-any-warning@-1 {{use of protocol 'Bar' as a type must be written 'any Bar'; this will be an error in a future Swift language mode [ExistentialAny]}}{{29-32=any Bar}}
}

func useBarAsType(_ x: any Bar) {}
Expand Down Expand Up @@ -217,7 +219,8 @@ protocol RawRepresentable {
enum E1: RawRepresentable {
typealias RawValue = P1

var rawValue: P1 { // expected-explicit-any-error {{use of protocol 'P1' as a type must be written 'any P1'}}{{17-19=any P1}}
var rawValue: P1 {
// expected-explicit-any-warning@-1 {{use of protocol 'P1' as a type must be written 'any P1'; this will be an error in a future Swift language mode [ExistentialAny]}}{{17-19=any P1}}
return ConcreteComposition()
}
}
Expand Down Expand Up @@ -315,9 +318,9 @@ enum EE : Equatable, any Empty { // expected-error {{raw type 'any Empty' is not

// Protocols from a serialized module (the standard library).
do {
// expected-explicit-any-error@+1 {{use of protocol 'Decodable' as a type must be written 'any Decodable'}}
// expected-explicit-any-warning@+1 {{use of protocol 'Decodable' as a type must be written 'any Decodable'; this will be an error in a future Swift language mode [ExistentialAny]}}
let _: Decodable
// expected-explicit-any-error@+1 {{use of 'Codable' (aka 'Decodable & Encodable') as a type must be written 'any Codable' (aka 'any Decodable & Encodable')}}
// expected-explicit-any-warning@+1 {{use of 'Codable' (aka 'Decodable & Encodable') as a type must be written 'any Codable' (aka 'any Decodable & Encodable'); this will be an error in a future Swift language mode [ExistentialAny]}}
let _: Codable
}

Expand Down Expand Up @@ -543,7 +546,7 @@ func testEnumAssociatedValue() {
case c1((any HasAssoc) -> Void)
// expected-error@+1 {{use of protocol 'HasAssoc' as a type must be written 'any HasAssoc'}}
case c2((HasAssoc) -> Void)
// expected-explicit-any-error@+1 {{use of protocol 'P' as a type must be written 'any P'}}
// expected-explicit-any-warning@+1 {{use of protocol 'P' as a type must be written 'any P'; this will be an error in a future Swift language mode [ExistentialAny]}}
case c3((P) -> Void)
}
}
Expand All @@ -568,5 +571,7 @@ typealias Objectlike = AnyObject
func f(_ x: Objectlike) {}

typealias Copy = Copyable
func h(_ z1: Copy, // expected-explicit-any-error {{use of 'Copy' (aka 'Copyable') as a type must be written 'any Copy' (aka 'any Copyable')}}
_ z2: Copyable) {} // expected-explicit-any-error {{use of protocol 'Copyable' as a type must be written 'any Copyable'}}
func h(_ z1: Copy,
// expected-explicit-any-warning@-1 {{use of 'Copy' (aka 'Copyable') as a type must be written 'any Copy' (aka 'any Copyable'); this will be an error in a future Swift language mode [ExistentialAny]}}
_ z2: Copyable) {}
// expected-explicit-any-warning@-1 {{use of protocol 'Copyable' as a type must be written 'any Copyable'; this will be an error in a future Swift language mode [ExistentialAny]}}
Loading