If key or value of a literal collection expression doesn't conform
to protocol(s) expected by the contextual existential type, let's
diagnose that via a tailed collection mismatch fix instead of a
generic conformance one.
Resolves: rdar://103045274
Even if protocol is not self-conforming it should be okay to produce
a conformance based on superclass if protocol bounds of the existential
are all marker protocols.
Superclass concrete conformance is wrapped into an inherited conformance
in such cases to reference the existential.
It's important to know whether a binding set has all of its bindings
as subtypes of some existential type(s), type variables like that
should be delayed.
Incremental binding inference introduced a bug into computation of
this property by checking only directly inferable bindings, but
it's also important to check that there are no literal requirements
that can produce bindings, because that would mean that type variable
can never be just a subtype of existential type(s).
Resolves: rdar://77570994
If there is a conformance failure related to existential conversion
let's ignore that fact that there could be an implicit value-to-optional
conversion involved, because it's not the main issue in cases like
that.
Resolves: rdar://problem/70814576
Argument-to-Parameter mismatch handles conformance failures
related to arguments, so the logic in `MissingConformanceFailure`
which wasn't entirely correct is now completely obsolete.
Resolves: rdar://problem/56234611
If one of the generic parameters is missing let's give solver a
chance to diagnose the problem, otherwise there is a risk of failing
type resolution and not producing any diagnostics.
Resolves: rdar://problem/50099849
In a few corner cases we built DeclRefExpr and MemberRefExpr
for references to types. These should just be TypeExpr so that
SILGen doesn't have to deal with it.
This also fixes a bug where a protocol typealias with an
unbound generic type could not be accessed properly from
expression context, but that is just so incredibly obscure.
TupleShuffleExpr could not express the full range of tuple conversions that
were accepted by the constraint solver; in particular, while it could re-order
elements or introduce and eliminate labels, it could not convert the tuple
element types to their supertypes.
This was the source of the annoying "cannot express tuple conversion"
diagnostic.
Replace TupleShuffleExpr with DestructureTupleExpr, which evaluates a
source expression of tuple type and binds its elements to OpaqueValueExprs.
The DestructureTupleExpr's result expression can then produce an arbitrary
value written in terms of these OpaqueValueExprs, as long as each
OpaqueValueExpr is used exactly once.
This is sufficient to express conversions such as (Int, Float) => (Int?, Any),
as well as the various cases that were already supported, such as
(x: Int, y: Float) => (y: Float, x: Int).
https://bugs.swift.org/browse/SR-2672, rdar://problem/12340004
For Swift 3 / 4:
Deprecate the spelling "ImplicitlyUnwrappedOptional", emitting a warning
and suggesting "!" in places where they are allowed according to
SE-0054.
In places where SE-0054 disallowed IUOs but we continued to accept them
in previous compilers, emit a warning suggesting "Optional" or "?" as
an alternative depending on context and treat the IUO as an Optional,
noting this in the diagnostic.
For Swift 5:
Treat "ImplicitlyUnwrappedOptional" as an error, suggesting
"!" in places where they are allowed by SE-0054.
In places where SE-0054 disallowed IUOs, emit an error suggestion
"Optional" or "?" as an alternative depending on context.
Protocol methods returning optionals, metatypes and functions
returning 'Self' are now handled correctly in Sema when
accessed with a base of existential type, eg:
protocol Clonable {
func maybeClone() -> Self?
func cloneMetatype() -> Self.Type
func getClonerFunc() -> () -> Self
}
let c: Clonable = ...
let _: Clonable = c.maybeClone()
let _: Clonable.Type = c.cloneMetatype()
Previously, we were unable to model this properly, for
several reasons:
- When opening the function type, we replaced the return
value in openedFullType _unconditionally_ with the
existential type. This was broken if the return type
was not the 'Self' parameter, but rather an optional,
metatype or function type involving the 'Self' parameter.
- It was also broken because we lost information; if the
return type originally contained an existential, we had
no way to draw the distinction. The 'hasArchetypeSelf()'
method was a hint that the original type contained a
type parameter, but it was inaccurate in some subtle cases.
- Since we performed this replacement on both the
'openedFullType' and 'openedType', CSApply had to "undo"
it to replace the existential type with the opened
existential archetype. This is because while the formal
type of the access returns the existential type, in
reality it returns the opened type, and CSApply has to
insert the correct ErasureExpr.
This was also done unconditionally, but even if it were
done more carefully, it would do the wrong thing because
of the 'loss of information' above.
- There was something fishy going on when we were dealing
with a constructor that was declared on the Optional type
itself, as seen in the fixed type_checker_crasher.
- TypeBase::eraseOpenedExistential() would transform a
MetatypeType of an opened existential into a MetatypeType
of an existential, rather than an ExistentialMetatypeType
of the existential type.
The new logic has the following improvements:
- When opening a function type, we replace the 'Self' type
parameter with the existential type in 'openedType', but
*not* 'openedFullType'. This simplifies CSApply, since it
doesn't have to "undo" this transformation when figuring
out what coercions to perform.
- We now only use replaceCovariantResultType() when working
with Self-returning methods on *classes*, which have more
severe restrictions than protocols. For protocols, we walk
the type using Type::transform() and handle all the cases
properly.
- Not really related to the above, but there was a whole
pile of dead code here concerning associated type references.
Note that SILGen still needs support for function conversions
involving an existential erasure; in the above Clonable example,
Sema now models this properly but SILGen still crashes:
let _: () -> Clonable = c.getClonerFunc()
Fixes <rdar://problem/28048391>, progress on <rdar://problem/21391055>.
What I've implemented here deviates from the current proposal text
in the following ways:
- I had to introduce a FunctionArrowPrecedence to capture the parsing
of -> in expression contexts.
- I found it convenient to continue to model the assignment property
explicitly.
- The comparison and casting operators have historically been
non-associative; I have chosen to preserve that, since I don't
think this proposal intended to change it.
- This uses the precedence group names and higherThan/lowerThan
as agreed in discussion.
- All parts of the compiler now use ‘P1 & P2’ syntax
- The demangler and AST printer wrap the composition in parens if it is
in a metatype lookup
- IRGen mangles compositions differently
- “protocol<>” is now “swift.Any”
- “protocol<_TP1P,_TP1Q>” is now “_TP1P&_TP1Q”
- Tests cases are updated and added to test the new syntax and mangling
This commit defines the ‘Any’ keyword, implements parsing for composing
types with an infix ‘&’, and provides a fixit to convert ‘protocol<>’
- Updated tests & stdlib for new composition syntax
- Provide errors when compositions used in inheritance.
Any is treated as a contextual keyword. The name ‘Any’
is used emit the empty composition type. We have to
stop user declaring top level types spelled ‘Any’ too.
We had four duplicated implementations of checking how a protocol
requirement uses 'Self', all slightly wrong or incomplete:
- When deciding if the protocol type can be used as an existential.
This one would just ignore 'Self' in the return type of a method
completely, which was incorrect for cases where 'Self' is
contravariant but part of the return value, for example:
func foo() -> (Self -> ())
- When deciding if a member access can be performed on an existential
value. This is distinct from the former, because the member may
have been defined in a protocol extension, in which case it cannot
be used even if the protocol type can be used as an existential.
Unfortunately, this implementation was overly conservative, and
would reject uses of 'Self' where Sema could in fact erase the
existential type, for example:
func foo() -> Self??
func foo() -> Self.Type
func foo() -> (Self, Self)
This function handled function return types correctly, effectively
plugging the leak in the previous code. It did lead to inconsistent
behavior with protocols that had contravariant Self in requirements
though; sometimes we would diagnose uses of the existential type,
other times we would only complain about specific members.
- When deciding if a method in a non-final class can model a protocol
requirement. This one was the most elaborate one, but here
contravariance and uses of associated types are actually okay, so
it was written to pick up covariant 'Self' only. However, it also
did not handle metatypes and tuples.
- When opening the type of member of an existential, we would check
if the return value was 'Self' or an optional of 'Self', but again
this check was too conservative, so after the previous three were
fixed, we could reference members on existentials that did not
have a correct opened type.
Now, these have been combined into one check. To fix some crashes,
Sema's implementation of erasing existentials now relies on
coerceToType() instead of hand-rolling a few coercions of its own,
and wrapping the rest in CovariantFunctionConversionExpr, which
didn't make much sense if the result was not a function type.
SILGen still does not support function type conversions where an
existential return value is being erased; these would silently
miscompile before, but crash with an assertion now, because they
are correctly modeled as a FunctionConversionExpr, and not
CovariantFunctionConversionExpr.
This removes the totally lame diagnostic telling the user to wrap
their function in a closure.
Some exotic Objective-C metatype to AnyObject conversions are still
missing, and there aren't any executable tests yet. Both will be
addressed soon.
Swift SVN r31527
we process contextual constraints when producing diagnostic. Formerly,
we would aggressively drop contextual type information on the floor under
the idea that it would reduce constraints on the system and make it more
likely to be solvable. However, this also has the downside of introducing
ambiguity into the system, and some expr nodes (notably closures) cannot
usually be solved without that contextual information.
In the new model, expr diagnostics are expected to handle the fact that
contextual information may be present, and bail out without diagnosing an
error if that is the case. This gets us more information into closures,
allowing more specific return type information, e.g. in the case in
test/expr/closure/closures.swift.
This approach also produces more correct diagnostics in a bunch of other
cases as well, e.g.:
- var c = [:] // expected-error {{type '[_ : _]' does not conform to protocol 'DictionaryLiteralConvertible'}}
+ var c = [:] // expected-error {{expression type '[_ : _]' is ambiguous without more context}}
and the examples in test/stmt/foreach.swift, test/expr/cast/as_coerce.swift,
test/expr/cast/array_iteration.swift, etc.
That said, this another two steps forward, one back thing. Because we
don't handle propagating sametype constraints from results of calls to their
arguments, we regress a couple of (admittedly weird) cases. This is now
tracked by:
<rdar://problem/22333090> QoI: Propagate contextual information in a call to operands
There is also the one-off narrow case tracked by:
<rdar://problem/22333281> QoI: improve diagnostic when contextual type of closure disagrees with arguments
Swift SVN r31319
argument. For now we start with some of the most simple cases: single argument
calls. This dramatically improves the QoI for error messages in argument lists,
typically turning a error+note combo into a single specific error message.
Some minor improvements coming (and also generalizing this to n-ary calls), but it
is nice that all the infrastructure is starting to come together...
Swift SVN r30905
fixing <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc
Swift SVN r30844
This covers:
- Lifetime-extending wrappers, like withExtendedLifetime, withCString, and withUnsafe*Pointer
- 'map' and friends on Optional
- 'indexOf'
A few APIs I haven't gotten to yet in this first pass:
- Autoclosure APIs, like assert, &&, etc.
- the 'isOrderedBefore' predicate for sorting APIs. The sorting implementation does some microoptimizations with 'inout' closures that violate rethrows checking.
- Strict 'map', 'filter', and friends on CollectionType. These need some plumbing in Lazy to be able to thread a Result-forming transformation through.
This version of the patch updates some protocol customization implementations that I missed the first time around, and includes the tests I forgot to add in the previous iteration.
Swift SVN r30790