We don't actually want to open the type; instead, calculate the
substituted member type using substMemberTypeWithBase(), which
will return an unbound generic type if the member is a generic
nominal or type alias, and then it open it with openUnboundGenericType().
This is NFC for now, but I need generic typealiases to come in as
UnboundGenericTypes here in a subsequent patch.
The openType() function did two things:
- Replace unbound generic types like 'G' with fresh type variables
applied to bound generic types, like 'G<$T0>'.
- Replace generic parameters with type variables from the replacement
map.
The two behaviors were mutually exclusive and never used from the
same call site, so split them up into two independent functions.
Also, eliminate ConstraintSystem::openBindingType() since it was only
used in one place and could be expressed in terms of existing functions.
If we had an unbound generic type whose parent was a bound
generic type, and the outer type's generic signature
placed generic constraints on outer parameters, we would
create type variables that weren't ever bound to anything.
Previously, this would never come up, but it will once
preCheckExpression() is folding more MemberRefExprs down
to TypeExprs.
Now that SILGen can correctly lower lvalue accesses of
class existential payloads, remove a hack in Sema that
was simply doing the wrong thing.
Fixes <rdar://problem/31858378>.
There were various problems with layout constraints either
being ignored or handled incorrectly. Now that I've exercised
this support with an upcoming patch, there are some fixes
here.
Also, introduce a new ExistentialLayout::getLayoutConstriant()
which returns a value for existentials which are class-constrained
but don't have a superclass or any class-constrained protocols;
an example would be AnyObject, or AnyObject & P for some
non-class protocol P.
NFC for now, since these layout-constrained existentials cannot
be constructed yet.
If the member came from a class, we're not going to substitute
the 'Self' type. Instead, we open the existential, upcast the
archetype up to the class type and access the member as if it
were a class member in the usual way.
Don't pass in the opened type; instead have the caller call
simplifyType() if needed. Also, make computeSubstitutions()
bail out if there's no generic signature, which allowed
unifying several generic vs non-generic code paths.
Hopefully there is enough short circuiting in there now that
we're not doing any extra work in the non-generic case.
First, add some new utility methods to create SubstitutionMaps:
- GenericSignature::getSubstitutionMap() -- provides a new
way to directly build a SubstitutionMap. It takes a
TypeSubstitutionFn and LookupConformanceFn. This is
equivalent to first calling getSubstitutions() with the two
functions to create an ArrayRef<Substitution>, followed by
the old form of getSubstitutionMap() on the result.
- TypeBase::getContextSubstitutionMap() -- replacement for
getContextSubstitutions(), returning a SubstitutionMap.
- TypeBase::getMemberSubstitutionMap() -- replacement for
getMemberSubstitutions(), returning a SubstitutionMap.
With these in place, almost all existing uses of subst() taking
a ModuleDecl can now use the new form taking a SubstitutionMap
instead. The few remaining cases are explicitly written to use a
TypeSubstitutionFn and LookupConformanceFn.
We can end up with IUOs bound as a result of overload resolution. When
this happens and the resulting type is used as a generic, we can end up
with dependent member types that fail to simplify properly as a result
of failing to substitute due to the IUO getting in the way. In these
cases it should be completely safe to strip the IUO off and retry
substitution with the base type.
This isn't really an ideal fix by any means, and we need to revisit how
we handle bindings to make it more uniform, but for now I think this is
a reasonable path to move forward.
Fixes a source compatibility regression.
rdar://problem/29960575
Without this, CSGen/CSSimplify and CSApply may have differing
opinions about whether e.g. a let property is settable, which
can lead to invalid ASTs.
Arguably, a better fix would be to remove the dependency on the
exact nested DC. For example, we could treat lets as settable
in all contexts and then just complain later about invalid
attempts to set them. Or we could change CSApply to directly
use the information it already has about how an l-value is used,
rather than trying to figure out whether it *might* be getting set.
But somehow, tracking a new piece of information through the
entire constraint system seems to be the more minimal change.
Fixes rdar://29810997.
ConstraintSystem::simplifyType() replaced types with their fixed types
from the global map.
Solution::simplifyType() replaced types with their fixed types from the
current bindings.
There were some minor differences between the two, and some dead code.
This commit introduces new kind of requirements: layout requirements.
This kind of requirements allows to expose that a type should satisfy certain layout properties, e.g. it should be a trivial type, have a given size and alignment, etc.
Previously all of the following would strip off varying amounts of
MetatypeType, LValueType, InOutType, DynamicSelfType, etc:
- ConstraintSystem::performMemberLookup()
- ConstraintSystem::lookupMember()
- TypeChecker::lookupMember()
- DeclContext::lookupQualified()
- Type::getContextSubstitutions()
The problem is that the higher level methods that took a lookup type
would call the lower level methods, and post-process the result using
the given lookup type. Since different levels of sugar were stripped,
it made the code hard to reason about and opened up edge cases, eg
if a DynamicSelfType or InOutType appears where we didn't expect it.
Since filtering out static/instance and mutating/nonmutating members
is done at higher levels, there's no reason for these name lookup
operations to accept anything other than nominal types, existentials
and archetypes.
Make this so with assertions, and deal with the fallout.
When inserting a new value, assert that there's no existing
value at that key, and to avoid the assert firing when
opening up UnboundGenericTypes, put those replacements in
their own map. We don't need them later.
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>.
This patch contains several intertwined changes:
- Remove some unnecessary complexity and duplication.
- Adds a new TypeChecker::lookupUnqualifiedType() which bypasses most of
the logic in TypeChecker::lookupUnqualified(), such as the
LookupResultBuilder. Use this when resolving unqualified references
to types.
- Fixes for generic typealiases to better preserve the type parameters of
the parent type, and clean up the logic for applying the inner generic
arguments. Some uses of generic typealiases that used to crash now work,
and those tests have been uncommented.
- Avoid an unnecessary desugaring of TypeAliasDecls which map directly
to GenericTypeParamTypes. Once again this perturbs the source-stability
test.
- When looking up a nested type of a base class with a derived class base,
always use the base class as the parent of the nested type. This fixes
a recent regression where in some cases we were using the wrong parent.
Fixes <rdar://problem/29782186>.
If T0 must be materializable and it's bound to T1, when matching T0 to
possibly optinal T1, look through optinality when setting materializability of the binding.
Currently isAnyHashableType method validates only structs but
it doesn't account for situation when type is represented via type
variable with type already fixed to AnyHashable, that results in
infinite loop in the solver because restriction [hashable-to-
anyhashable] is going to add new type variable recursively.
withoutActuallyEscaping has a signature like `<T..., U, V, W> (@nonescaping (T...) throws<U> -> V, (@escaping (T...) throws<U> -> V) -> W) -> W, but our type system for functions unfortunately isn't quite that expressive yet, so we need to special-case it. Set up the necessary type system when resolving an overload set to reference withoutActuallyEscaping, and if a type check succeeds, build a MakeTemporarilyEscapableExpr to represent it in the type-checked AST.
`type(of:)` has behavior whose type isn't directly representable in Swift's type system, since it produces both concrete and existential metatypes. In Swift 3 we put in a parser hack to turn `type(of: <expr>)` into a DynamicTypeExpr, but this effectively made `type(of:)` a reserved name. It's a bit more principled to put `Swift.type(of:)` on the same level as other declarations, even with its special-case type system behavior, and we can do this by special-casing the type system we produce during overload resolution if `Swift.type(of:)` shows up in an overload set. This also lays groundwork for handling other declarations we want to ostensibly behave like normal declarations but with otherwise inexpressible types, viz. `withoutActuallyEscaping` from SE-0110.
Follow the pattern set by isDictionaryType() of performing the query
and extracting the underlying key/element types directly. We often
need both regardless. NFC
- The DeclContext versions of these methods have equivalents
on the DeclContext class; use them instead.
- The GenericEnvironment versions of these methods are now
static methods on the GenericEnvironment class. Note that
these are not made redundant by the instance methods on
GenericEnvironment, since the static methods can also be
called with a null GenericEnvironment, in which case they
just assert that the type is fully concrete.
- Remove some unnecessary #includes of ArchetypeBuilder.h
and GenericEnvironment.h. Now changes to these files
result in a lot less recompilation.