How does the SwiftUI Entry macro get information about extension?

The code generated by the Entry macro depends on the extension in which the macro is applied.

extension EnvironmentValues {
    @Entry var value: Int = 42
}

expands to

extension EnvironmentValues {
    var value: Int {
        get {
            self[__Key_value.self]
        }
        set {
            self[__Key_value.self] = newValue
        }
    }
    
    private struct __Key_value: SwiftUICore.EnvironmentKey {
        typealias Value = Int
        static var defaultValue: Value { 42 }
    }
}

and

extension ContainerValues {
    @Entry var value: Int = 42
}

expands to

extension ContainerValues {
    var value: Int {
        get {
            self[__Key_value.self]
        }
        set {
            self[__Key_value.self] = newValue
        }
    }
    
    private struct __Key_value: SwiftUI.ContainerValueKey {
        typealias Value = Int
        static var defaultValue: Value { 42 }
    }
}

How does the macro get information about the extension?

What do you mean?

I mean the type extensions. extension EnvironmentValues and extension ContainerValues in the examples.

I had to look closely to see the difference between the two expansions:

private struct __Key_value: SwiftUICore.EnvironmentKey {

vs:

private struct __Key_value: SwiftUI.ContainerValueKey {

there is a in context: some MacroExpansionContext parameter in the macro invocation function.

if you look into context.lexicalContext you will have access to the name of the extension

2 Likes

Thanks! lexicalContext is exactly what I was looking for.

Couldn't understand till @mlienert gave the answer)

There is a good tool for searching such things