This improves support for initializing instances of `std::optional` from Swift. Previously only a null optional could be initialized directly from Swift. Now instantiations of `std::optional` will get a Swift initializer that takes the wrapped value as a parameter.
rdar://118026392
Previously, we would get two copies, one accessing the pointee and one
when we pass the pointee as a method as the implicit self argument.
These copies are unsafe as they might introduce slicing. When
addressable paramaters features are enabled, we no longer make these
copies for the standard STL types. Custom smart pointers can replicate
this by making the lifetime dependency between the implicit object
parameter and the returned reference of operator* explicit via a
lifetime annotation.
rdar://154213694&128293252&112690482
While I could not trigger a scenario where the generated macro triggers
a compilation error, the generated code is definitely not valid Swift.
rdar://151422108
Parameters can be named with keywords without escaping, because it's
unambiguous in the grammar that they are parameters. They still need to
escaped when referred to inside the function body however. This escapes
all references to parameters using backticks.
Parameter names are also checked for clashes with the function name - in
such cases the parameter is renamed in the same way as unnamed
parameters.
rdar://151024645
* [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
While we expect our users to use type aliases for template
instantiations, there are some contexts when we import instantiations
without aliases. Unfortunately, in case of C++ span we generated a name
for the instantiation that cannot be a syntactically valid Swift type
due to unary negation appearing in the type name. This PR replaces the
unary negation with "Neg" in the type name and also fixed a bug that
ended up printing certain unsigned values as signed. Moreover, this PR
also fixes some other fallouts in the SwiftifyImport macro.
rdar://146833480
__counted_by return values with .lifetimeDependence are now mapped to
Span instead of UnsafeBufferPointer. Also fixes bug where std::span
return values would map to Span even if lifetime dependence info was
missing.
importBoundsAttributes and importSpanAttributes are merged into a single
function named swiftify. This allows us to not have to duplicate the
effort of attaching _SwiftifyImport macros, but is also necessary to
allow importing a function with both __counted_by and std::span types.
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.
We do not need to borrow from view objects passed by value but we need
to borrow from owners taken by const reference regardless of whether it
was annotated using lifetimebound or lifetime_capture_by.
Support adding safe wrappers for APIs returning std::span depending on
the this object. This also fixes an issue for APIs with 0 parameters.
rdar://139074571
A previous PR already added support to the SwiftifyImport macro to
generate safe wrappers. This PR makes ClangImporter emit the macro to do
the transformation.
A first step towards creating safe overloads for C++ APIs using span
(rdar://139074571).
Note that we need to mark span as owned because it the libc++
implementation was mistakenly recognized as owned and might now rely on
span methods like `data` being renamed as `__dataUnsafe`. We will change
it under a new interop version. But for the time being, we want
consistent behavior across stdlib versions.
The PR https://github.com/swiftlang/swift/pull/77857 added windows-specific workaround for https://github.com/swiftlang/swift/issues/77856, that happened after https://github.com/swiftlang/swift/pull/77843. Unfortunately this caused a new issue on windows - https://github.com/swiftlang/swift/issues/78119. It looks like windows is suffering from a similar serialization issue as libstdc++, although its even more complex as the callAsFunction is not only a derived function from a base class, the base class although has a static call operator. In any case, the libstdc++ callAsFunction deserialization fix should align with the static operator () deserialization too, so for now make windows use the same workaround as other platforms to avoid the deserialization crash (77856).
This change was tested on i686 windows too, ensuring that IR verifier crash no longer happens
When explicitly asked not to load the C++ standard library, Swift should not emit warnings for missing libstdc++.
This fixes a compiler warning when building the Cxx module on Linux.
`__msvc_bit_utils.hpp` was added in a recent version of MSVC, and it is causing build errors for SwiftCompilerSources:
```
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.39.33519\include\numeric:598:12: error: function '_Select_countr_zero_impl<unsigned long long, (lambda at C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.39.33519\include\numeric:598:55)>' with deduced return type cannot be used before it is defined
return _Select_countr_zero_impl<_Common_unsigned>([=](auto _Countr_zero_impl) {
```
This change references the `__msvc_bit_utils.hpp` header from the modulemap. Since we still need to support older versions of Visual Studio that do not provide `__msvc_bit_utils.hpp`, this also teaches ClangImporter to inject an empty header file named `__msvc_bit_utils.hpp` into the system include directory, unless it already exists.
rdar://137066642
This fixes test failures of libcxx-module-interface.swift and
libcxx-symbolic-module-interface.swift where the std module was split.
e.g building against a MacOS 14.4 SDK.
While initializing a `std::function` that takes `const std::string&` as a parameter currently crashes, changing the parameter type to `std::string` should work fine.
The header was defining a function, the function created a lambda, and
the lambda was transformed into a `std::function`. This transformation
is incorrect because the function scope does not have linkage, so the
instantiated types will not have linkage either, causing the error
below.
```
.../include/c++/11.2.0/bits/invoke.h:104:5:
error: function 'std::__invoke_r<int, (lambda at .../swift/test/Interop/Cxx/stdlib/Inputs/std-function.h:9:10) &, int>' is used but not defined in this translation unit, and cannot be defined in any other translation unit because its type does not have linkage
102 │ template<typename _Res, typename _Callable, typename... _Args>
103 │ constexpr enable_if_t<is_invocable_r_v<_Res, _Callable,
_Args...>, _Res>
104 │ __invoke_r(_Callable&& __fn, _Args&&... __args)
│ ╰─ error: function 'std::__invoke_r<int, (lambda at .../swift/test/Interop/Cxx/stdlib/Inputs/std-function.h:9:10) &, int>' is used but not defined in this translation unit, and cannot be defined in any other translation unit because its type does not have linkage
105 │ noexcept(is_nothrow_invocable_r_v<_Res, _Callable,
_Args...>)
106 │ {
}
```
Declaring the function `inline` forces each TU to have their own copies
of the function, which avoids the instantiated templates from being in a
different TU than the one using them.
The header would not have worked in a normal C++ program, since none of
the functions declare linkage, they would have been defined in each TU
that included the header and it would fail linking as soon as two of
those TU tried to be linked together. Declaring the functions `inline`
avoids the problem (a more normal header, only with declarations, would
also worked).
For C++ types that are defined in the bridging header, or are `#include`-d from the bridging header, we did not generate the automatic conformances to `CxxSequence`, `CxxRandomAccessCollection` protocols.
To check whether we should try to conform a C++ type to those protocols, the compiler checks for the presence of `requires cplusplus` in the module declaration in a modulemap file. This check is there to prevent us from accidentally pulling in `Cxx`/`CxxStdlib` modules when a client is importing a C library.
This change makes sure those conformances are generated.
rdar://121927459
If the C++ type of a function parameter defines a custom copy constructor, assume that it is safe to use from Swift. This matches the heuristic that we use to detect if a C++ method is safe based on the return type.
rdar://121391798
The test was passing by accident: we didn't properly check `std::pair` type for completeness, and assumed that it is incomplete.
This updates the test to actually verify the behavior that is specified in the vision document.
This makes sure that `std::function` is imported consistently on supported platforms, and that it allows basic usage: calling a function with `callAsFunction`, initializing an empty function, and passing a function retrieved from C++ back to C++ as a parameter.
rdar://103979602