* Refactor Bincompat
Organize everything around internal functions that test for
a particular OS version.
Correctly handle cases where we don't know the version of the app.
Make all bincompat functions consistently return `true` for the
legacy semantics, `false` for new semantics. Consistently name
them all to reflect this.
* Conditionalize the support for SR-14635
SR-14635 pointed out a hole in the updated dynamic casting logic
that allowed certain casts that should have been illegal.
In particular, when casting certain types to Obj-C protocols,
the Swift value gets boxed; we would permit the cast to succeed
whenever the resulting box satisfied the protocol. For example,
this allowed any Swift value to be cast to `NSCopying` regardless of
whether or not it implemented the required `copy(with:)` method.
This was fixed in #37683 to reject such casts but of course some folks were
depending on this behavior to pass Swift data into Obj-C functions.
(The properly supported approach for passing arbitrary Swift data into
Obj-C functions is to cast the Swift value to `AnyObject`.)
This change makes that new behavior conditional. For now,
the legacy semantics are enabled on Apple platforms and the
new semantics are in use everywhere else. This will allow
us to gradually enable enforcement of the new behavior over
time.
* Just skip this test on Apple platforms, since it is inconsistently implemented there (and is therefore not really testable)
tryGetCompleteMetadataNonblocking crashes on artificial subclasses due to the NULL type descriptor. Explicitly check for artificial subclasses in getSuperclassForMaybeIncompleteMetadata and immediately return their Superclass field. Artificial subclasses are always fully initialized so we don't need to do anything special for them.
rdar://72583931
* SR-14635: Casts to NSCopying should not always succeed
The runtime dynamic casting logic explores a variety of strategies for
each cast request. One of the last options is to wrap the source
in a `__SwiftValue` box so it can bridge to Obj-C. The previous
code was overly aggressive about such boxing; it performed the boxing
for any source type and only checked to verify that the `__SwiftValue`
box itself was compatible with the destination.
Among other oddities, this results in the behavior discussed
in SR-14635, where any Swift or Obj-C type will always successfully cast
to NSCopying because `__SwiftValue` is compatible with NSCopying.
This is actually two subtly different issues:
* Class types should not be subject to `__SwiftValue` boxing at all.
Casting class types to class existentials is already handled elsewhere,
so this function should just reject any source with class type.
* Non-class types should be boxed only when being assigned to
an AnyObject (an "unconstrained class existential"). If
the class existential has constraints, it is by definition
a class-constrained existential which should not receive
any non-class object.
To solve these, this PR disables `__SwiftValue` boxing in two cases:
1. If the source is a class (reference) type.
2. If the destination has constraints
Resolves SR-14635
Resolves rdar://78224322
* Avoid boxing class metatypes on Darwin
But continue boxing
* Non-class metatypes on all platforms
* All metatypes on non-Darwin platforms
Obj-C interop requires that we do not box class metatypes;
those must be usable as simple pointers when passed to Obj-C.
But no other metatype is object-compatible, so we have to
continue boxing everything else.
* Split out ObjC-specific test cases
* Casting from AnyHashable to AnyHashable should never create another wrapper
This adds a conformance for _HasCustomAnyHashableRepresentation to
AnyHashable that simply returns self. This ensures that anytime
you try to create a new AnyHashable wrapper for an existing
AnyHashable, you just get back the original.
Resolves rdar://75180619
* Move the `Struct AnyHashable` change to `without-asserts` list
As suggested by @lorentey
This restores the earlier behavior of Optionals cast to
AnyHashable, so that [String?:Any] dictionaries cast
to [AnyHashable:Any] can be indexed by plain String
keys.
This is a little problematic because it's not consistent with the
compiler-optimized casts.
But the ability to index such dictionaries by plain String
keys seems important to preserve. SR-9047 will expand
Optional/AnyHashable interoperability so that such
indexing works without this special case.
An earlier proposal would link-check this, changing the behavior
depending on the caller. But it's not really workable to
change the behavior seen by intermediate frameworks depending
on the app they're being called by.
As part of making casting more consistent, the behavior of Optional -> AnyHashable casts
was changed in some cases. This PR provides a hook for re-enabling the old behavior
in certain contexts.
Background: Most of the time, casts from String? to AnyHashable get optimized
to just injects the String? into the AnyHashable, so the following
has long been true and remains true in Swift 5.4:
```
let s = "abc"
let o: String? = s
// Next test is true because s is promoted to Optional<String>
print(s == o)
// Next test is false: Optional<String> and String are different types
print(s as AnyHashable == o as AnyHashable)
```
But when casts ended up going through the runtime, Swift 5.3 behaved
differently, as you could see by casting a dictionary with `String?` keys (in
the generic array code, key and value casts always use the runtime logic). In
the following code, both print statements behave differently in Swift 5.4 than
before:
```
let a: [String?:String] = ["Foo":"Bar"]
let b = a as [AnyHashable:Any]
print(b["Foo"] == "Bar") // Works before Swift 5.4
print(b["Foo" as String?] == "Bar") // Works in Swift 5.4 and later
```
Old behavior: The `String?` keys would get unwrapped to `String` before being injected into AnyHashable. This allows the first to work but strangely breaks the second.
New behavior: The `String?` keys do not get unwrapped. This breaks the first but makes the second work.
TODO: The long-term goal, of course, is for `AnyHashable("Foo" as String?)` to
test equal to `AnyHashable("Foo")` (and hash the same, of course). In that
case, all of the tests above will succeed.
Resolves rdar://73301155
Add regression tests for a number of casting cases that were fixed by recent work:
* SR-13812 (aka rdar://70999129)
Verify that the new casting logic correctly handles
a generic `is` test for a struct conforming to a protocol.
* SR-8964 (aka rdar://45217461)
Test casts from Any! holding Error types
* SR-1999 (aka rdar://48769924)
* SR-6279 (aka rdar://35321438
* rdar://59844232
* SR-12025
Note that SR-12025 is not actually fixed yet; this test is marked "expected failure" until it is.
* Dynamic Casting: Properly unwrap existential metatype sources
Existential metatypes are really just existentials that hold metatypes. As
such, they should be handled in the general casting logic in much the same way
as regular existentials: They should generally be ignored by most casting logic,
and unwrapped as necessary at the top level.
In particular, the previous code would fail to correctly handle the following
cast from an existential metatype (`AnyObject.Type`) to an existential
(`AnyObject`):
```
class C {}
let a = C.self as AnyObject.Type
let b = a as! AnyObject
```
With the old code, `b` above would hold a reference to a `__SwiftValue` box
containing the type reference. The correct result would simply store the type
reference directly in `b`. These two are only really distinguishable in that
the correct form permits `a === b` to return `true`.
Fixes rdar://70582753
Note: This is not yet fully supported on Linux. Basically, metatypes on Linux are not currently
fully compatible with reference-counted class pointers, which prevents us from
fully supporting metatype operations on Linux that we support on macOS.
* [DynamicCast] Rely on runtime when casts can't be optimized
The Swift compiler renders `as?` operations in Swift into variations of the
`checked_cast_br` instructions in SIL. Subsequent optimization passes may alter
or eliminate these instructions. Any remaining instructions after optimization
are translated by IRGen into runtime calls.
At least, that's the theory. Unfortunately, the current IRGen logic does not
recognize all of the casting instruction variants and renders one particular
unrecognized variant as a simple nil load. Specifically, this occurs for
optimized casts of metatypes to AnyObject:
```
let a = Int.self
let b = a as? AnyObject
// b should not be nil here
```
This PR changes this case in IRGen to instead generate a call to
`swift_dynamicCast`, deferring this case to the runtime.
Future: Someday, the compiler should be taught to correctly optimize
this cast away.
Optional conditionally conforms to Hashable, so for
example `Optional<Int>` must cast to AnyHashable
_even if it contains `nil`_. This was broken up
through Swift 5.3 and was fixed by the new dynamic
cast runtime.
Add a test to ensure this stays fixed.
* Dynamic Cast Rework: Runtime
This is a completely refactored version of the core swift_dynamicCast
runtime method.
This fixes a number of bugs, especially in the handling of multiply-wrapped
types such as Optional within Any. The result should be much closer to the
behavior specified by `docs/DynamicCasting.md`.
Most of the type-specific logic is simply copied over from the
earlier implementation, but the overall structure has been changed
to be uniformly recursive. In particular, this provides uniform
handling of Optional, existentials, Any and other common "box"
types along all paths. The consistent structure should also be
easier to update in the future with new general types.
Benchmarking does not show any noticable performance implications.
**Temporarily**, the old implementation is still available. Setting the
environment variable `SWIFT_OLD_DYNAMIC_CAST_RUNTIME` before launching a program
will use the old runtime implementation. This is only to facilitate testing;
once the new implementation is stable, I expect to completely remove the old
implementation.