From 18c5e23a31ca05654f445f20e48cd5920e7b872d Mon Sep 17 00:00:00 2001 From: Egor Zhdan Date: Thu, 11 Sep 2025 15:32:38 +0100 Subject: [PATCH] [cxx-interop] Fix a crash when calling `std::any_cast` from Swift In libc++, `std::any_cast` is declared as a friend function of `std::any`. ClangImporter was not correctly handling friend functions declared within structs within namespaces correctly. rdar://147261941 --- .../Cxx/stdlib/Inputs/module.modulemap | 6 +++++ test/Interop/Cxx/stdlib/Inputs/std-any.h | 6 +++++ test/Interop/Cxx/stdlib/use-std-any.swift | 23 +++++++++++++++++++ 3 files changed, 35 insertions(+) create mode 100644 test/Interop/Cxx/stdlib/Inputs/std-any.h create mode 100644 test/Interop/Cxx/stdlib/use-std-any.swift diff --git a/test/Interop/Cxx/stdlib/Inputs/module.modulemap b/test/Interop/Cxx/stdlib/Inputs/module.modulemap index 0ca81ec0670af..330d63b5d1af6 100644 --- a/test/Interop/Cxx/stdlib/Inputs/module.modulemap +++ b/test/Interop/Cxx/stdlib/Inputs/module.modulemap @@ -1,3 +1,9 @@ +module StdAny { + header "std-any.h" + requires cplusplus + export * +} + module StdNumeric { header "std-numeric.h" requires cplusplus diff --git a/test/Interop/Cxx/stdlib/Inputs/std-any.h b/test/Interop/Cxx/stdlib/Inputs/std-any.h new file mode 100644 index 0000000000000..930280a0b682c --- /dev/null +++ b/test/Interop/Cxx/stdlib/Inputs/std-any.h @@ -0,0 +1,6 @@ +#include +#include + +inline std::any getStdAnyString() { + return std::string("abc210"); +} diff --git a/test/Interop/Cxx/stdlib/use-std-any.swift b/test/Interop/Cxx/stdlib/use-std-any.swift new file mode 100644 index 0000000000000..513ee6ccf9b81 --- /dev/null +++ b/test/Interop/Cxx/stdlib/use-std-any.swift @@ -0,0 +1,23 @@ +// RUN: %target-run-simple-swift(-I %S/Inputs -cxx-interoperability-mode=upcoming-swift) +// RUN: %target-run-simple-swift(-I %S/Inputs -cxx-interoperability-mode=upcoming-swift -Xcc -std=c++17) +// RUN: %target-run-simple-swift(-I %S/Inputs -cxx-interoperability-mode=upcoming-swift -Xcc -std=c++20) + +// REQUIRES: executable_test + +// In Microsoft STL, all overloads of std::any_cast return a dependent templated +// type, which Swift isn't able to instantiate. +// UNSUPPORTED: OS=windows-msvc + +import StdlibUnittest +import StdAny +import CxxStdlib + +var StdAnyTestSuite = TestSuite("StdAny") + +StdAnyTestSuite.test("std.any_cast") { + let a1 = getStdAnyString() + let c1 = std.any_cast(a1) as std.string + expectEqual(c1, std.string("abc210")) +} + +runAllTests()