Can extension macro be used to extend a type different from the one the macro is applied to?

I have a scenario where I'd like to apply extension macro to type Foo but to generate extension for type Bar. For example, the code

@MyMacro
struct Foo {
    ...
}

should be expanded to

struct Foo {
    ...
}

extension Array<Foo> {
    ...
}

My quick experiments show the code compiles, but with a mysterious warning, which seems to indicate the above usage isn't supported by design.

Extending a protocol composition is not supported; extending 'Foo' instead

I wonder if someone can clarify if this usage is supported or not?

My Scenario

Suppose I have a model like the following:

struct Model {
   var foos: [Foo]
   var bars: [Bar]
}

I like to organize CRUD methods in layers:

  • Foo has create/modify/etc. methods
  • Array<Foo> has corresponding create/modify/etc. methods
  • Model has corresponding create/modify/etc. methods for Foo.

The CRUD code in Array and Model are very similar for different properties (e.g. Foo, Bar). It becomes a burden to write them manually when adding new properties to Model. So I'd like to use macro to generate CRUD methods for them. That leads to the above question.


UPDATE:

I find the following in SE-0402, so the compiler should output error, instead of warning, in this case.

The generated extensions of the macro must only extend the type the macro is attached to.

I personally think it would be very useful to support generating extension to other types in extension macro.

1 Like

I've read before that extending arbitrary types is specifically disallowed to enable the compiler to be conservative about when it expands macros.

Perhaps it could support your specific use case - extending a generic type with the attached type as a generic parameter.