Skip to content

Commit 33335f9

Browse files
authored
Merge pull request #59624 from zoecarver/disable-eager-import
2 parents 24caf94 + ba7e6e4 commit 33335f9

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

50 files changed

+896
-198
lines changed

SwiftCompilerSources/Sources/Basic/SourceLoc.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ public struct SourceLoc {
2727
guard bridged.isValid() else {
2828
return nil
2929
}
30-
self.locationInFile = bridged.getOpaquePointerValue().assumingMemoryBound(to: UInt8.self)
30+
self.locationInFile = bridged.__getOpaquePointerValueUnsafe().assumingMemoryBound(to: UInt8.self)
3131
}
3232

3333
public var bridged: swift.SourceLoc {
@@ -57,7 +57,7 @@ public struct CharSourceRange {
5757
}
5858

5959
public init?(bridged: swift.CharSourceRange) {
60-
guard let start = SourceLoc(bridged: bridged.getStart()) else {
60+
guard let start = SourceLoc(bridged: bridged.__getStartUnsafe()) else {
6161
return nil
6262
}
6363
self.init(start: start, byteLength: bridged.getByteLength())

SwiftCompilerSources/Sources/Basic/Utils.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ extension String {
6565
/// Underscored to avoid name collision with the std overlay.
6666
/// To be replaced with an overlay call once the CI uses SDKs built with Swift 5.8.
6767
public init(_cxxString s: std.string) {
68-
self.init(cString: s.c_str())
68+
self.init(cString: s.__c_strUnsafe())
6969
withExtendedLifetime(s) {}
7070
}
7171
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# C++ Interop User Manual
2+
3+
The following document explains how C++ APIs are imported into Swift and is targeted at users of C++ interoperability. Hopefully this document will help you understand why the compiler cannot import various APIs and help you update these APIs to be useable from Swift. First, the document will lay out some API patterns and definitions, then it will discuss how the Swift compiler decides if an API should be usable in Swift.
4+
5+
## Reference Types
6+
7+
Reference types have reference semantics and object identity. A reference type is a pointer (or “reference”) to some object which means there is a layer of indirection. When a reference type is copied, the pointer’s value is copied rather than the object’s storage. This means reference types can be used to represent non-copyable types in C++. Any C++ APIs that use reference types must have at least one layer of indirection to the type (a pointer or reference). Currently reference types must be immortal (never deallocated) or have manually managed lifetimes. You can specify a type has reference semantics by using the `import_reference` swift attribute.
8+
9+
## Owned Types
10+
11+
Owned types “own” some storage which can be copied and destroyed. An owned type must be copyable and destructible. The copy constructor must copy any storage that is owned by the type and the destructor must destroy that storage. Copies and destroys must balance out and these operations must not have side effects. Examples of owned types include `std::vector` and `std::string`. The Swift compiler will assume that any types which do not contain pointers are owned types. You can also specify a type is an owned type by using the `import_owned` swift attribute.
12+
13+
## Iterator Types
14+
15+
An iterator represents a point in a range. Iterator types must provide a comparison operator and increment operator (increment or ++ operators are imported as a member called successor). Iterators can be returned by `begin` and `end` methods to form a range which will automatically be imported as a Sequence in Swift. Iterators can often be inferred by the compiler using the C++ iterator traits, but you can also specify a type is an iterator by using the `import_iterator` swift attribute.
16+
17+
## Trivial Types
18+
19+
Trivial types can be copied by copying the bits of a value of the trivial type and do not need any special destruction logic. Trivial types are inferred by the compiler and cannot be specified using an attribute. Trivial types own their storage, so rules below that apply to owned types also apply to trivial types (specifically regarding projections). Pointers are not trivial types. When Objective-C++ mode is enabled, C++ types that hold Objective-C classes are still considered trivial, even though they technically violate the above contract.
20+
21+
## Unsafe Types
22+
23+
All types which do not fall into one of the above categories are considered unsafe. Any unsafe API, including unsafe types that are copyable and destructible may be imported using the `import_unsafe` swift attribute. There are two kinds of unsafe types: **unsafe pointer types** and **un-importable types**.
24+
25+
**Unsafe Pointer Types:** are types which contain an un-owned pointer. This type is assumed to represent an unsafe memory projection when used as a return type for the method of an owned type.
26+
27+
**Un-importable Types:** are types that are not copyable or destructible. These types cannot be represented in Swift, so they cannot be imported (even if they are marked with the `import_unsafe` attribute).
28+
29+
## API rules
30+
31+
The Swift compiler enforces certain API rules, not to ensure a completely safe C++ API interface, but to prevent especially unsafe patterns that will likely lead to bugs. Many of these unsafe patterns stem from the subtly different lifetime semantics in C++ and Swift and aim to prevent memory projections of owned types. The currently enforced rules are as follows:
32+
33+
* Un-importable types are not allowed to be used in any contexts.
34+
* Unsafe pointer types are not allowed to represent unsafe memory projections from owned types. Note: unsafe pointer types *are* allowed to represent memory projections from reference types. Note: the Swift compiler assumes that global and static functions do not return projections.
35+
* Iterators are not allowed to represent unsafe memory projections from owned types. Iterators may be used safely through the `CxxIterator` and `CxxSequence` protocols which iterators and ranges automatically conform to.
36+
* Members of an unsafe type that is explicitly imported using the `import_unsafe` swift attribute are still subject to the above rules. Each individual unsafe member must also have the `import_unsafe` swift attribute to be usable.
37+

include/swift/AST/DiagnosticsClangImporter.def

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,10 @@ WARNING(too_many_class_template_instantiations, none,
128128
"template instantiation for '%0' not imported: too many instantiations",
129129
(StringRef))
130130

131+
WARNING(api_pattern_attr_ignored, none,
132+
"'%0' swift attribute ignored on type '%1': type is not copyable or destructible",
133+
(StringRef, StringRef))
134+
131135
NOTE(macro_not_imported_unsupported_operator, none, "operator not supported in macro arithmetic", ())
132136
NOTE(macro_not_imported_unsupported_named_operator, none, "operator '%0' not supported in macro arithmetic", (StringRef))
133137
NOTE(macro_not_imported_invalid_string_literal, none, "invalid string literal", ())
@@ -143,8 +147,30 @@ NOTE(return_type_not_imported, none, "return type not imported", ())
143147
NOTE(parameter_type_not_imported, none, "parameter %0 not imported", (const clang::NamedDecl*))
144148
NOTE(incomplete_interface, none, "interface %0 is incomplete", (const clang::NamedDecl*))
145149
NOTE(incomplete_protocol, none, "protocol %0 is incomplete", (const clang::NamedDecl*))
146-
NOTE(unsupported_builtin_type, none, "built-in type '%0' not supported", (StringRef))
150+
NOTE(incomplete_record, none, "record '%0' is not defined (incomplete)", (StringRef))
151+
NOTE(record_over_aligned, none, "record '%0' is over aligned", (StringRef))
152+
NOTE(record_non_trivial_copy_destroy, none, "record '%0' is not trivial to copy/destroy", (StringRef))
153+
NOTE(record_is_dependent, none, "record '%0' is dependent", (StringRef))
154+
NOTE(record_parent_unimportable, none, "record %0's parent is not importable", (StringRef))
155+
NOTE(reference_passed_by_value, none, "function uses foreign reference type "
156+
"'%0' as a value in %1 types which breaks "
157+
"'import_reference' contract (outlined in "
158+
"C++ Interop User Manual).",
159+
(StringRef, StringRef))
160+
NOTE(record_not_automatically_importable, none, "record '%0' is not "
161+
"automatically importable: %1. "
162+
"Refer to the C++ Interop User "
163+
"Manual to classify this type.",
164+
(StringRef, StringRef))
165+
NOTE(projection_not_imported, none, "C++ method '%0' that returns unsafe "
166+
"projection of type '%1' not imported",
167+
(StringRef, StringRef))
168+
NOTE(dont_use_iterator_api, none, "C++ method '%0' that returns an unsafe "
169+
"iterator not imported: use Swift Sequence "
170+
"APIs instead",
171+
(StringRef))
147172

173+
NOTE(unsupported_builtin_type, none, "built-in type '%0' not supported", (StringRef))
148174
NOTE(record_field_not_imported, none, "field %0 not imported", (const clang::NamedDecl*))
149175
NOTE(invoked_func_not_imported, none, "function %0 not imported", (const clang::NamedDecl*))
150176
NOTE(record_method_not_imported, none, "method %0 not imported", (const clang::NamedDecl*))

include/swift/Basic/Compiler.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@
180180

181181
// Tells Swift's ClangImporter to import a C++ type as a foreign reference type.
182182
#if __has_attribute(swift_attr)
183-
#define SWIFT_IMPORT_REFERENCE __attribute__((swift_attr("import_as_ref")))
183+
#define SWIFT_IMPORT_REFERENCE __attribute__((swift_attr("import_reference")))
184184
#else
185185
#define SWIFT_IMPORT_REFERENCE
186186
#endif

include/swift/ClangImporter/ClangImporterRequests.h

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,113 @@ class ClangRecordMemberLookup
178178
evaluate(Evaluator &evaluator, ClangRecordMemberLookupDescriptor desc) const;
179179
};
180180

181+
enum class CxxRecordSemanticsKind {
182+
Trivial,
183+
Owned,
184+
Reference,
185+
Iterator,
186+
// An API that has be annotated as explicitly unsafe, but still importable.
187+
// TODO: we should rename these APIs.
188+
ExplicitlyUnsafe,
189+
// A record that is either not copyable or not destructible.
190+
MissingLifetimeOperation,
191+
// A record that contains a pointer (aka non-trivial type).
192+
UnsafePointerMember
193+
};
194+
195+
struct CxxRecordSemanticsDescriptor final {
196+
const clang::CXXRecordDecl *decl;
197+
ASTContext &ctx;
198+
199+
CxxRecordSemanticsDescriptor(const clang::CXXRecordDecl *decl,
200+
ASTContext &ctx)
201+
: decl(decl), ctx(ctx) {}
202+
203+
friend llvm::hash_code hash_value(const CxxRecordSemanticsDescriptor &desc) {
204+
return llvm::hash_combine(desc.decl);
205+
}
206+
207+
friend bool operator==(const CxxRecordSemanticsDescriptor &lhs,
208+
const CxxRecordSemanticsDescriptor &rhs) {
209+
return lhs.decl == rhs.decl;
210+
}
211+
212+
friend bool operator!=(const CxxRecordSemanticsDescriptor &lhs,
213+
const CxxRecordSemanticsDescriptor &rhs) {
214+
return !(lhs == rhs);
215+
}
216+
};
217+
218+
void simple_display(llvm::raw_ostream &out, CxxRecordSemanticsDescriptor desc);
219+
SourceLoc extractNearestSourceLoc(CxxRecordSemanticsDescriptor desc);
220+
221+
/// What pattern does this C++ API fit? Uses attributes such as
222+
/// import_owned and import_as_reference to determine the pattern.
223+
class CxxRecordSemantics
224+
: public SimpleRequest<CxxRecordSemantics,
225+
CxxRecordSemanticsKind(CxxRecordSemanticsDescriptor),
226+
RequestFlags::Cached> {
227+
public:
228+
using SimpleRequest::SimpleRequest;
229+
230+
// Caching
231+
bool isCached() const { return true; }
232+
233+
// Source location
234+
SourceLoc getNearestLoc() const { return SourceLoc(); };
235+
236+
private:
237+
friend SimpleRequest;
238+
239+
// Evaluation.
240+
CxxRecordSemanticsKind evaluate(Evaluator &evaluator,
241+
CxxRecordSemanticsDescriptor) const;
242+
};
243+
244+
struct SafeUseOfCxxDeclDescriptor final {
245+
const clang::Decl *decl;
246+
ASTContext &ctx;
247+
248+
SafeUseOfCxxDeclDescriptor(const clang::Decl *decl, ASTContext &ctx)
249+
: decl(decl), ctx(ctx) {}
250+
251+
friend llvm::hash_code hash_value(const SafeUseOfCxxDeclDescriptor &desc) {
252+
return llvm::hash_combine(desc.decl);
253+
}
254+
255+
friend bool operator==(const SafeUseOfCxxDeclDescriptor &lhs,
256+
const SafeUseOfCxxDeclDescriptor &rhs) {
257+
return lhs.decl == rhs.decl;
258+
}
259+
260+
friend bool operator!=(const SafeUseOfCxxDeclDescriptor &lhs,
261+
const SafeUseOfCxxDeclDescriptor &rhs) {
262+
return !(lhs == rhs);
263+
}
264+
};
265+
266+
void simple_display(llvm::raw_ostream &out, SafeUseOfCxxDeclDescriptor desc);
267+
SourceLoc extractNearestSourceLoc(SafeUseOfCxxDeclDescriptor desc);
268+
269+
class IsSafeUseOfCxxDecl
270+
: public SimpleRequest<IsSafeUseOfCxxDecl, bool(SafeUseOfCxxDeclDescriptor),
271+
RequestFlags::Cached> {
272+
public:
273+
using SimpleRequest::SimpleRequest;
274+
275+
// Caching
276+
bool isCached() const { return true; }
277+
278+
// Source location
279+
SourceLoc getNearestLoc() const { return SourceLoc(); };
280+
281+
private:
282+
friend SimpleRequest;
283+
284+
// Evaluation.
285+
bool evaluate(Evaluator &evaluator, SafeUseOfCxxDeclDescriptor desc) const;
286+
};
287+
181288
#define SWIFT_TYPEID_ZONE ClangImporter
182289
#define SWIFT_TYPEID_HEADER "swift/ClangImporter/ClangImporterTypeIDZone.def"
183290
#include "swift/Basic/DefineTypeIDZone.h"

include/swift/ClangImporter/ClangImporterTypeIDZone.def

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,9 @@ SWIFT_REQUEST(ClangImporter, CXXNamespaceMemberLookup,
2424
SWIFT_REQUEST(ClangImporter, ClangRecordMemberLookup,
2525
Decl *(ClangRecordMemberLookupDescriptor), Uncached,
2626
NoLocationInfo)
27+
SWIFT_REQUEST(ClangImporter, CxxRecordSemantics,
28+
CxxRecordSemanticsKind(const clang::CXXRecordDecl *), Cached,
29+
NoLocationInfo)
30+
SWIFT_REQUEST(ClangImporter, IsSafeUseOfCxxDecl,
31+
bool(SafeUseOfCxxRecordDescriptor), Cached,
32+
NoLocationInfo)

0 commit comments

Comments
 (0)