Skip to content

[SE-0407] [Macros] Provide member macros with information about "missing" conformances #68372

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
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
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,18 @@

_**Note:** This is in reverse chronological order, so newer entries are added to the top._

## Swift 5.9.2

* [SE-0407][]:

Member macros can specify a list of protocols via the `conformances` argument to the macro role. The macro implementation will be provided with those protocols that are listed but have not already been implemented by the type to which the member macro is attached, in the same manner as extension macros.

```swift
@attached(member, conformances: Decodable, Encodable, names: named(init(from:), encode(to:)))
@attached(extension, conformances: Decodable, Encodable, names: named(init(from:), encode(to:)))
macro Codable() = #externalMacro(module: "MyMacros", type: "CodableMacro")
```

## Swift 5.9

* [SE-0382][], [SE-0389][], [SE-0394][], [SE-0397][]:
Expand Down Expand Up @@ -9830,6 +9842,7 @@ using the `.dynamicType` member to retrieve the type of an expression should mig
[SE-0389]: https://github.com/apple/swift-evolution/blob/main/proposals/0389-attached-macros.md
[SE-0394]: https://github.com/apple/swift-evolution/blob/main/proposals/0394-swiftpm-expression-macros.md
[SE-0397]: https://github.com/apple/swift-evolution/blob/main/proposals/0397-freestanding-declaration-macros.md
[SE-0407]: https://github.com/apple/swift-evolution/blob/main/proposals/0407-member-macro-conformances.md
[#64927]: <https://github.com/apple/swift/issues/64927>
[#42697]: <https://github.com/apple/swift/issues/42697>
[#42728]: <https://github.com/apple/swift/issues/42728>
Expand Down
1 change: 1 addition & 0 deletions include/swift/AST/Decl.h
Original file line number Diff line number Diff line change
Expand Up @@ -8621,6 +8621,7 @@ class MacroDecl : public GenericContext, public ValueDecl {
/// be added if this macro does not contain an extension role.
void getIntroducedConformances(
NominalTypeDecl *attachedTo,
MacroRole role,
SmallVectorImpl<ProtocolDecl *> &conformances) const;

/// Returns a DeclName that represents arbitrary names.
Expand Down
8 changes: 4 additions & 4 deletions include/swift/AST/TypeCheckRequests.h
Original file line number Diff line number Diff line change
Expand Up @@ -3337,10 +3337,10 @@ class ResolveMacroRequest
void noteCycleStep(DiagnosticEngine &diags) const;
};

/// Returns the resolved constraint types that an extension macro
/// adds conformances to.
class ResolveExtensionMacroConformances
: public SimpleRequest<ResolveExtensionMacroConformances,
/// Returns the resolved constraint types that a macro references conformances
/// to.
class ResolveMacroConformances
: public SimpleRequest<ResolveMacroConformances,
ArrayRef<Type>(const MacroRoleAttr *, const Decl *),
RequestFlags::Cached> {
public:
Expand Down
2 changes: 1 addition & 1 deletion include/swift/AST/TypeCheckerTypeIDZone.def
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ SWIFT_REQUEST(TypeChecker, ResolveImplicitMemberRequest,
SWIFT_REQUEST(TypeChecker, ResolveMacroRequest,
ConcreteDeclRef(UnresolvedMacroReference, const Decl *),
Cached, NoLocationInfo)
SWIFT_REQUEST(TypeChecker, ResolveExtensionMacroConformances,
SWIFT_REQUEST(TypeChecker, ResolveMacroConformances,
ArrayRef<Type>(const MacroRoleAttr *, const Decl *),
Cached, NoLocationInfo)
SWIFT_REQUEST(TypeChecker, ResolveTypeEraserTypeRequest,
Expand Down
2 changes: 1 addition & 1 deletion lib/AST/Attr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1387,7 +1387,7 @@ bool DeclAttribute::printImpl(ASTPrinter &Printer, const PrintOptions &Options,
// Print conformances, if present.
auto conformances = evaluateOrDefault(
D->getASTContext().evaluator,
ResolveExtensionMacroConformances{Attr, D},
ResolveMacroConformances{Attr, D},
{});
if (!conformances.empty()) {
Printer << ", conformances: ";
Expand Down
3 changes: 2 additions & 1 deletion lib/AST/ConformanceLookupTable.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -503,7 +503,8 @@ void ConformanceLookupTable::addMacroGeneratedProtocols(
MacroRole::Extension,
[&](CustomAttr *attr, MacroDecl *macro) {
SmallVector<ProtocolDecl *, 2> conformances;
macro->getIntroducedConformances(nominal, conformances);
macro->getIntroducedConformances(
nominal, MacroRole::Extension, conformances);

for (auto *protocol : conformances) {
addProtocol(protocol, attr->getLocation(), source);
Expand Down
5 changes: 3 additions & 2 deletions lib/AST/Decl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10826,15 +10826,16 @@ void MacroDecl::getIntroducedNames(MacroRole role, ValueDecl *attachedTo,

void MacroDecl::getIntroducedConformances(
NominalTypeDecl *attachedTo,
MacroRole role,
SmallVectorImpl<ProtocolDecl *> &conformances) const {
auto *attr = getMacroRoleAttr(MacroRole::Extension);
auto *attr = getMacroRoleAttr(role);
if (!attr)
return;

auto &ctx = getASTContext();
auto constraintTypes = evaluateOrDefault(
ctx.evaluator,
ResolveExtensionMacroConformances{attr, this},
ResolveMacroConformances{attr, this},
{});

for (auto constraint : constraintTypes) {
Expand Down
2 changes: 1 addition & 1 deletion lib/Sema/TypeCheckAttr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7151,7 +7151,7 @@ void AttributeChecker::visitMacroRoleAttr(MacroRoleAttr *attr) {

(void)evaluateOrDefault(
Ctx.evaluator,
ResolveExtensionMacroConformances{attr, D},
ResolveMacroConformances{attr, D},
{});
}

Expand Down
69 changes: 50 additions & 19 deletions lib/Sema/TypeCheckMacros.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1533,12 +1533,56 @@ swift::expandAttributes(CustomAttr *attr, MacroDecl *macro, Decl *member) {
return macroSourceFile->getBufferID();
}

// Collect the protocol conformances that the macro asked about but were
// not already present on the declaration.
static TinyPtrVector<ProtocolDecl *> getIntroducedConformances(
NominalTypeDecl *nominal, MacroRole role, MacroDecl *macro,
SmallVectorImpl<ProtocolDecl *> *potentialConformances = nullptr) {
SmallVector<ProtocolDecl *, 2> potentialConformancesBuffer;
if (!potentialConformances)
potentialConformances = &potentialConformancesBuffer;
macro->getIntroducedConformances(nominal, role, *potentialConformances);

TinyPtrVector<ProtocolDecl *> introducedConformances;
for (auto protocol : *potentialConformances) {
SmallVector<ProtocolConformance *, 2> existingConformances;
nominal->lookupConformance(protocol, existingConformances);

bool hasExistingConformance = llvm::any_of(
existingConformances,
[&](ProtocolConformance *conformance) {
return conformance->getSourceKind() !=
ConformanceEntryKind::PreMacroExpansion;
});

if (!hasExistingConformance) {
introducedConformances.push_back(protocol);
}
}

return introducedConformances;
}

llvm::Optional<unsigned> swift::expandMembers(CustomAttr *attr,
MacroDecl *macro, Decl *decl) {
auto nominal = dyn_cast<NominalTypeDecl>(decl);
if (!nominal) {
auto ext = dyn_cast<ExtensionDecl>(decl);
if (!ext)
return llvm::None;

nominal = ext->getExtendedNominal();
if (!nominal)
return llvm::None;
}
auto introducedConformances = getIntroducedConformances(
nominal, MacroRole::Member, macro);

// Evaluate the macro.
auto macroSourceFile =
::evaluateAttachedMacro(macro, decl, attr,
/*passParentContext=*/false, MacroRole::Member);
/*passParentContext=*/false, MacroRole::Member,
introducedConformances);
if (!macroSourceFile)
return llvm::None;

Expand Down Expand Up @@ -1611,22 +1655,9 @@ llvm::Optional<unsigned> swift::expandExtensions(CustomAttr *attr,
return llvm::None;
}

// Collect the protocol conformances that the macro can add. The
// macro should not add conformances that are already stated in
// the original source.

SmallVector<ProtocolDecl *, 2> potentialConformances;
macro->getIntroducedConformances(nominal, potentialConformances);

SmallVector<ProtocolDecl *, 2> introducedConformances;
for (auto protocol : potentialConformances) {
SmallVector<ProtocolConformance *, 2> existingConformances;
nominal->lookupConformance(protocol, existingConformances);
if (existingConformances.empty()) {
introducedConformances.push_back(protocol);
}
}

auto introducedConformances = getIntroducedConformances(
nominal, MacroRole::Extension, macro, &potentialConformances);
auto macroSourceFile = ::evaluateAttachedMacro(macro, nominal, attr,
/*passParentContext=*/false,
role, introducedConformances);
Expand Down Expand Up @@ -1815,9 +1846,9 @@ ConcreteDeclRef ResolveMacroRequest::evaluate(Evaluator &evaluator,
}

ArrayRef<Type>
ResolveExtensionMacroConformances::evaluate(Evaluator &evaluator,
const MacroRoleAttr *attr,
const Decl *decl) const {
ResolveMacroConformances::evaluate(Evaluator &evaluator,
const MacroRoleAttr *attr,
const Decl *decl) const {
auto *dc = decl->getDeclContext();
auto &ctx = dc->getASTContext();

Expand Down
50 changes: 50 additions & 0 deletions test/Macros/Inputs/syntax_macro_definitions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2018,3 +2018,53 @@ public struct InitWithProjectedValueWrapperMacro: PeerMacro {
]
}
}

public struct RequiredDefaultInitMacro: ExtensionMacro {
public static func expansion(
of node: AttributeSyntax,
attachedTo decl: some DeclGroupSyntax,
providingExtensionsOf type: some TypeSyntaxProtocol,
conformingTo protocols: [TypeSyntax],
in context: some MacroExpansionContext
) throws -> [ExtensionDeclSyntax] {
if protocols.isEmpty {
return []
}

let decl: DeclSyntax =
"""
extension \(type.trimmed): DefaultInit {
}

"""

return [
decl.cast(ExtensionDeclSyntax.self)
]
}
}

extension RequiredDefaultInitMacro: MemberMacro {
public static func expansion(
of node: AttributeSyntax,
providingMembersOf declaration: some DeclGroupSyntax,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
fatalError("old swift-syntax")
}

public static func expansion(
of node: AttributeSyntax,
providingMembersOf declaration: some DeclGroupSyntax,
conformingTo protocols: [TypeSyntax],
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
let decl: DeclSyntax
if declaration.is(ClassDeclSyntax.self) && protocols.isEmpty {
decl = "required init() { }"
} else {
decl = "init() { }"
}
return [ decl ]
}
}
22 changes: 22 additions & 0 deletions test/Macros/macro_expand_member_with_conformances.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// REQUIRES: swift_swift_parser

// RUN: %empty-directory(%t)
// RUN: %host-build-swift -swift-version 5 -emit-library -o %t/%target-library-name(MacroDefinition) -module-name=MacroDefinition %S/Inputs/syntax_macro_definitions.swift -g -no-toolchain-stdlib-rpath

// RUN: %target-typecheck-verify-swift -enable-experimental-feature ExtensionMacros -swift-version 5 -load-plugin-library %t/%target-library-name(MacroDefinition) -module-name MacroUser -DTEST_DIAGNOSTICS -swift-version 5 -I %t
protocol DefaultInit {
init()
}

@attached(extension, conformances: DefaultInit)
@attached(member, conformances: DefaultInit, names: named(init()))
macro DefaultInit() = #externalMacro(module: "MacroDefinition", type: "RequiredDefaultInitMacro")

@DefaultInit
class C { }

@DefaultInit
class D: C { }

@DefaultInit
struct E { }