-
Notifications
You must be signed in to change notification settings - Fork 10.5k
(take 2) SR-0140: Bridge Optionals to nonnull ObjC objects by bridging their payload, or using a sentinel. #4869
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -487,3 +487,81 @@ extension Optional { | |
} | ||
|
||
} | ||
|
||
//===----------------------------------------------------------------------===// | ||
// Bridging | ||
//===----------------------------------------------------------------------===// | ||
|
||
#if _runtime(_ObjC) | ||
extension Optional : _ObjectiveCBridgeable { | ||
// The object that represents `none` for an Optional of this type. | ||
internal static var _nilSentinel : AnyObject { | ||
@_silgen_name("_swift_Foundation_getOptionalNilSentinelObject") | ||
get | ||
} | ||
|
||
public func _bridgeToObjectiveC() -> AnyObject { | ||
// Bridge a wrapped value by unwrapping. | ||
if let value = self { | ||
return _bridgeAnythingToObjectiveC(value) | ||
} | ||
// Bridge nil using a sentinel. | ||
return type(of: self)._nilSentinel | ||
} | ||
|
||
public static func _forceBridgeFromObjectiveC( | ||
_ source: AnyObject, | ||
result: inout Optional<Wrapped>? | ||
) { | ||
// Map the nil sentinel back to .none. | ||
// NB that the signature of _forceBridgeFromObjectiveC adds another level | ||
// of optionality, so we need to wrap the immediate result of the conversion | ||
// in `.some`. | ||
if source === _nilSentinel { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Are all NSNulls guaranteed to be identical? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It is documented as a singleton, but I would double-check with someone from Foundation. @phausler? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There's example ObjC code that uses There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. NSNull in Darwin is a singleton (swift-corelibs-foundation it cannot be since we don't have factory patterns) |
||
result = .some(.none) | ||
return | ||
} | ||
// Otherwise, force-bridge the underlying value. | ||
let unwrappedResult = source as! Wrapped | ||
result = .some(.some(unwrappedResult)) | ||
} | ||
|
||
public static func _conditionallyBridgeFromObjectiveC( | ||
_ source: AnyObject, | ||
result: inout Optional<Wrapped>? | ||
) -> Bool { | ||
// Map the nil sentinel back to .none. | ||
// NB that the signature of _forceBridgeFromObjectiveC adds another level | ||
// of optionality, so we need to wrap the immediate result of the conversion | ||
// in `.some` to indicate success of the bridging operation, with a nil | ||
// result. | ||
if source === _nilSentinel { | ||
result = .some(.none) | ||
return true | ||
} | ||
// Otherwise, try to bridge the underlying value. | ||
if let unwrappedResult = source as? Wrapped { | ||
result = .some(.some(unwrappedResult)) | ||
return true | ||
} else { | ||
result = .none | ||
return false | ||
} | ||
} | ||
|
||
public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?) | ||
-> Optional<Wrapped> { | ||
if let nonnullSource = source { | ||
// Map the nil sentinel back to none. | ||
if nonnullSource === _nilSentinel { | ||
return .none | ||
} else { | ||
return .some(nonnullSource as! Wrapped) | ||
} | ||
} else { | ||
// If we unexpectedly got nil, just map it to `none` too. | ||
return .none | ||
} | ||
} | ||
} | ||
#endif |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2513,6 +2513,18 @@ bool swift::swift_dynamicCast(OpaqueValue *dest, | |
// unwrapping the target. This handles an optional source wrapped within an | ||
// existential that Optional conforms to (Any). | ||
if (auto srcExistentialType = dyn_cast<ExistentialTypeMetadata>(srcType)) { | ||
#if SWIFT_OBJC_INTEROP | ||
// If coming from AnyObject, we may want to bridge. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why is this specific to AnyObject? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I suppose we could also support it from There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Oh, I somehow missed that this was only when casting to Optional. Thanks for clarifying. |
||
if (srcExistentialType->Flags.getSpecialProtocol() | ||
== SpecialProtocol::AnyObject) { | ||
if (auto targetBridgeWitness = findBridgeWitness(targetType)) { | ||
return _dynamicCastClassToValueViaObjCBridgeable(dest, src, srcType, | ||
targetType, | ||
targetBridgeWitness, | ||
flags); | ||
} | ||
} | ||
#endif | ||
return _dynamicCastFromExistential(dest, src, srcExistentialType, | ||
targetType, flags); | ||
} | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the Swift.org open source project | ||
// | ||
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors | ||
// Licensed under Apache License v2.0 with Runtime Library Exception | ||
// | ||
// See http://swift.org/LICENSE.txt for license information | ||
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
#include "swift/Basic/Lazy.h" | ||
#include "swift/Basic/LLVM.h" | ||
#include "swift/Runtime/Metadata.h" | ||
#include "swift/Runtime/Mutex.h" | ||
#include "swift/Runtime/ObjCBridge.h" | ||
#include <vector> | ||
#import <Foundation/Foundation.h> | ||
#import <CoreFoundation/CoreFoundation.h> | ||
|
||
using namespace swift; | ||
|
||
/// Class of sentinel objects used to represent the `nil` value of nested | ||
/// optionals. | ||
@interface _SwiftNull : NSObject { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this should'd probably be There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good idea. We aren't making any of the runtime-private classes hidden yet. I think we should do that as a separate patch, though, just to keep the risk of unintentional breakage minimal for this as a 3.0.1 patch. |
||
@public | ||
unsigned depth; | ||
} | ||
@end | ||
|
||
@implementation _SwiftNull : NSObject | ||
|
||
- (NSString*)description { | ||
return [NSString stringWithFormat:@"<%@ %p depth = %u>", [self class], | ||
self, | ||
self->depth]; | ||
} | ||
|
||
@end | ||
|
||
namespace { | ||
|
||
struct SwiftNullSentinelCache { | ||
std::vector<id> Cache; | ||
StaticReadWriteLock Lock; | ||
}; | ||
|
||
static Lazy<SwiftNullSentinelCache> Sentinels; | ||
|
||
static id getSentinelForDepth(unsigned depth) { | ||
// For unnested optionals, use NSNull. | ||
if (depth == 1) | ||
return (id)kCFNull; | ||
// Otherwise, make up our own sentinel. | ||
// See if we created one for this depth. | ||
auto &theSentinels = Sentinels.get(); | ||
unsigned depthIndex = depth - 2; | ||
{ | ||
StaticScopedReadLock lock(theSentinels.Lock); | ||
const auto &cache = theSentinels.Cache; | ||
if (depthIndex < cache.size()) { | ||
id cached = cache[depthIndex]; | ||
if (cached) | ||
return cached; | ||
} | ||
} | ||
// Make one if we need to. | ||
{ | ||
StaticScopedWriteLock lock(theSentinels.Lock); | ||
if (depthIndex >= theSentinels.Cache.size()) | ||
theSentinels.Cache.resize(depthIndex + 1); | ||
auto &cached = theSentinels.Cache[depthIndex]; | ||
// Make sure another writer didn't sneak in. | ||
if (!cached) { | ||
auto sentinel = [[_SwiftNull alloc] init]; | ||
sentinel->depth = depth; | ||
cached = sentinel; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Am I not reading this correctly? On cache miss you are not storing a value into the cache? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
} | ||
return cached; | ||
} | ||
} | ||
|
||
} | ||
|
||
/// Return the sentinel object to use to represent `nil` for a given Optional | ||
/// type. | ||
SWIFT_RUNTIME_STDLIB_INTERFACE SWIFT_CC(swift) | ||
extern "C" | ||
id _swift_Foundation_getOptionalNilSentinelObject(const Metadata *Wrapped) { | ||
// Figure out the depth of optionality we're working with. | ||
unsigned depth = 1; | ||
while (Wrapped->getKind() == MetadataKind::Optional) { | ||
++depth; | ||
Wrapped = cast<EnumMetadata>(Wrapped)->getGenericArgs()[0]; | ||
} | ||
|
||
return objc_retain(getSentinelForDepth(depth)); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is this worth caching, for SIL optimization purposes?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unfortunately, we don't support stored static properties on generic types. We have to rely on the runtime's caching.