Skip to content

Commit 17ae635

Browse files
[SwiftToCxx] Implementing the Swift Error representation in C++
1 parent b1a939f commit 17ae635

File tree

3 files changed

+29
-2
lines changed

3 files changed

+29
-2
lines changed

lib/PrintAsClang/PrintSwiftToClangCoreScaffold.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ static void printTypeMetadataResponseType(SwiftToClangInteropContext &ctx,
158158

159159
void printCxxNaiveException(raw_ostream &os) {
160160
os << "/// Naive exception class that should be thrown\n";
161-
os << "class NaiveException {\n";
161+
os << "class NaiveException : public swift::Error {\n";
162162
os << "public:\n";
163163
os << " inline NaiveException(const char * _Nonnull msg) noexcept : "
164164
<< "msg_(msg) { }\n";

stdlib/public/SwiftShims/_SwiftCxxInteroperability.h

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ extern "C" void *_Nonnull swift_retain(void *_Nonnull) noexcept;
3232

3333
extern "C" void swift_release(void *_Nonnull) noexcept;
3434

35+
extern "C" void *_Nonnull swift_errorRetain(void *_Nonnull swiftError) noexcept;
36+
37+
extern "C" void swift_errorRelease(void *_Nonnull swiftError) noexcept;
38+
3539
inline void *_Nonnull opaqueAlloc(size_t size, size_t align) noexcept {
3640
#if defined(_WIN32)
3741
void *r = _aligned_malloc(size, align);
@@ -172,6 +176,29 @@ template <class T> inline void *_Nonnull getOpaquePointer(T &value) {
172176
return reinterpret_cast<void *>(&value);
173177
}
174178

179+
namespace swift {
180+
class Error {
181+
public:
182+
Error() {}
183+
~Error() {
184+
if (opaqueValue)
185+
swift_errorRelease(opaqueValue);
186+
}
187+
void* _Nonnull getPointerToOpaquePointer() { return opaqueValue; }
188+
Error(Error &&other) : opaqueValue(other.opaqueValue) {
189+
other.opaqueValue = nullptr;
190+
}
191+
Error(const Error &other) {
192+
if (other.opaqueValue)
193+
swift_errorRetain(other.opaqueValue);
194+
opaqueValue = other.opaqueValue;
195+
}
196+
197+
private:
198+
void * _Nonnull opaqueValue = nullptr;
199+
};
200+
}
201+
175202
} // namespace _impl
176203

177204
#pragma clang diagnostic pop

test/Interop/SwiftToCxx/core/swift-impl-defs-in-cxx.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@
9999
// CHECK-NEXT: #endif
100100
// CHECK-EMPTY:
101101
// CHECK-NEXT: /// Naive exception class that should be thrown
102-
// CHECK-NEXT: class NaiveException {
102+
// CHECK-NEXT: class NaiveException : public swift::Error {
103103
// CHECK-NEXT: public:
104104
// CHECK-NEXT: inline NaiveException(const char * _Nonnull msg) noexcept : msg_(msg) { }
105105
// CHECK-NEXT: inline NaiveException(NaiveException&& other) noexcept : msg_(other.msg_) { other.msg_ = nullptr; }

0 commit comments

Comments
 (0)