Circular Reference error when using keypaths to properties with Macros: Bug or Expected Behaviour?

Hey all,

I'm currently playing around with macros and I've hit a bit of a problem. I'm wanting to set up a macro to define a relationship between two properties, for example:

class MyClassA {
    @Relationship(inverse: \MyClassB.objectA) var objectB: MyClassB?
}


class MyClassB {
    @Relationship(inverse: \MyClassA.objectB) var objectAs: Set<MyClassA>
}

The problem is, I'm getting a Circular reference resolving attached macro 'Relationship' error from the compiler.

The Macro is defined like so (the implementation doesn't matter as I get this regardless of implementation if both properties have the macro attached):

@attached(accessor, names: named(get), named(set))
@attached(peer, names: prefixed(_))
public macro Relationship(inverse: AnyKeyPath) = #externalMacro(module: "M3DataMacros", type: "RelationshipMacro")

I've searched online and found a bunch of similar issues (especially with the similar macro from SwiftData) but before I start looking for a workaround I wanted to know if this is a compiler bug [1] or if it's expected behaviour that this should not work?

It feels like it should be possible to do as I'm just wanting a keypath that will be inserted into the generated code, I'm not changing the other property definition.

[1] I found this bug but I'm not sure if it covers this particular case as it's more about sub types Extensions for subtype of a class marked @Observable generate compile error · Issue #66450 · apple/swift · GitHub

1 Like

I remember having the exact same error a while ago when dealing with macros and key paths.