Skip to content

(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

Merged
merged 1 commit into from
Sep 20, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 18 additions & 9 deletions lib/AST/ASTContext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3879,18 +3879,22 @@ ASTContext::getForeignRepresentationInfo(NominalTypeDecl *nominal,
known->second.getGeneration() < CurrentGeneration)) {
Optional<ForeignRepresentationInfo> result;

// Look for a conformance to _ObjectiveCBridgeable.
// Look for a conformance to _ObjectiveCBridgeable (other than Optional's--
// we don't want to allow exposing APIs with double-optional types like
// NSObject??, even though Optional is bridged to its underlying type).
//
// FIXME: We're implicitly depending on the fact that lookupConformance
// is global, ignoring the module we provide for it.
if (auto objcBridgeable
= getProtocol(KnownProtocolKind::ObjectiveCBridgeable)) {
if (auto conformance
= dc->getParentModule()->lookupConformance(
nominal->getDeclaredType(), objcBridgeable,
getLazyResolver())) {
result =
ForeignRepresentationInfo::forBridged(conformance->getConcrete());
if (nominal != dc->getASTContext().getOptionalDecl()) {
if (auto objcBridgeable
= getProtocol(KnownProtocolKind::ObjectiveCBridgeable)) {
if (auto conformance
= dc->getParentModule()->lookupConformance(
nominal->getDeclaredType(), objcBridgeable,
getLazyResolver())) {
result =
ForeignRepresentationInfo::forBridged(conformance->getConcrete());
}
}
}

Expand Down Expand Up @@ -3986,6 +3990,11 @@ Type ASTContext::getBridgedToObjC(const DeclContext *dc, Type type,
// Try to find a conformance that will enable bridging.
auto findConformance =
[&](KnownProtocolKind known) -> Optional<ProtocolConformanceRef> {
// Don't ascribe any behavior to Optional other than what we explicitly
// give it. We don't want things like AnyObject?? to work.
if (type->getAnyNominal() == getOptionalDecl())
return None;

// Find the protocol.
auto proto = getProtocol(known);
if (!proto) return None;
Expand Down
13 changes: 13 additions & 0 deletions lib/SILGen/SILGenBridging.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,19 @@ emitBridgeNativeToObjectiveC(SILGenFunction &gen,
witnessFnTy = witnessFnTy.substGenericArgs(gen.SGM.M, substitutions);
}

// The witness may be more abstract than the concrete value we're bridging,
// for instance, if the value is a concrete instantiation of a generic type.
//
// Note that we assume that we don't ever have to reabstract the parameter.
// This is safe for now, since only nominal types currently can conform to
// protocols.
if (witnessFnTy.castTo<SILFunctionType>()->getParameters()[0].isIndirect()
&& !swiftValue.getType().isAddress()) {
auto tmp = gen.emitTemporaryAllocation(loc, swiftValue.getType());
gen.B.createStore(loc, swiftValue.getValue(), tmp);
swiftValue = ManagedValue::forUnmanaged(tmp);
}

// Call the witness.
SILType resultTy = gen.getLoweredType(objcType);
SILValue bridgedValue = gen.B.createApply(loc, witnessRef, witnessFnTy,
Expand Down
7 changes: 6 additions & 1 deletion lib/SILOptimizer/Utils/Local.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1662,6 +1662,11 @@ optimizeBridgedSwiftToObjCCast(SILInstruction *Inst,

auto SILFnTy = SILType::getPrimitiveObjectType(
M.Types.getConstantFunctionType(BridgeFuncDeclRef));

// TODO: Handle indirect argument to or return from witness function.
if (ParamTypes[0].isIndirect()
|| BridgedFunc->getLoweredFunctionType()->getSingleResult().isIndirect())
return nullptr;

// Get substitutions, if source is a bound generic type.
ArrayRef<Substitution> Subs =
Expand Down Expand Up @@ -1728,9 +1733,9 @@ optimizeBridgedSwiftToObjCCast(SILInstruction *Inst,
case ParameterConvention::Direct_Unowned:
break;
case ParameterConvention::Indirect_In:
case ParameterConvention::Indirect_In_Guaranteed:
case ParameterConvention::Indirect_Inout:
case ParameterConvention::Indirect_InoutAliasable:
case ParameterConvention::Indirect_In_Guaranteed:
case ParameterConvention::Direct_Deallocating:
llvm_unreachable("unsupported convention for bridging conversion");
}
Expand Down
78 changes: 78 additions & 0 deletions stdlib/public/core/Optional.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Copy link
Contributor

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?

internal static let _nilSentinel = _swift_Foundation_getOptionalNilSentinelObject()

Copy link
Contributor Author

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.

@_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 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are all NSNulls guaranteed to be identical?

Copy link
Contributor

Choose a reason for hiding this comment

The 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?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's example ObjC code that uses x == [NSNull null] too.

Copy link
Contributor

@phausler phausler Sep 20, 2016

Choose a reason for hiding this comment

The 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
12 changes: 12 additions & 0 deletions stdlib/public/runtime/Casting.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this specific to AnyObject?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suppose we could also support it from NSNull. AnyObject is the only Swift-level formal type that'd make sense to cast back to Optional otherwise.

Copy link
Contributor

Choose a reason for hiding this comment

The 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);
}
Expand Down
1 change: 1 addition & 0 deletions stdlib/public/stubs/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ if(SWIFT_HOST_VARIANT MATCHES "${SWIFT_DARWIN_VARIANTS}")
Availability.mm
DispatchShims.mm
FoundationHelpers.mm
OptionalBridgingHelper.mm
Reflection.mm
SwiftNativeNSXXXBase.mm.gyb)
set(LLVM_OPTIONAL_SOURCES
Expand Down
99 changes: 99 additions & 0 deletions stdlib/public/stubs/OptionalBridgingHelper.mm
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 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should'd probably be __attribute__((visibility("hidden")))

Copy link
Contributor Author

Choose a reason for hiding this comment

The 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;
Copy link
Contributor

Choose a reason for hiding this comment

The 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?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cached is a reference, so this will store the value into the cache.

}
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));
}
14 changes: 8 additions & 6 deletions test/SILGen/objc_bridging_any.swift
Original file line number Diff line number Diff line change
Expand Up @@ -126,27 +126,29 @@ func passingToId<T: CP, U>(receiver: NSIdLover,
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]])
receiver.takesId(knownUnbridged)

// These cases bridge using Optional's _ObjectiveCBridgeable conformance.

// CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover,
// CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @_TFSq19_bridgeToObjectiveCfT_Ps9AnyObject_
// CHECK: [[TMP:%.*]] = alloc_stack $Optional<String>
// CHECK: store [[OPT_STRING]] to [[TMP]]
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @_TFs27_bridgeAnythingToObjectiveC
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<Optional<String>>([[TMP]])
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<String>([[TMP]])
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]])
receiver.takesId(optionalA)

// CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover,
// CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @_TFSq19_bridgeToObjectiveCfT_Ps9AnyObject_
// CHECK: [[TMP:%.*]] = alloc_stack $Optional<NSString>
// CHECK: store [[OPT_NSSTRING]] to [[TMP]]
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @_TFs27_bridgeAnythingToObjectiveC
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<Optional<NSString>>([[TMP]])
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<NSString>([[TMP]])
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]])
receiver.takesId(optionalB)

// CHECK: [[METHOD:%.*]] = class_method [volatile] [[SELF]] : $NSIdLover,
// CHECK: [[TMP:%.*]] = alloc_stack $Optional<Any>
// CHECK: copy_addr [[OPT_ANY]] to [initialization] [[TMP]]
// CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @_TFs27_bridgeAnythingToObjectiveC
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<Optional<Any>>([[TMP]])
// CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @_TFSq19_bridgeToObjectiveCfT_Ps9AnyObject_
// CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<Any>([[TMP]])
// CHECK: apply [[METHOD]]([[ANYOBJECT]], [[SELF]])
receiver.takesId(optionalC)

Expand Down
Loading