Skip to content

[AST/Sema] Add @extensible attribute on enum declarations #80503

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 2 commits into from
Apr 4, 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
7 changes: 2 additions & 5 deletions include/swift/AST/Decl.h
Original file line number Diff line number Diff line change
Expand Up @@ -735,7 +735,7 @@ class alignas(1 << DeclAlignInBits) Decl : public ASTAllocated<Decl>, public Swi
HasAnyUnavailableDuringLoweringValues : 1
);

SWIFT_INLINE_BITFIELD(ModuleDecl, TypeDecl, 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+8,
SWIFT_INLINE_BITFIELD(ModuleDecl, TypeDecl, 1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+8,
/// If the module is compiled as static library.
StaticLibrary : 1,

Expand Down Expand Up @@ -804,10 +804,7 @@ class alignas(1 << DeclAlignInBits) Decl : public ASTAllocated<Decl>, public Swi
SerializePackageEnabled : 1,

/// Whether this module has enabled strict memory safety checking.
StrictMemorySafety : 1,

/// Whether this module has enabled `ExtensibleEnums` feature.
ExtensibleEnums : 1
StrictMemorySafety : 1
);

SWIFT_INLINE_BITFIELD(PrecedenceGroupDecl, Decl, 1+2,
Expand Down
7 changes: 6 additions & 1 deletion include/swift/AST/DeclAttr.def
Original file line number Diff line number Diff line change
Expand Up @@ -879,7 +879,12 @@ SIMPLE_DECL_ATTR(constInitialized, ConstInitialized,
168)
DECL_ATTR_FEATURE_REQUIREMENT(ConstInitialized, CompileTimeValues)

LAST_DECL_ATTR(ConstInitialized)
SIMPLE_DECL_ATTR(extensible, Extensible,
OnEnum,
ABIStableToAdd | ABIStableToRemove | APIBreakingToAdd | APIStableToRemove | ForbiddenInABIAttr,
169)

LAST_DECL_ATTR(Extensible)

#undef DECL_ATTR_ALIAS
#undef CONTEXTUAL_DECL_ATTR_ALIAS
Expand Down
13 changes: 13 additions & 0 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -8572,6 +8572,19 @@ GROUPED_WARNING(
"behavior",
(StringRef, DeclAttribute))

//===----------------------------------------------------------------------===//
// MARK: @extensible Attribute
//===----------------------------------------------------------------------===//

ERROR(extensible_attr_on_frozen_type,none,
"cannot use '@extensible' together with '@frozen'", ())

ERROR(extensible_attr_on_internal_type,none,
"'@extensible' attribute can only be applied to public or package "
"declarations, but %0 is "
"%select{private|fileprivate|internal|%error|%error|%error}1",
(DeclName, AccessLevel))

//===----------------------------------------------------------------------===//
// MARK: SwiftSettings
//===----------------------------------------------------------------------===//
Expand Down
8 changes: 0 additions & 8 deletions include/swift/AST/Module.h
Original file line number Diff line number Diff line change
Expand Up @@ -840,14 +840,6 @@ class ModuleDecl
Bits.ModuleDecl.ObjCNameLookupCachePopulated = value;
}

bool supportsExtensibleEnums() const {
return Bits.ModuleDecl.ExtensibleEnums;
}

void setSupportsExtensibleEnums(bool value = true) {
Bits.ModuleDecl.ExtensibleEnums = value;
}

/// For the main module, retrieves the list of primary source files being
/// compiled, that is, the files we're generating code for.
ArrayRef<SourceFile *> getPrimarySourceFiles() const;
Expand Down
5 changes: 0 additions & 5 deletions include/swift/Basic/Features.def
Original file line number Diff line number Diff line change
Expand Up @@ -492,11 +492,6 @@ ADOPTABLE_EXPERIMENTAL_FEATURE(AsyncCallerExecution, false)
/// Allow custom availability domains to be defined and referenced.
SUPPRESSIBLE_EXPERIMENTAL_FEATURE(CustomAvailability, true)

/// Allow public enumerations to be extensible by default
/// regardless of whether the module they are declared in
/// is resilient or not.
EXPERIMENTAL_FEATURE(ExtensibleEnums, true)

/// Allow isolated conformances.
EXPERIMENTAL_FEATURE(IsolatedConformances, true)

Expand Down
6 changes: 0 additions & 6 deletions include/swift/Serialization/Validation.h
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,6 @@ class ExtendedValidationInfo {
unsigned AllowNonResilientAccess: 1;
unsigned SerializePackageEnabled: 1;
unsigned StrictMemorySafety: 1;
unsigned SupportsExtensibleEnums : 1;
} Bits;

public:
Expand Down Expand Up @@ -272,11 +271,6 @@ class ExtendedValidationInfo {
version, SourceLoc(), /*Diags=*/nullptr))
SwiftInterfaceCompilerVersion = genericVersion.value();
}

bool supportsExtensibleEnums() const { return Bits.SupportsExtensibleEnums; }
void setSupportsExtensibleEnums(bool val) {
Bits.SupportsExtensibleEnums = val;
}
};

struct SearchPath {
Expand Down
1 change: 1 addition & 0 deletions lib/AST/ASTDumper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4925,6 +4925,7 @@ class PrintAttribute : public AttributeVisitor<PrintAttribute, void, Label>,
TRIVIAL_ATTR_PRINTER(Used, used)
TRIVIAL_ATTR_PRINTER(WarnUnqualifiedAccess, warn_unqualified_access)
TRIVIAL_ATTR_PRINTER(WeakLinked, weak_linked)
TRIVIAL_ATTR_PRINTER(Extensible, extensible)

#undef TRIVIAL_ATTR_PRINTER

Expand Down
1 change: 1 addition & 0 deletions lib/AST/ASTPrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,7 @@ PrintOptions PrintOptions::printSwiftInterfaceFile(ModuleDecl *ModuleToPrint,
DeclAttrKind::RestatedObjCConformance,
DeclAttrKind::NonSendable,
DeclAttrKind::AllowFeatureSuppression,
DeclAttrKind::Extensible,
};

return result;
Expand Down
13 changes: 5 additions & 8 deletions lib/AST/Decl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6854,14 +6854,11 @@ bool EnumDecl::treatAsExhaustiveForDiags(const DeclContext *useDC) const {
if (enumModule->inSamePackage(useDC->getParentModule()))
return true;

// If the module where enum is declared supports extensible enumerations
// and this enum is not explicitly marked as "@frozen", cross-module
// access cannot be exhaustive and requires `@unknown default:`.
if (enumModule->supportsExtensibleEnums() &&
!getAttrs().hasAttribute<FrozenAttr>()) {
if (useDC != enumModule->getDeclContext())
return false;
}
// When the enum is marked as `@extensible` cross-module access
// cannot be exhaustive and requires `@unknown default:`.
if (getAttrs().hasAttribute<ExtensibleAttr>() &&
enumModule != useDC->getParentModule())
return false;
}

return isFormallyExhaustive(useDC);
Expand Down
1 change: 0 additions & 1 deletion lib/AST/FeatureSet.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,6 @@ UNINTERESTING_FEATURE(SuppressedAssociatedTypes)
UNINTERESTING_FEATURE(StructLetDestructuring)
UNINTERESTING_FEATURE(MacrosOnImports)
UNINTERESTING_FEATURE(AsyncCallerExecution)
UNINTERESTING_FEATURE(ExtensibleEnums)
UNINTERESTING_FEATURE(KeyPathWithMethodMembers)

static bool usesFeatureNonescapableTypes(Decl *decl) {
Expand Down
1 change: 1 addition & 0 deletions lib/ASTGen/Sources/ASTGen/DeclAttrs.swift
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ extension ASTGenVisitor {
.dynamicCallable,
.eagerMove,
.exported,
.extensible,
.discardableResult,
.disfavoredOverload,
.dynamicMemberLookup,
Expand Down
2 changes: 0 additions & 2 deletions lib/Frontend/Frontend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1469,8 +1469,6 @@ ModuleDecl *CompilerInstance::getMainModule() const {
MainModule->setSerializePackageEnabled();
if (Invocation.getLangOptions().hasFeature(Feature::StrictMemorySafety))
MainModule->setStrictMemorySafety(true);
if (Invocation.getLangOptions().hasFeature(Feature::ExtensibleEnums))
MainModule->setSupportsExtensibleEnums(true);

configureAvailabilityDomains(getASTContext(),
Invocation.getFrontendOptions(), MainModule);
Expand Down
15 changes: 15 additions & 0 deletions lib/Sema/TypeCheckAttr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,21 @@ class AttributeChecker : public AttributeVisitor<AttributeChecker> {
}
}

void visitExtensibleAttr(ExtensibleAttr *attr) {
auto *E = cast<EnumDecl>(D);

if (D->getAttrs().hasAttribute<FrozenAttr>()) {
diagnoseAndRemoveAttr(attr, diag::extensible_attr_on_frozen_type);
return;
}

if (E->getFormalAccess() < AccessLevel::Package) {
diagnoseAndRemoveAttr(attr, diag::extensible_attr_on_internal_type,
E->getName(), E->getFormalAccess());
return;
}
}

void visitAlignmentAttr(AlignmentAttr *attr) {
// Alignment must be a power of two.
auto value = attr->getValue();
Expand Down
1 change: 1 addition & 0 deletions lib/Sema/TypeCheckDeclOverride.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1615,6 +1615,7 @@ namespace {
UNINTERESTING_ATTR(Isolated)
UNINTERESTING_ATTR(Optimize)
UNINTERESTING_ATTR(Exclusivity)
UNINTERESTING_ATTR(Extensible)
UNINTERESTING_ATTR(NoLocks)
UNINTERESTING_ATTR(NoAllocation)
UNINTERESTING_ATTR(NoRuntime)
Expand Down
5 changes: 1 addition & 4 deletions lib/Sema/TypeCheckSwitchStmt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1159,10 +1159,7 @@ namespace {
auto *enumModule = theEnum->getParentModule();
shouldIncludeFutureVersionComment =
enumModule->isSystemModule() ||
enumModule->supportsExtensibleEnums();
// Since the module enabled `ExtensibleEnums` feature they
// opted-in all of their clients into exhaustivity errors.
shouldDowngradeToWarning = !enumModule->supportsExtensibleEnums();
theEnum->getAttrs().hasAttribute<ExtensibleAttr>();
}
DE.diagnose(startLoc, diag::non_exhaustive_switch_unknown_only,
subjectType, shouldIncludeFutureVersionComment)
Expand Down
5 changes: 0 additions & 5 deletions lib/Serialization/ModuleFile.h
Original file line number Diff line number Diff line change
Expand Up @@ -714,11 +714,6 @@ class ModuleFile
/// \c true if this module was built with strict memory safety.
bool strictMemorySafety() const { return Core->strictMemorySafety(); }

/// \c true if this module was built with `ExtensibleEnums` feature enabled.
bool supportsExtensibleEnums() const {
return Core->supportsExtensibleEnums();
}

/// Associates this module file with the AST node representing it.
///
/// Checks that the file is compatible with the AST module it's being loaded
Expand Down
4 changes: 0 additions & 4 deletions lib/Serialization/ModuleFileSharedCore.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -224,9 +224,6 @@ static bool readOptionsBlock(llvm::BitstreamCursor &cursor,
case options_block::STRICT_MEMORY_SAFETY:
extendedInfo.setStrictMemorySafety(true);
break;
case options_block::EXTENSIBLE_ENUMS:
extendedInfo.setSupportsExtensibleEnums(true);
break;
default:
// Unknown options record, possibly for use by a future version of the
// module format.
Expand Down Expand Up @@ -1508,7 +1505,6 @@ ModuleFileSharedCore::ModuleFileSharedCore(
Bits.AllowNonResilientAccess = extInfo.allowNonResilientAccess();
Bits.SerializePackageEnabled = extInfo.serializePackageEnabled();
Bits.StrictMemorySafety = extInfo.strictMemorySafety();
Bits.SupportsExtensibleEnums = extInfo.supportsExtensibleEnums();
MiscVersion = info.miscVersion;
SDKVersion = info.sdkVersion;
ModuleABIName = extInfo.getModuleABIName();
Expand Down
7 changes: 1 addition & 6 deletions lib/Serialization/ModuleFileSharedCore.h
Original file line number Diff line number Diff line change
Expand Up @@ -421,11 +421,8 @@ class ModuleFileSharedCore {
/// Whether this module enabled strict memory safety.
unsigned StrictMemorySafety : 1;

/// Whether this module enabled has `ExtensibleEnums` feature enabled.
unsigned SupportsExtensibleEnums : 1;

// Explicitly pad out to the next word boundary.
unsigned : 1;
unsigned : 2;
} Bits = {};
static_assert(sizeof(ModuleBits) <= 8, "The bit set should be small");

Expand Down Expand Up @@ -684,8 +681,6 @@ class ModuleFileSharedCore {

bool strictMemorySafety() const { return Bits.StrictMemorySafety; }

bool supportsExtensibleEnums() const { return Bits.SupportsExtensibleEnums; }

/// How should \p dependency be loaded for a transitive import via \c this?
///
/// If \p importNonPublicDependencies, more transitive dependencies
Expand Down
9 changes: 2 additions & 7 deletions lib/Serialization/ModuleFormat.h
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const uint16_t SWIFTMODULE_VERSION_MAJOR = 0;
/// describe what change you made. The content of this comment isn't important;
/// it just ensures a conflict if two people change the module format.
/// Don't worry about adhering to the 80-column limit for this line.
const uint16_t SWIFTMODULE_VERSION_MINOR = 933; // isConstantValue
const uint16_t SWIFTMODULE_VERSION_MINOR = 935; // remove ExtensibleEnums feature

/// A standard hash seed used for all string hashes in a serialized module.
///
Expand Down Expand Up @@ -974,8 +974,7 @@ namespace options_block {
CXX_STDLIB_KIND,
PUBLIC_MODULE_NAME,
SWIFT_INTERFACE_COMPILER_VERSION,
STRICT_MEMORY_SAFETY,
EXTENSIBLE_ENUMS,
STRICT_MEMORY_SAFETY
};

using SDKPathLayout = BCRecordLayout<
Expand Down Expand Up @@ -1085,10 +1084,6 @@ namespace options_block {
SWIFT_INTERFACE_COMPILER_VERSION,
BCBlob // version tuple
>;

using ExtensibleEnumsLayout = BCRecordLayout<
EXTENSIBLE_ENUMS
>;
}

/// The record types within the input block.
Expand Down
5 changes: 0 additions & 5 deletions lib/Serialization/Serialization.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1186,11 +1186,6 @@ void Serializer::writeHeader() {
static_cast<uint8_t>(M->getCXXStdlibKind()));
}

if (M->supportsExtensibleEnums()) {
options_block::ExtensibleEnumsLayout ExtensibleEnums(Out);
ExtensibleEnums.emit(ScratchRecord);
}

if (Options.SerializeOptionsForDebugging) {
options_block::SDKPathLayout SDKPath(Out);
options_block::XCCLayout XCC(Out);
Expand Down
2 changes: 0 additions & 2 deletions lib/Serialization/SerializedModuleLoader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1100,8 +1100,6 @@ LoadedFile *SerializedModuleLoaderBase::loadAST(
if (!loadedModuleFile->getModulePackageName().empty()) {
M.setPackageName(Ctx.getIdentifier(loadedModuleFile->getModulePackageName()));
}
if (loadedModuleFile->supportsExtensibleEnums())
M.setSupportsExtensibleEnums();
M.setUserModuleVersion(loadedModuleFile->getUserModuleVersion());
M.setSwiftInterfaceCompilerVersion(
loadedModuleFile->getSwiftInterfaceCompilerVersion());
Expand Down
2 changes: 2 additions & 0 deletions test/IDE/complete_decl_attribute.swift
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,7 @@ struct _S {
// ON_MEMBER_LAST-DAG: Keyword/None: freestanding[#Declaration Attribute#]; name=freestanding
// ON_MEMBER_LAST-DAG: Keyword/None: storageRestrictions[#Declaration Attribute#]; name=storageRestrictions
// ON_MEMBER_LAST-DAG: Keyword/None: lifetime[#Declaration Attribute#]; name=lifetime
// ON_MEMBER_LAST-DAG: Keyword/None: extensible[#Declaration Attribute#]; name=extensible
// ON_MEMBER_LAST-NOT: Keyword
// ON_MEMBER_LAST-DAG: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// ON_MEMBER_LAST-DAG: Decl[Struct]/CurrModule/TypeRelation[Convertible]: MyPropertyWrapper[#Property Wrapper#]; name=MyPropertyWrapper
Expand Down Expand Up @@ -397,6 +398,7 @@ func dummy2() {}
// KEYWORD_LAST-DAG: Keyword/None: attached[#Declaration Attribute#]; name=attached
// KEYWORD_LAST-DAG: Keyword/None: storageRestrictions[#Declaration Attribute#]; name=storageRestrictions
// KEYWORD_LAST-DAG: Keyword/None: lifetime[#Declaration Attribute#]; name=lifetime
// KEYWORD_LAST-DAG: Keyword/None: extensible[#Declaration Attribute#]; name=extensible
// KEYWORD_LAST-NOT: Keyword
// KEYWORD_LAST-DAG: Decl[Struct]/CurrModule: MyStruct[#MyStruct#]; name=MyStruct
// KEYWORD_LAST-DAG: Decl[Struct]/CurrModule/TypeRelation[Convertible]: MyGenericPropertyWrapper[#Property Wrapper#]; name=MyGenericPropertyWrapper
Expand Down
8 changes: 8 additions & 0 deletions test/ModuleInterface/attrs.swift
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,11 @@ public func testExecutionConcurrent() async {}
@execution(caller)
public func testExecutionCaller() async {}
// CHECK: @execution(caller) public func testExecutionCaller() async

// CHECK-NOT: @extensible
// CHECK: public enum TestExtensible
@extensible
public enum TestExtensible {
case a
case b
}
15 changes: 6 additions & 9 deletions test/ModuleInterface/extensible_enums.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
/// Build the library
// RUN: %target-swift-frontend -emit-module %t/src/Lib.swift \
// RUN: -module-name Lib \
// RUN: -emit-module-path %t/Lib.swiftmodule \
// RUN: -enable-experimental-feature ExtensibleEnums
// RUN: -emit-module-path %t/Lib.swiftmodule

// Check that the errors are produced when using enums from module with `ExtensibleEnums` feature enabled.
// RUN: %target-swift-frontend -typecheck %t/src/TestChecking.swift \
Expand All @@ -19,19 +18,17 @@
// RUN: %target-swift-frontend -emit-module %t/src/Lib.swift \
// RUN: -module-name Lib \
// RUN: -package-name Test \
// RUN: -emit-module-path %t/Lib.swiftmodule \
// RUN: -enable-experimental-feature ExtensibleEnums
// RUN: -emit-module-path %t/Lib.swiftmodule

// Different module but the same package
// RUN: %target-swift-frontend -typecheck %t/src/TestSamePackage.swift \
// RUN: -swift-version 5 -module-name Client -I %t \
// RUN: -package-name Test \
// RUN: -verify

// REQUIRES: swift_feature_ExtensibleEnums

//--- Lib.swift

@extensible
public enum E {
case a
}
Expand All @@ -57,10 +54,10 @@ func test_same_module(e: E, f: F) {
import Lib

func test(e: E, f: F) {
// `E` is not marked as `@frozen` which means it gets new semantics
// `E` is marked as `@extensible` which means it gets new semantics

switch e {
// expected-error@-1 {{switch covers known cases, but 'E' may have additional unknown values, possibly added in future versions}}
// expected-warning@-1 {{switch covers known cases, but 'E' may have additional unknown values, possibly added in future versions; this is an error in the Swift 6 language mode}}
// expected-note@-2 {{handle unknown values using "@unknown default"}}
case .a: break
}
Expand All @@ -70,7 +67,7 @@ func test(e: E, f: F) {
@unknown default: break
}

// `F` is marked as `@frozen` which means regular rules apply even with `ExtensibleEnums` feature enabled.
// `F` is marked as `@frozen` which means regular rules apply.

switch f { // Ok (no errors because `F` is `@frozen`)
case .a: break
Expand Down
Loading