swiftlang / swift

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

SE-0444: Fix interactions with Cxx interop #76756

Closed tshortli closed 1 month ago

tshortli commented 1 month ago

With the upcoming MemberImportVisibility feature enabled, code built with Cxx interop also enabled could be rejected by the compiler with cryptic errors about the __ObjC module not being imported. This is the result of a surprising implementation detail of Cxx interop. When importing C++ namespaces and their members, the Clang importer puts these declarations in the Clang header import module (a.k.a. the bridging header module, __ObjC). C++ namespaces don't have a logical modular home in the Swift AST because they can span multiple modules, so it's understandable why this implementation was chosen. However, the concrete members of namespaces also get placed in the __ObjC module too, and this really confuses things.

To work around this idiosyncrasy of Cxx interop, I've introduced Decl::getModuleContextForNameLookup() which returns the module that a declaration would ideally belong to if Cxx interop didn't have this behavior. This alternative to Decl::getModuleContext() is now used everywhere that MemberImportVisibility rules are enforced to provide consistency.

Additionally, I found that I also had to further special-case the header import module for Cxx interop because it turns out that there are some additional declarations, beyond imported namespaces, that also live there and need to be implicitly visible in every source file. The __ObjC module is not implicitly imported in source files when Cxx interop is enabled, so these declarations are not deemed visible under normal name lookup rules. When I tried to add an implicit import of __ObjC when Cxx interop is enabled, it broke a bunch tests. So for now, when a decl really belongs to the __ObjC module in Cxx interop mode, we just always allow it to be referenced.

This Cxx interop behavior really needs a re-think in my opinion, but that will require larger discussions.

Resolves rdar://136600598.

tshortli commented 1 month ago

@swift-ci please smoke test