swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
66.85k stars 10.3k forks source link

Macro: unable to add Codable conformance if type has only private init #70086

Open rayx opened 7 months ago

rayx commented 7 months ago

Description

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
}

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:

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

Xcode 15.0, macOS: 13.6

Additional information

No response

vanvoorden commented 2 months ago

@rayx I saw a similar issue building from Swift 5.9.1. It went away in 5.9.2 and still looks fixed in 5.10.