Commit Graph

230 Commits

Author SHA1 Message Date
Egor Zhdan
f271db22bd Merge pull request #83429 from CrazyFanFan/feature/cxx_map_mapvalues_and_compactmapvalues
Adds `mapValues` and `compactMapValues` to CxxDictionary:
2025-10-13 12:00:57 +01:00
Henrik G. Olsson
b8592ff33c add cstddef to libstdc++ module map 2025-10-07 11:34:30 -07:00
Henrik G. Olsson
5519be8b7c Move span to conditional header in libstdc++ module map
`span` is not available in all versions of libstd++, so make it a
conditional header. Also adds other missing c++20 headers.

Fixing this triggered an assert when importing a constant initialized
`wchar_t` variable, so that is also fixed. The reason is that `wchar_t`
is mapped to `Unicode.Scalar`, which cannot be directly initialized by
integer literals in Swift, triggering an assert when looking up the
protocol conformance for `_ExpressibleByBuiltinIntegerLiteral`.

rdar://162074714
2025-10-06 16:02:35 -07:00
Henrik G. Olsson
f7d5902db5 add std::span to module map for libstdc++ 2025-10-02 16:37:45 -07:00
Gabor Horvath
43cef148cb [cxx-interop] Do not consider std::span<T>::size and co unsafe
Since these APIs operate on unsafes we consider them unsafe by default.
This PR adds APINotes to override these defaults as these APIs will not
touch the underlying buffer. This should slightly reduce the number of
`unsafe`s in user code.

rdar://159839254
2025-09-25 11:28:26 +01:00
Egor Zhdan
4b0e8861f5 [cxx-interop] Fix warning about missing unsafe 2025-08-28 12:10:14 +01:00
Egor Zhdan
4dda78846d [cxx-interop] Provide overlay for std::wstring
This adds CxxStdlib overlay features to `std::wstring` similarly to `std::string`, `std::u16string`, etc.

This lets clients e.g. convert between Swift String and C++ wide string simply by calling an initializer.

rdar://159272493
2025-08-27 13:20:09 +01:00
Egor Zhdan
7dc8873266 [cxx-interop] Simplify std::string construction in the overlay
libc++ provides a 2-parameter constructor of `std::string`, so we can apply the logic under `#if os(Windows)` on Apple platforms too.

This avoids deserialization issues when building some complex projects that are still under investigation.

rdar://145939013
2025-08-14 17:45:19 +01:00
Gabor Horvath
2bd8684868 [cxx-interop] Add span accessors to std.string variants
rdar://146944876
2025-08-13 15:49:39 +01:00
Gábor Horváth
35b5c817b2 Merge pull request #83520 from Xazax-hun/check-safety-function-types 2025-08-08 06:39:39 +01:00
fahadnayyar
9a01358132 [C++ Interop] Deprecate Optional argument overloads of std.string initializer in Swift’s C++ Stdlib Overlay (#83223)
This patch addresses potential ambiguity and unsafe behavior by
deprecating initializer overloads for `std.string` that accept optional
arguments (`string?`). These overloads previously allowed implicit
initialization from optional pointers (`UnsafePointer<CChar>?`), causing
unclear or unintended behavior.

- Deprecated: `init(_ string: UnsafePointer<CChar>?)`, guiding users
toward the explicit, non-optional initializer.
- Unavailable: `init(_ string: String?)`, explicitly preventing misuse
from optional Swift strings.

rdar://148041893
2025-08-05 15:22:02 -07:00
Gabor Horvath
402ad33463 [StrictMemorySafety] Check the safety of return types of calls
Previously, we skipped checking the return type of a function for safety
as we expected to warn at the use of the returned value:

  let x = returnsUnsafe()
  usesUnsafe(x) // warn here

Unfortunately, this resulted in missing some unsafe constructs that can
introduce memory safety issues when the use of the return value had a
different shape resulting in false negatives for cases like:

  return returnsUnsafe()

or

  usesUnsafe(returnsUnsafe())

This PR changes the analysis to always take return types of function
calls into account.

rdar://157237301
2025-08-05 12:16:44 +01:00
Crazy凡
44269122c0 Implement mapValues and compactMapValues for CxxDictionary 2025-07-30 22:45:31 +08:00
Egor Zhdan
19c7884ec5 [cxx-interop] Allow creating Dictionary from std::map
This adds an initializer to `Swift.Dictionary` that takes an instance of `std::map` or `std::unordered_map`.

rdar://155050682
2025-07-05 21:54:11 +01:00
Gabor Horvath
3dda301496 [cxx-interop] Reenable C++ benchmarks
The underlying issue was fixed in #82309

rdar://149402670
2025-06-24 17:57:42 +01:00
Allan Shortlidge
008efc432f stdlib: Fix missing unsafe operators in more places.
Add `unsafe` where it is still missing. I missed these in previous passes due
to conditional compilation.
2025-06-22 18:46:57 -07:00
Egor Zhdan
e4fb2549b9 Merge pull request #82309 from swiftlang/egorzhdan/span-shared-cache
[cxx-interop] Make usages of Swift Span `@_alwaysEmitIntoClient` in the overlay
2025-06-19 16:46:07 +01:00
michael-yuji
cf2f7154a5 Merge pull request #77836 from michael-yuji/mchiu/freebsd
[FreeBSD] Adding FreeBSD support
2025-06-18 19:59:48 -07:00
Egor Zhdan
67e2024417 [cxx-interop] Make usages of Swift Span @_alwaysEmitIntoClient in the overlay
This fixes a regression where projects that use the C++ stdlib overlay stop building because of a linker error:
```
ld: Shared cache eligible dylib cannot link to ineligible dylib '@rpath/libswiftCompatibilitySpan.dylib'.
```

Usages of `Span<T>` would generally cause a type metadata accessor to be emitted for `Swift.Span`. This becomes a problem with backdeployment, since Span is partially defined in a compatibility binary.

This change adds `@_alwaysEmitIntoClient` to generic usages of `Span` to prevent the type metadata accessor from being emitted into `libswiftCxx.a`.

rdar://152192080
2025-06-17 19:42:14 +01:00
Egor Zhdan
607dd4a7d4 [cxx-interop] Import nullability of templated function parameters correctly
This teaches ClangImporter to respect the `_Nonnull`/`_Nullable` arguments on templated function parameters.

Previously Swift would only import a non-annotated function overload. Using an overload that has either  `_Nonnull` or `_Nullable` would result in a compiler error. The non-annotated overload would get imported with incorrect nullability: Swift would always assume non-null pointers, which was inconsistent with non-templated function parameters, which are mapped to implicitly unwrapped optionals.

With this change all three possible overloads are imported, and all of them get the correct nullability in Swift.

rdar://151939344
2025-06-13 18:15:52 +01:00
michael-yuji
8738e722bd Merge branch 'main' into mchiu/freebsd 2025-05-28 14:44:11 -07:00
Ian Anderson
0027779029 Merge pull request #81726 from ian-twilightcoder/remove_darwin_overlay
[CMake][Darwin] Remove support for building the SDK overlays on Apple platforms
2025-05-26 12:19:28 -07:00
Ian Anderson
15345ef2d5 [CMake][Darwin] Remove support for building the SDK overlays on Apple platforms
The SDK overlays have been provided in the Apple SDKs for many years, and the interface and implementation has diverged in more recent years such that trying to build the Swift version no longer works. Remove all of the dead code.

rdar://151889154
2025-05-23 23:38:08 -07:00
Henrik G. Olsson
262a53f599 [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
2025-05-22 15:36:19 -07:00
michael-yuji
9a948a9c3b Merge branch 'main' into mchiu/freebsd 2025-05-21 16:29:16 -07:00
Alastair Houghton
b2f0d92eaa [Cxx] Build the C++ interop support library for the Static SDK for Linux.
We need the C++ interop support library to make the build work, as
the Runtime module uses C++ interop.

(Also, we should build it, because some user programs might want to
use C++ interop.)

rdar://147201087
2025-05-15 14:30:12 +01:00
Egor Zhdan
16b280862a [cxx-interop] Do not install binary .swiftmodule files for the overlays
This fixes a deserialization failure in the compiler that occurred while loading the CxxStdlib overlay module:
```
Cross-reference to module 'Swift'
... Optional
... some
... with type <τ_0_0 where τ_0_0 : ~Copyable, τ_0_0 : ~Escapable> (Optional<τ_0_0>.Type) -> (τ_0_0) -> Optional<τ_0_0>
```

This was happening because the overlays were built against a different version of the Swift stdlib than is being used. The compiler is able to rebuild the Cxx and CxxStdlib modules from their textual interfaces. Let's use that feature unconditionally in production toolchains to avoid this kind of binary incompatibilities.

rdar://150416863
2025-05-10 22:55:06 +01:00
Gabor Horvath
7d0d872bdb [cxx-interop] Proper conversions between MutableSpan and C++ span
One of the initializers were missing and the other was crashing at
runtime due to a faulty signature in the overlay.

rdar://149846666
2025-04-25 11:28:32 +01:00
Egor Zhdan
1ea54588d0 Merge pull request #78841 from CrazyFanFan/feature/replace_self_type_with_generics
[cxx-interop]: Refactor `CxxDictionary` protocols to use generics instead of `Self`.
2025-04-07 11:50:36 +01:00
Doug Gregor
0100104ff7 [stdlib] Reinstate AllowUnsafeAttribute experimental feature on libraries
We need this so that older compilers can handle the .swiftinterface
files we generate. It's unnecessary for newer compilers and can be
removed later.

Fixes rdar://148529962.
2025-04-03 18:07:19 -07:00
Crazy凡
b4531a6ae8 [cxx-interop]: Refactor CxxDictionary protocols to use generics instead of Self.
- Add support for merging `std::map` and `std::unordered_map` with each other seamlessly.
- Add support for typed throws
2025-04-02 09:14:06 +08:00
Allan Shortlidge
c6cbcd8553 stdlib: Address StrictMemorySafety warnings in Cxx String related code. 2025-03-31 16:45:08 -07:00
Henrik G. Olsson
87f5309144 [Swiftify] enable mutable span (#80387)
* [Swiftify] Emit Mutable[Raw]Span when possible

Previously wrappers would use UnsafeMutable[Raw]Pointer for mutable
pointers, and Span for non-const std::span, to prevent the compiler from
complaining that MutableSpan didn't exist.

Now that MutableSpan has landed we can finally emit MutableSpan without
causing compilation errors. While we had (disabled) support for MutableSpan
syntax already, some unexpected semantic errors required additional
changes:
 - Mutable[Raw]Span parameters need to be inout (for mutation)
 - inout ~Escapable paramters need explicit lifetime annotations
 - MutableSpan cannot be directly bitcast to std::span, because it is
   ~Copyable, so they need unwrapping to UnsafeMutableBufferPointer

rdar://147883022

* [Swiftify] Wrap if-expressions in Immediately Called Closures

When parameters in swiftified wrapper functions are nullable, we use
separate branches for the nil and nonnil cases, because
`withUnsafeBufferPointer` (and similar) cannot be called on nil.
If-expressions have some limitations on where they are allowed in the
grammar, and cannot be passed as arguments to a function. As such, when
the return value is also swiftified, we get an error when trying to
pass the if-expression to the UnsafeBufferPointer/Span constructor.
While it isn't pretty, the best way forward seems to be by wrapping the
if-expressions in Immediately Called Closures.

The closures have the side-effect of acting as a barrier for 'unsafe':
unsafe keywords outside the closure do not "reach" unsafe expressions
inside the closure. We therefore have to emit "unsafe" where unsafe
expressions are used, rather than just when returning.

rdar://148153063
2025-03-29 05:05:01 -07:00
Gabor Horvath
3d6c714cd6 [cxx-interop] Add span property to std::vector
rdar://146944876
2025-03-20 16:15:06 +00:00
Andrew Trick
955d089a90 CxxSpanReturnThunkBuilder: use _cxxOverrideLifetime(_:copying:)
Do not rely on the @_unsafeNonescapableResult attribute. That attribute is only
for temporarily working around bugs! And it only affects lifetime diagnostics within
the function. It has no affect on the caller's diagnostics, so it won't solve
this problem:

func macroGeneratedThunk() -> CxxSpan<Int> {
  return _unsafeRemoveLifetime(Span...)
}

We cannot simply add @_unsafeRemoveLifetime to the thunk, because SwiftSyntax
does not natively support the attribute. We don't want to add SwiftSyntax
support because this attribute will never be supported syntax!

Instead, use `_overrideLifetime` copying the `Void` type to remove a dependency:

func macroGeneratedThunk() -> CxxSpan<Int> {
  return _cxxOverrideLifetime(Span..., copying: ())
}
2025-03-19 11:59:05 -07:00
Andrew Trick
e91981266b Update CXXSpan for strict @lifetime 2025-03-19 11:59:04 -07:00
Egor Zhdan
e32e64353f [cxx-interop] Conform std::string to ExpressibleByStringInterpolation
This adds conformances for C++ string types (`std::string`, `std::u16string`, `std::u32string`) to `Swift.ExpressibleByStringInterpolation`.

These conformances currently implicitly use `DefaultStringInterpolation`. In the future we can provide more performant interpolation mechanisms for C++ strings specifically that avoid the extra conversion between Swift String and C++ string types.

rdar://147249169
2025-03-18 15:54:56 +00:00
Michael Chiu
26dd5c3787 FreeBSD cxx stdlib and tests fixes 2025-03-14 02:15:15 -04:00
Doug Gregor
733dd86c92 Merge pull request #79896 from DougGregor/strict-memory-safety-cleanups
Strict memory safety cleanups
2025-03-11 01:26:30 -07:00
Doug Gregor
9f2859edd8 Update Cxx library for strict memory safety 2025-03-10 15:42:29 -07:00
Guillaume Lessard
082aaecc9c [stdlib] update availability for CxxSpan (#79883) 2025-03-10 10:13:39 -07:00
Doug Gregor
89d0277a35 Enable strict memory safety in the Cxx/CxxStdlib modules 2025-02-26 14:28:30 -08:00
Allan Shortlidge
eb75c0cd23 CMake: Bring back -enable-experimental-feature Span.
Reenable it temporarily (until after 6.2 is released) for compatibility with
older compilers.
2025-02-16 07:15:44 -08:00
Allan Shortlidge
a0ac6c74e3 Tests: Stop referring to the Span feature since it has been removed. 2025-02-15 17:23:14 -08:00
Gabor Horvath
df27b79579 [cxx-interop] Work around lifetime errors in SwiftifyImport generated code
Unfortunately, this was not discovered earlier as swift-ide-test is not
invoking the SIL passes that produce this diagnostic. When creating
Swift spans from C++ spans we have no lifetime dependency information to
propagate as C++ spans are modeled as escapable types. Hence, this PR
introduces a helper function to bypass the lifetime checks triggered by
this discepancy. Hopefully, the new utility will go away as the lifetime
analysis matures on the Swift side and we get standardized way to deal
with unsafe lifetimes.
2025-02-14 16:40:43 +00:00
Egor Zhdan
52a2638b3f Merge pull request #78353 from swiftlang/egorzhdan/nfc-fix-cxx-warning
[cxx-interop] NFC: Fix a warning
2025-01-02 12:15:39 +00:00
Egor Zhdan
67da2026ea [cxx-interop] NFC: Fix a warning
This fixes a build warning:
```
swift/stdlib/public/Cxx/CxxDictionary.swift:168:9: warning: variable 'iter' was never mutated; consider changing to 'let' constant
```
2024-12-23 16:26:36 +00:00
Andrew Trick
60845673b0 Fix Span initialization from CxxSpan.
CxxSpan is trivial, but not immortal.

This initializer is diagnosed with an error after enabling trivial dependence
enforcement. Correct this with an _overrideLifetime call. This could be avoided
if we had a another way to tell the compiler that CxxSpan.__dataUnsafe()
produced a pointer with the same effective lifetime as the CxxSpan.
2024-12-18 16:58:49 -08:00
Egor Zhdan
0fa65bea8a Merge pull request #77864 from CrazyFanFan/feature_cxxmap
[cxx-interop]: Enhance CxxDictionary with Merging, Initializer, and Unsafe Erasure
2024-12-18 13:37:44 +00:00
Gábor Horváth
8398e693e7 Merge pull request #77700 from swiftlang/gaborh/span-conversion
[cxx-interop] Explicit conversions between Swift and C++ spans
2024-12-13 19:54:27 +00:00