swiftlang / swift

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

Expand Macro and Inline Macro commands put extension macro expansion in nested type and not at top level. #73140

Open vanvoorden opened 2 months ago

vanvoorden commented 2 months ago

Description

https://forums.swift.org/t/extensionmacro-on-a-nested-type-does-not-generate-extension-at-top-level/71349

I'm seeing some unexpected behavior with using ExtensionMacro. According to SE-0402^1 we can expect that an ExtensionMacro applied to a nested type will generate an extension at top-level. I am testing with an ExtensionMacro example from the swift-syntax repo and I am seeing the extension generated at local scope:

struct Outer {
  @Observable
  struct Inner {}
}

Expands to:

struct Outer {

  struct Inner {

    let _registrar = ObservationRegistrar<Inner >()

    public nonisolated func addObserver(_ observer: some Observer<Inner >) {
      _registrar.addObserver(observer)
    }

    public nonisolated func removeObserver(_ observer: some Observer<Inner >) {
      _registrar.removeObserver(observer)
    }

    private func withTransaction<T>(_ apply: () throws -> T) rethrows -> T {
      _registrar.beginAccess()
      defer {
        _registrar.endAccess()
      }
      return try apply()
    }

    private struct Storage {

    }

    private var _storage = Storage()
  }

  extension Outer.Inner: Observable {
  }

}

Reproduction

Here is a diff on swift-syntax to repro:

diff --git a/Examples/Sources/MacroExamples/Playground/main.swift b/Examples/Sources/MacroExamples/Playground/main.swift
index 6df22c09..00df357b 100644
--- a/Examples/Sources/MacroExamples/Playground/main.swift
+++ b/Examples/Sources/MacroExamples/Playground/main.swift
@@ -84,6 +84,11 @@ print("Point storage contains only the value we set:  \(point)")

 // MARK: - ObservableMacro

+struct Outer {
+  @Observable
+  struct Inner {}
+}
+
 struct Treat {}

 @Observable

Expected behavior

Similar behavior to assertMacroExpansion.

Environment

Xcode 15.3 and Swift-Syntax 510.0.1.

Additional information

No response

vanvoorden commented 2 months ago

cc @ahoppen