swiftlang / swift

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

Swift Macros: Adding an enum case with an associated value produces incorrect results #70208

Open skyler-cricut opened 1 year ago

skyler-cricut commented 1 year ago

Description

If a Macro adds an enum case with an associated value, other cases are transformed at runtime. In the example below, the case foo is translated into the Macro-generated case bar(false).

EnumCase

There is lots of other strange behavior, such as:

Reproduction

Download the sample project here. The main code snippets are included below.

// EnumCase.swift
@attached(member, names: named(bar))
public macro EnumCase() = #externalMacro(module: "EnumCaseMacros", type: "EnumCaseMacro")
// EnumCaseMacro.swift
import SwiftCompilerPlugin
import SwiftDiagnostics
import SwiftSyntax
import SwiftSyntaxBuilder
import SwiftSyntaxMacros

public struct EnumCaseMacro: MemberMacro {
    public static func expansion(of node: SwiftSyntax.AttributeSyntax, providingMembersOf declaration: some SwiftSyntax.DeclGroupSyntax, in context: some SwiftSyntaxMacros.MacroExpansionContext) throws -> [SwiftSyntax.DeclSyntax] {
        return ["case bar(Bool)"]
    }
}

@main
struct macro_testPlugin: CompilerPlugin {
    let providingMacros: [Macro.Type] = [EnumCaseMacro.self]
}
// SimpleEnum.swift
import EnumCase

@EnumCase
enum SimpleEnum {
    case foo
}
// Main.swift
@main
final class Main {
    static func main() -> Void {
        print(SimpleEnum.foo)
    }
}

The program prints "bar(false)"

Expected behavior

The program prints "foo".

Environment

SwiftSyntax version 509.0.2

Additional information

Reproduced in Xcode versions 15.0.1 and 15.1 beta 3. Also discussed on the Swift Forums and Apple Developer Forums.

kyounh12 commented 9 months ago

Facing the same issue and this is still happening on Xcode 15.3 beta 3. Hope it will be fixed soon 🙏