Skip to content

TypeCheckType: Unconditionally warn about missing existential any until a future language mode #78459

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

Merged
merged 3 commits into from
Feb 14, 2025
Merged
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 @@ -5580,12 +5580,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 @@ -27,6 +27,7 @@ GROUP(Unsafe, "Unsafe.md")
GROUP(UnknownWarningGroup, "UnknownWarningGroup.md")
GROUP(PreconcurrencyImport, "PreconcurrencyImport.md")
GROUP(StrictLanguageFeatures, "StrictLanguageFeatures.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 @@ -5839,11 +5839,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 @@ -6958,13 +6958,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
196 changes: 112 additions & 84 deletions lib/Sema/TypeCheckType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -907,11 +907,15 @@ static Type applyGenericArguments(Type type,
auto parameterized =
ParameterizedProtocolType::get(ctx, protoType, argTys);

// FIXME: Can this not be done in ExistentialTypeSyntaxChecker?
if (resolution.getOptions().isConstraintImplicitExistential() &&
!ctx.LangOpts.hasFeature(Feature::ImplicitSome)) {
diags.diagnose(loc, diag::existential_requires_any, parameterized,
ExistentialType::get(parameterized),
/*isAlias=*/isa<TypeAliasType>(type.getPointer()));
diags
.diagnose(loc, diag::existential_requires_any, parameterized,
ExistentialType::get(parameterized),
/*isAlias=*/isa<TypeAliasType>(type.getPointer()))
.warnUntilSwiftVersion(7);

return ErrorType::get(ctx);
}

Expand Down Expand Up @@ -6171,18 +6175,15 @@ namespace {
/// written syntax.
class ExistentialTypeSyntaxChecker : public ASTWalker {
ASTContext &Ctx;
bool checkStatements;
const bool checkStatements;
bool hitTopStmt;
bool warnUntilSwift7;

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

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

MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::ArgumentsAndExpansion;
Expand Down Expand Up @@ -6215,7 +6216,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 @@ -6339,14 +6340,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 @@ -6356,7 +6356,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 @@ -6365,84 +6365,119 @@ 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 bool shouldDiagnoseMissingAnyOrSomeKeyword(Type constraintTy,
bool isInverted,
ASTContext &ctx) {
// `Any` and `AnyObject` are always exempt from `any` syntax.
if (constraintTy->isAny() || constraintTy->isAnyObject()) {
return false;
}

if (Ctx.LangOpts.hasFeature(Feature::ImplicitSome)) {
return;
// A missing `any` or `some` is always diagnosed if this feature is enabled.
if (ctx.LangOpts.hasFeature(Feature::ExistentialAny)) {
return true;
}

// 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 it = reprStack.end() - 2;
while (it != reprStack.begin() &&
((*it)->isParenType() || isa<MetatypeTypeRepr>(*it))) {
--it;
continue;
// If the type is inverted, a missing `any` or `some` is always diagnosed.
if (isInverted) {
return true;
}

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

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;
// If one of the protocols has "Self or associated type" requirements,
// a missing `any` or `some` is always diagnosed.
auto layout = constraintTy->getExistentialLayout();
for (auto *protoDecl : layout.getProtocols()) {
if (protoDecl->hasSelfOrAssociatedTypeRequirements()) {
return true;
}
}

return false;
}

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

auto *decl = T->getBoundDecl();
if (!decl) {
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);
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;
}
} 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 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);
}
auto it = reprStack.end() - 2;
while (it != reprStack.begin() &&
((*it)->isParenType() || isa<MetatypeTypeRepr>(*it))) {
--it;
continue;
}

return dyn_cast<InverseTypeRepr>(*it);
}();

if (!shouldDiagnoseMissingAnyOrSomeKeyword(
type, /*isInverted=*/outerInversion, this->Ctx)) {
return;
}

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->warnUntilSwiftVersion(7);
emitInsertAnyFixit(*diag, T);
}

public:
Expand Down Expand Up @@ -6516,14 +6551,7 @@ void TypeChecker::checkExistentialTypes(ASTContext &ctx, Stmt *stmt,
if (DC->isInSwiftinterface())
return;

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

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

Expand Down
4 changes: 2 additions & 2 deletions test/Generics/inverse_generics.swift
Original file line number Diff line number Diff line change
Expand Up @@ -475,8 +475,8 @@ func checkExistentials() {

typealias NotCopyable = ~Copyable
typealias EmptyComposition = ~Copyable & ~Escapable
func test(_ t: borrowing NotCopyable) {} // expected-error {{use of 'NotCopyable' (aka '~Copyable') as a type must be written 'any NotCopyable'}}
func test(_ t: borrowing EmptyComposition) {} // expected-error {{use of 'EmptyComposition' (aka '~Copyable & ~Escapable') as a type must be written 'any EmptyComposition' (aka 'any ~Copyable & ~Escapable')}}
func test(_ t: borrowing NotCopyable) {} // expected-warning {{use of 'NotCopyable' (aka '~Copyable') as a type must be written 'any NotCopyable'}}
func test(_ t: borrowing EmptyComposition) {} // expected-warning {{use of 'EmptyComposition' (aka '~Copyable & ~Escapable') as a type must be written 'any EmptyComposition' (aka 'any ~Copyable & ~Escapable')}}

typealias Copy = Copyable
func test(_ z1: Copy, _ z2: Copyable) {}
Expand Down
4 changes: 2 additions & 2 deletions test/Macros/macros_diagnostics.swift
Original file line number Diff line number Diff line change
Expand Up @@ -196,8 +196,8 @@ struct MyStruct<T: MyProto> {

struct SomeType {
#genericUnary<Equatable>(0 as Hashable)
// expected-error@-1{{use of protocol 'Equatable' as a type must be written 'any Equatable'}}
// expected-error@-2{{use of protocol 'Hashable' as a type must be written 'any Hashable'}}
// expected-warning@-1{{use of protocol 'Equatable' as a type must be written 'any Equatable'}}
// expected-warning@-2{{use of protocol 'Hashable' as a type must be written 'any Hashable'}}
// expected-error@-3{{external macro implementation type}}
}

Expand Down
6 changes: 3 additions & 3 deletions test/Macros/top_level_freestanding.swift
Original file line number Diff line number Diff line change
Expand Up @@ -107,12 +107,12 @@ func testGlobalVariable() {

// expected-note @+1 6 {{in expansion of macro 'anonymousTypes' here}}
#anonymousTypes(causeErrors: true) { "foo" }
// DIAG_BUFFERS-DAG: @__swiftmacro_9MacroUser0033top_level_freestandingswift_DbGHjfMX108_0_33_082AE7CFEFA6960C804A9FE7366EB5A0Ll14anonymousTypesfMf0_{{.*}}: error: use of protocol 'Equatable' as a type must be written 'any Equatable'
// DIAG_BUFFERS-DAG: @__swiftmacro_9MacroUser00142___swiftmacro_9MacroUser0033top_level_freestandingswift_DbGHjfMX108_0_33_082AE7CFEFA6960C804A9FE7366EB5A0Ll14anonymousTypesfMf0_swift_DAIABdjIbfMX23_2_33_082AE7CFEFA6960C804A9FE7366EB5A0Ll27introduceTypeCheckingErrorsfMf_{{.*}}: error: use of protocol 'Hashable' as a type must be written 'any Hashable'
// DIAG_BUFFERS-DAG: @__swiftmacro_9MacroUser0033top_level_freestandingswift_DbGHjfMX108_0_33_082AE7CFEFA6960C804A9FE7366EB5A0Ll14anonymousTypesfMf0_{{.*}}: warning: use of protocol 'Equatable' as a type must be written 'any Equatable'
// DIAG_BUFFERS-DAG: @__swiftmacro_9MacroUser00142___swiftmacro_9MacroUser0033top_level_freestandingswift_DbGHjfMX108_0_33_082AE7CFEFA6960C804A9FE7366EB5A0Ll14anonymousTypesfMf0_swift_DAIABdjIbfMX23_2_33_082AE7CFEFA6960C804A9FE7366EB5A0Ll27introduceTypeCheckingErrorsfMf_{{.*}}: warning: use of protocol 'Hashable' as a type must be written 'any Hashable'

// expected-note @+1 2 {{in expansion of macro 'anonymousTypes' here}}
#anonymousTypes { () -> String in
// expected-error @+1 {{use of protocol 'Equatable' as a type must be written 'any Equatable'}}
// expected-warning @+1 {{use of protocol 'Equatable' as a type must be written 'any Equatable'}}
_ = 0 as Equatable
return "foo"
}
Expand Down
2 changes: 1 addition & 1 deletion test/decl/nested/protocol.swift
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ extension OuterProtocol {

struct ConformsToOuterProtocol : OuterProtocol {
typealias Hen = Int
func f() { let _ = InnerProtocol.self } // expected-error {{use of protocol 'InnerProtocol' as a type must be written 'any InnerProtocol'}}
func f() { let _ = InnerProtocol.self } // expected-warning {{use of protocol 'InnerProtocol' as a type must be written 'any InnerProtocol'}}
}

extension OuterProtocol {
Expand Down
Loading