[Half-baked idea] Autoconform Codable for C structs

Currently, Codable cannot be autosynthesized in an extension outside the file declaring the type. See SR-6101, which discusses maybe extending it within the module. Per that issue we seem to lack a comprehensive theory of where this ought to be allowed. We do have a vague intuition that it's bound together with member visibility, which is obviously involved in the autosynthesized conformance.

I'd like to assert it ought to be allowed for C structs (that otherwise contain Codables). C structs by definition have no private members, so we have no visibility issues. In fact, we have substantially more guarantees about C structs than we do for Swift types (memory layout, etc.)

Moreover, writing conformances for C structs is very tedious, and is substantially similar to the problem that motivated autosynthesis for Swift in the first place. And of course C authors cannot write conformances in the declaring file (or even module), since Codable is a Swift feature and the types are declared in C. So chances are, this falls to you as a random Swift user.

There are some open questions:

  1. Are C structs a special case, or is it an application of a general theory of allowing conformances on "simple types"? For example, I can see good arguments for C++ types to also want to support Codable, but since C++ types may have private fields it is not as obvious how to support it. For that matter I think Swift @frozen types are also an interesting case.
  2. An alternative might be considering autosynthesis of foreign types part of the 'refine for swift' surface area. So we could introduce __attribute__((swift_equatable)) and so on. I do think pushing Swift features onto C developers is not ideal, but if you take the view that autoconformance is an 'ergonomics' issue it makes some sense.
1 Like

This is likely to work only for the most trivial C structs, because Swift's pointer types do not conform to Codable, and it is arguably not possible to write a sensible Codable implementation for them.

I suspect the majority of structs are "the most trivial" for this purpose. In the iOS SDK, the regex struct(.*)\{[^}]*\} returns 2k results, whereas struct(.*)\{[^}\*]*\} (forbidding * in the definition) returns about 1k. Manually reviewing structs containing * suggest they're 80% comments (/* */) which I lack the regex knowledge to pattern-exclude appropriately.

There are a number of limitations with this sort of survey but it confirms my intuition that structs meeting criteria for autosynthesis are quite common.

Bear in mind the iOS SDK’s C structures need to look for Ref as a keyword as well, as those are opaque C pointers.

1 Like
Terms of Service

Privacy Policy

Cookie Policy