I have an extension macro which adds Codable conformance. The macro expands the code:
@Foo
public struct Name {
private var value: String
}
to:
public struct Name {
private var value: String
}
extension Name: Codable {
}
The expanded code compiles, but the unexpanded code doesn't. The error:
'value' is inaccessible due to 'private' protection level
If I add an internal or pubic init(), the error is gone.
I ran into the issue when I used macros and property wrapper together, as below. I used macro to generate init so there wasn't an explicit init declaration. The property wrapper generated _value variable with private access. These combination exposed the above issue.
@Foo
@Init
public struct Name {
@SomePW var value: String
}
public enum FooMacro: ExtensionMacro {
public static func expansion(
of node: AttributeSyntax,
attachedTo declaration: some DeclGroupSyntax,
providingExtensionsOf type: some TypeSyntaxProtocol,
conformingTo protocols: [TypeSyntax],
in context: some MacroExpansionContext
) throws -> [ExtensionDeclSyntax] {
let extensionDecl = try ExtensionDeclSyntax(
"""
extension \(type.trimmed): Codable {
}
"""
)
return [extensionDecl]
}
}
Test:
@Foo
public struct Name {
private var value: String
}
Expected behavior
It should compile.
Environment
$ /Users/app/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -version
swift-driver version: 1.87.1 Apple Swift version 5.9 (swiftlang-5.9.0.128.108 clang-1500.0.40.1)
Target: x86_64-apple-macosx13.0
Description
I have an extension macro which adds Codable conformance. The macro expands the code:
to:
The expanded code compiles, but the unexpanded code doesn't. The error:
If I add an internal or pubic
init()
, the error is gone.I ran into the issue when I used macros and property wrapper together, as below. I used macro to generate
init
so there wasn't an explicitinit
declaration. The property wrapper generated_value
variable with private access. These combination exposed the above issue.Swift forums thread: https://forums.swift.org/t/macro-unable-to-add-codable-conformance-if-type-has-only-private-init-though-the-expanded-code-compiles/68639
Reproduction
Macro implementation:
Test:
Expected behavior
It should compile.
Environment
$ /Users/app/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -version swift-driver version: 1.87.1 Apple Swift version 5.9 (swiftlang-5.9.0.128.108 clang-1500.0.40.1) Target: x86_64-apple-macosx13.0
Xcode 15.0, macOS: 13.6
Additional information
No response