Commit Graph

2524 Commits

Author SHA1 Message Date
Slava Pestov
acb53d2050 Merge pull request #82132 from slavapestov/bind-extensions-macro-6.2
[6.2] Sema: Don't expand macros when binding extensions
2025-06-14 12:14:10 -04:00
Slava Pestov
15f968f269 AST: Call setExtendedNominal() instead of cacheOutput(ExtendedNominalRequest...) 2025-06-13 16:00:16 -04:00
John Hui
a2bd6cafd9 Merge pull request #82171 from j-hui/j-hui/6.2/jump-to-def-for-macro-expanded-clang-imports
🍒 [6.2] [SourceKit] Support location info for macro-expanded Clang imports
2025-06-13 04:10:37 -07:00
John Hui
c94955b571 [SourceKit] Support location info for macro-expanded Clang imports
Currently, when we jump-to-definition for decls that are macro-expanded
from Clang imported decls (e.g., safe overloads generated by
@_SwiftifyImport), setLocationInfo() emits a bongus location pointing to
a generated buffer, leading the IDE to try to jump to a file that does
not exist.

The root cause here is that setLocationInfo() calls getOriginalRange()
(earlier, getOriginalLocation()), which was not written to account for
such cases where a macro is generated from another generated buffer
whose kind is 'AttributeFromClang'.

This patch fixes setLocationInfo() with some refactoring:

-   getOriginalRange() is inlined into setLocationInfo(), so that the
    generated buffer-handling logic is localized to that function. This
    includes how it handles buffers generated for ReplacedFunctionBody.

-   getOriginalLocation() is used in a couple of other places that only
    care about macros expanded from the same buffer (so other generated
    buffers not not relevant). This "macro-chasing" logic is simplified
    and moved from ModuleDecl::getOriginalRange() to a free-standing
    function, getMacroUnexpandedRange() (there is no reason for it to be
    a method of ModuleDecl).

-   GeneratedSourceInfo now carries an extra ClangNode field, which is
    populated by getClangSwiftAttrSourceFile() when constructing
    a generated buffer for an 'AttributeFromClang'. This could probably
    be union'ed with one or more of the other fields in the future.

rdar://151020332
(cherry picked from commit 44aba1382d)
2025-06-12 18:24:04 -07:00
Gábor Horváth
4590d5551b [6.2][cxx-interop] Only swiftify template instantiations behind type aliases
Explanation: C++ template instantiations that are not behind type
aliases don't have corresponding Swift names that are both syntactically
and semantically valid types. This PR prevents generating swiftified
overloads for those types.
Issue: rdar://151422108
Risk: Low, we swiftify functions less often.
Testing: Regression test added.
Original PR: #81973
Reviewer: @hnrklssn
2025-06-12 19:05:36 +01:00
Gábor Horváth
5d243730b4 Merge pull request #82061 from swiftlang/gaborh/swiftify-initializers-on-6.2
[6.2][cxx-interop] Support Swiftifying C++ constructors
2025-06-12 19:01:26 +01:00
Devin Coughlin
dd2f521d86 Merge pull request #82104 from swiftlang/gaborh/swiftify-private-on-6.2
[6.2][cxx-interop] Avoid swiftifying private and protected methods
2025-06-12 10:08:29 -07:00
Henrik G. Olsson
993929c3e1 Merge pull request #81752 from hnrklssn/swiftify-sized-sizedby
[Swiftify] Support __sized_by on byte-sized pointee types

(cherry picked from commit 89b09a69e4)
2025-06-10 21:49:52 +02:00
Gábor Horváth
7548cbf71a [6.2][cxx-interop] Avoid swiftifying private and protected methods
Explanation: We do not serialize the private macro generated swift
method's bodies which crashes the compiler. This PR skips generating
swiftified overloads to these private/protected method to work around
the crash.
Issue: rdar://152181531
Risk: Low, the change is straightforward.
Testing: Regression test added.
Original PR: #82016
Reviewer: @hnrklssn
2025-06-09 13:15:55 +01:00
Gábor Horváth
2b33c44796 [6.2][cxx-interop] Support Swiftifying C++ constructors
Explanation: We did not have support to generate swiftified overload for
initializers. This PR adds that support.
Issue: rdar://152112660
Risk: Low, the feature is localized to swiftified overloads.
Testing: Regression test added.
Original PR: #81947
Reviewer: @hnrklssn
2025-06-06 15:34:15 +01:00
Henrik G. Olsson
8584d343cb [Swiftify] Update availability for CxxSpan<->Span, fix lifetimebound on parameters with reference type (#81634)
Update availability for CxxSpan<->Span, fix lifetimebound on parameters
with reference type

Because swift-ide-test doesn't care about typechecking,
std-span-interface.swift passed despite containing 2 separate errors.
This updates the test file to properly exercise the entire compilation
pipeline for the macro expansions, by running swift-frontend
-emit-module and calling each macro expansion.

The first issue was that CxxSpan initializers taking [Mutable]Span still
had their availability set to Swift 6.2+, even after back-deploying
caused [Mutable]Span to have availability back to Swift 5.0. Since
_SwiftifyImport expansions copy the availbility of Span, this resulted
in the macro expansions calling unavailable initializers. Interestingly
enough, this manifested itself in the form of a tripped assert in SIL
verification, because although we do now typecheck the expansions from
_SwiftifyImport, the compilation can still keep going after
`shouldEmitFunctionBody` returns false: the macro expansion declaration
is still there, but is now missing its definition, despite not being
external.

The second issue was when parameters with C++ reference types were
annotated with `[[clang::lifetimebound]]`. For parameters with a type
that is `Escapable`, this is normally done using `@lifetime(borrow
foo)`. However C++ reference parameters are imported as `inout`, which
requires the `@lifetime(&foo)` syntax.

rdar://151493400
rdar://151678415
(cherry picked from commit 262a53f599)
2025-05-30 18:19:57 -07:00
Henrik G. Olsson
341ee5124a [Swiftify] Copy doc comment from clang node (#81584)
Swift nodes imported from clang don't have doc comments carried over,
but IDEs are clever enough to fetch the comments from the associated
clang node. The swift node in the macro expansion from _SwiftifyImport
doesn't have a clang node directly associated with it however.

This patch adds the same comment from the clang node to the
_SwiftifyImport macro invocation node. Since the macro has access to
this node, it can easily copy over its leading trivia.

For now the comment is not altered at all, meaning @param still remains
even if the parmeter is removed.

rdar://151346977
(cherry picked from commit 6534b9b14f)
2025-05-29 00:20:07 -07:00
John Hui
3db1314ba8 Merge pull request #81699 from j-hui/cherry-pick-6.2/fix-unavailable-enum
[6.2 🍒][cxx-interop] Fix assertion failure from unavailable typedef + enum pattern
2025-05-22 09:47:32 -07:00
John Hui
d1c2c76a19 [NFC] [cxx-interop] Flatten findOptionSetEnum() and move it to ImportEnumInfo.cpp
It's at home there alongside other ObjC enum-specific logic, rather than
in the middle of ImportDecl.cpp (since it isn't directly or exclusively
related to importing decls).

(cherry picked from commit 5aa5bcfea2)
2025-05-21 18:54:42 -07:00
John Hui
1f4ce612ba [NFC] [cxx-interop] Consolidate uses of findOptionSetType() helper function
Also renames it to findOptionSetEnum() to make it a bit clearer at face
value that the returned ImportedType will contain a Swift enum.

Also refactors some nearby instances of

  if (auto e = dyn_cast<ElaboratedType>(t))
      t = e->desugar();

into a helper function, desugarIfElaborated().

(cherry picked from commit c7070e73fe)
2025-05-21 18:54:42 -07:00
Henrik G. Olsson
c335b80ebd [Swiftify] Don't create safe wrapper for autoreleasing pointers (#81568) (#81590)
_SwiftifyImport doesn't know how to handle
AutoreleasingUnsafeMutablePointer, so we should not attach any
.countedBy information for pointers that are imported as this type.

This also adds defensive checks against adding .countedBy to any pointer
type that _SwiftifyImport doesn't know how to transform.

rdar://151479521
2025-05-20 08:03:10 -07:00
Devin Coughlin
2e941ef2db Merge pull request #81388 from hnrklssn/swiftify-anonymous-params-qual
[Swiftify] Emit @availability when expansions contain Span (#81320)
2025-05-12 17:29:18 -07:00
John Hui
97c5fbfe99 Merge pull request #81397 from j-hui/cherry-pick-6.2/dont-swiftify-invalid-expr
🍒  [6.2] [Swiftify] Do not swiftify non-Swift-like counted_by exprs
2025-05-09 11:55:23 -07:00
fahadnayyar
5ac1e63ad6 [6.2] [cxx-interop] Disabling should be annotated with SWIFT_RETURNS_(UN)RETAINED warning (#81390)
**Explanation**:
In Swift 6.1, we introduced warnings for C++ APIs returning
`SWIFT_SHARED_REFERENCE` types that lack the
`SWIFT_RETURNS_(UN)RETAINED` annotations. These warnings serve as a
reminder to annotate APIs, as the absence of these annotations can lead
to arbitrary assumptions about the ownership of returned
`SWIFT_SHARED_REFERENCE` values. This could result in both
use-after-free (memory safety) bugs and memory leaks.
We have received feedback from a few adopters indicating potential false
positive cases where these warnings are triggered. Consequently, we have
decided to disable these warnings in Swift 6.2 and re-qualify the
warnings on larger projects to ensure their effectiveness and eliminate
false positives.

- **Scope**: Disabling a previously shipped warning. There is no
likelihood of any source breakage or semantic alterations.
- **Issues**: rdar://150937617 , rdar://150800115
- **Original PRs**: N/A
- **Risk**: Low
- **Testing**: Lit test and adopted manually on a demo Xcode project
- **Reviewers**: N/A Our intention is to re-enable the warnings in later
beta releases of Swift 6.2 once we have stronger evidence of their
effectiveness on large codebases and proof that there are no false
positives.
2025-05-09 08:08:01 -07:00
John Hui
8be78da6de [Swiftify] Do not swiftify non-Swift-like counted_by exprs
__counted_by (and __sized_by) expressions can have arbitrary C syntax
in them, such as:

    void foo(int * __counted_by(*len) p, int *len);

When @_SwififyImport tries to generate Swift code for this, the
expression `*len` leads to a syntax error, since it isn't valid Swift.

This patch adds a check to ensure we only attach the Swiftify macro to
__counted_by expressions that are also syntactically valid in Swift.

rdar://150956352
(cherry picked from commit e5b1f4a251)
2025-05-08 21:14:08 -07:00
Henrik G. Olsson
f70676a340 [Swiftify] Emit @availability when expansions contain Span (#81320)
This prevents errors when compiling for older targets using a newer
compiler.

rdar://150740330
(cherry picked from commit 59d7d3160f)
2025-05-08 16:40:20 -07:00
Henrik G. Olsson
5498c5db05 [Swiftify] Skip swiftify during symbolic import (#81349)
Swiftify cannot work in this mode. This mode has been removed entirely
in main. This takes a smaller change into the release to minimise risk.

rdar://149953125
2025-05-07 16:18:33 -07:00
Doug Gregor
751678d7fb Merge pull request #81235 from j-hui/cherry-pick-6.2/fix-ast-layout-dependent-types
🍒 [6.2] [cxx-interop] Avoid querying layout of dependent types during symbolic import
2025-05-06 14:04:51 -07:00
John Hui
f6f5adb5f4 [cxx-interop] Avoid querying layout of dependent types during symbolic import
In #80786, we started importing certain padded fields as opaque blobs.
Part of this logic involved querying those fields' ASTRecordLayout.
However, dependent types (which are imported symbolically) do not have
an ASTRecordLayout, so calling Clang's getASTRecordLayout() would lead
to an assertion error for class templates where a no_unique_address
field is some kind of dependent C++ record type.

This patch avoids the field padding check during symbolic import mode
because that check is only relevant for codegen anyway.

rdar://150067288
(cherry picked from commit 1fdb239cea)
2025-05-01 10:10:56 -07:00
Yeoul Na
203ee392f1 [Swiftify] SafeInteropWrapper crashes with 'cgImage.width' (#81075)
* [Swiftify] Fix crash calling cgImage.width

cgImage.width calls the C function, CGImageGetWidth(CGImageRef).
Swift representation and Clang representation of this function
seem to have a parameter number mismatch, causing swiftify function
to crash.

rdar://149691207
(cherry picked from commit af8579fac0)

* [NFC] Fix test/Interop/ObjC/swiftify-import/getter.swift
2025-04-30 12:25:33 -07:00
Gabor Horvath
291a63fd80 [6.2][cxx-interop] Fix a crash with [[no_unique_address]]
Explanation: Swift does not support storing fields in the padding of the previous
fields just yet, so let's not import fields like that from C++.
Represent them as opaque blobs instead.
Issue: rdar://149072458
Risk: Low, the fix is targeted at a scenario that was crashing before.
Testing: Regression test added.
Original PR: #80786
Reviewer:
2025-04-25 12:51:13 +01:00
Gábor Horváth
1c92940446 Merge pull request #81047 from swiftlang/gaborh/span-ctor-crash-6.2
[6.2][cxx-interop] Work around crash in codegen when initializing C++ span
2025-04-23 23:47:46 -07:00
Gábor Horváth
0b1df04fc1 [6.2][cxx-interop] Work around crash in codegen when initializing C++ span
Explanation: C++ templates are imported as Swift generics.
Unfortunately, the codegen for some of the instantiations will crash
codegen due to a confusion in how Swift pointer types are mapped back to their
native counterparts. As a result, when a user is passing an
UnsafePointer<Element>? to a C++ span constructor we got a crash. The
user should never need the generic version of the initializer as we
already have an initializer taking an UnsafePointer<Element> in the C++
overlay. This PR avoids importing the templated span constructors to
work around this issue.
Issue: rdar://148961349
Risk: Low, the fix is very targeted.
Testing: Regression test added.
Original PR: #81030
Reviewer: @j-hui
2025-04-23 21:46:56 +01:00
Gábor Horváth
a3b9c409ef [6.2][cxx-interop] Properly import annotations from functions in namespace scope
Explanation: C++ namespaces imported as Swift enums. This was not
accounted for in a condition and that resulted in not importing lifetime
annotations for functions that are in namespace scope. This PR fixes
that condition.
Issue: rdar://149756644
Risk: Low, the fix is very targeted.
Testing: Regression test added.
Original PR: #80986
Reviewer: @j-hui
2025-04-23 16:18:11 +01:00
fahadnayyar
2f6fead77c Merge pull request #80706 from swiftlang/fahadnayyar/returns-unretained/diag-relax-templated-return-type
🍒 [6.2] [cxx-interop] Relax error when using SWIFT_RETURNS_(UN)RETAINED on templated return types resolving to non-frts
2025-04-18 16:14:32 -07:00
Pavel Yaskevich
65f78f3c01 Merge pull request #80807 from xedin/se-0461-renamings-6.2
[6.2][SE-0461] Replace `@execution(...)` with `@concurrent` and `nonisolated(nonsending)`
2025-04-16 20:47:14 -07:00
Becca Royal-Gordon
0a26b44aaa Merge pull request #80780 from beccadax/the-case-of-the-missing-member-6.2
🌸 [ClangImporter] Fix import of aliased enum cases
2025-04-16 19:52:17 -07:00
Pavel Yaskevich
826176a28a [AST] NFC: Add a convenient way to create implicit NonisolatedAttrs 2025-04-16 13:20:16 -07:00
Gábor Horváth
ae55f3e4ec Merge pull request #80631 from swiftlang/gaborh/nested-foreign-type-metadata-on-6.2 2025-04-14 11:10:25 -07:00
Gábor Horváth
710c26e87d Merge pull request #80710 from swiftlang/gaborh/escapable-type-nonesc-field-on-6.2 2025-04-14 11:10:04 -07:00
Becca Royal-Gordon
429128c2ab [ClangImporter] Fix import of aliased enum cases
When a C enum has multiple constants with the same value, ClangImporter selects one of them to import as an `EnumElementDecl` and imports the others as `VarDecl` “aliases” of that one. This helps preserve the invariant that each case of an enum has a unique raw value and is distinct for exhaustiveness checking.

However, a bug in that logic could sometimes cause the canonical case to be imported *twice*—once as an `EnumElementDecl` and again as a `VarDecl` alias. In this situation, the `EnumElementDecl` was not added to the enum’s member list, resulting in a malformed AST. This bug has apparently been present since early 2017 (!), but it seems to have been harmless until recently, when the `ComputeSideEffects` SIL pass recently became sensitive to it (probably because of either #79872 or #80263).

Correct this problem by modifying the memoization logic to retrieve the canonical case’s clang-side constant so the subsequent check will succeed. Additionally change a variable name and add comments to help clarify this code for future maintainers.

In lieu of adding new unit tests, this commit adds a (slightly expensive) conditional assertion to catch this kind of AST malformation. There are actually about twenty tests that will fail with just the assertion and not the fix, but I’ve updated one of them to enable the assertion even in release mode.

Fixes rdar://148213237. Followup to #80487, which added related assertions to the SIL layer.
2025-04-11 16:42:44 -07:00
fahadnayyar
f3ecb7ea8b [cxx-interop] convert CXXForeignReferenceTypeInitializers into SuppressCXXForeignReferenceTypeInitializers to be an opt-out flag
Turning the feature "ctor of C++ foreign reference types is callable as Swift Initializers" on by default.

rdar://148285972
2025-04-10 05:55:05 -07:00
fahadnayyar
5cab57439f [cxx-interop] Import parameterized public ctors of C++ foreign ref types as Swift Initializer (#80449)
Extends PR #79986 by adding support for calling parameterized C++ initializers from Swift. This patch synthesizes static factory methods corresponding to C++ parameterized constructors, allowing Swift to call them as Swift initializers (e.g., init(_:), init(_:_:), etc.). This patch also aded tests and logic to make sure that we emit no additional diagnostics when a C++ foreign ref type is just referred from Swift and its initializer is not explicitly called.

rdar://148285251
2025-04-10 05:55:05 -07:00
Gábor Horváth
8c4be8a37d [6.2][cxx-interop] Diagnose Escapable C++ types with non-escapable fields
Explanation: In Swift, Escapable types cannot have non-escapable stored
properties. Unfortunately, these checks could be circumvented via C++
interop, constructing invalid Swift code. This patch errors out on
importing C++ code of this shape.
Issue: rdar://148899224
Risk: Low, the fix is fairly targeted to the affected scenario.
Testing: Added tests to test suite
Original PR: #80671
Reviewer: John Hui
2025-04-10 10:23:57 +01:00
fahadnayyar
b7d05052bf [cxx-interop] Relax error when using SWIFT_RETURNS_(UN)RETAINED on templated return types resolving to non-frts (#78968)
We should not complain about usage of SWIFT_RETURNS_(UN)RETAINED for templated C++ APIs when instantiated with a non SWIFT_SHARED_REFERENCE types

rdar://143732201
2025-04-09 23:12:23 -07:00
Gábor Horváth
8e6daf75ec [6.2][cxx-interop] Fix a rare compilation error in reverse interop header
Explanation: Fix a compilation error in the generated reverse interop
header when a nested foreign type is used in a generic context and it is
reexposed to C++.
Issue: rdar://148597079
Risk: Low, the fix is fairly targeted to the affected scenario.
Testing: Added tests to test suite
Reviewer: @egorzhdan
2025-04-08 11:32:08 +01:00
Gábor Horváth
789359ced3 [cxx-interop] Fix not importing return type for certain functions
Explanation: Fixes that functions imported from C++ namespaces are
taking a different code path than functions importing from the global
namespace. This also fixes an error where the return type of a templated
function is sometimes not imported.
Scope: C++ forward interop.
Issue: rdar://148735986
Risk: Low, the fix is targeted to make C++ functions in namespaces take
a well tested code path that we already use for C++ functions in the
global scope.
Testing: Added tests to test suite
Reviewer: John Hui
2025-04-07 11:52:12 +01:00
Doug Gregor
c522138987 [Strict memory safety] Union member accessors are always unsafe
Union member accessors have no way to know what the "active field" is,
so consider them to always be unsafe.
2025-04-02 16:59:17 -07:00
John Hui
e8bcc52356 [cxx-interop] Fix access check for nested private C++ enums (#80366)
This patch fixes the access check for nested private C++ enums to look for the SWIFT_PRIVATE_FILEID of the enclosing C++ class, if any. Previously, the check was looking at for SWIFT_PRIVATE_FILEID on the enum decl itself (which is meaningless); that prevented nested private enum members from being accessible in Swift.

This patch also specializes the type signature of getPrivateFileIDAttrs to clarify the fact that SWIFT_PRIVATE_FILEID is not a meaningful annotation on anything other than CXXRecordDecl, because that is the only kind of decl that can assign access specifiers to its members.

rdar://148081340
2025-03-31 22:23:22 -07:00
fahadnayyar
9694cc8d70 [cxx-interop] Import default public ctor of C++ foreign ref types as Swift Initializer (#79986)
Building on top of PR #79288, this update synthesizes a static factory method using the default new operator, with a call to the default constructor expression for C++ foreign reference types, and imports them as Swift initializers.

rdar://147529406
2025-03-31 20:33:53 -07:00
John Hui
3b18849dcc [NFC] Remove stale FIXME about importing enum variants (#80358)
This comment is from 940a65a994, but is now stale.
2025-03-31 16:05:48 -07:00
John Hui
bbf92fd6e1 [cxx-interop] Import non-public members of SWIFT_PRIVATE_FILEID-annotated classes (#80320) 2025-03-26 22:41:38 -07:00
Egor Zhdan
7c494800a7 [cxx-interop] Avoid diagnosing missing lifetime operations in symbolic mode
When importing C++ decls in symbolic mode, class templates are not instantiated, which means they might not have a destructor or a move constructor. Make sure we are not trying to diagnose those missing lifetime operations in symbolic mode.

This fixes incorrect diagnostics that were emitted during indexing at the end of compilation:
```
warning: 'import_owned' Swift attribute ignored on type 'basic_string': type is not copyable or destructible
```

As a nice side effect, this moves the logic that emits these diagnostics from the request body, which might be invoked many times, to the importer itself, which is only invoked once per C++ class.

rdar://147421710
2025-03-21 18:07:22 +00:00
Gábor Horváth
ddd36a7cfc Merge pull request #79662 from swiftlang/gaborh/dynamic-self-frt
[cxx-interop] Interpret Self as a static shorthand for FRTs
2025-03-20 17:54:35 +00:00
Andrew Trick
d41c4d4cc9 ClangImporter: fix C++ memberwise inits to use @lifetime(immortal)
_unsafeNonEscapableResult no longer dsiables diagnostics at the call site. We
need to use a proper lifetime annotation for that.
2025-03-19 11:59:05 -07:00