When creating disjunctions with favored constraints in constraint
optimization, we actually ended up duplicating the constraint that we
favor, resulting with extra constraints in the disjunction.
Noticed while debugging other issues.
For instance:
protocol P1 {
func foo()
}
protocol P2 : P1 {
func bar()
}
extension P2 {
func foo() {}
}
We report the foo() in P2's extension as the default implementation of foo() declared in P1.
It is generally useful to allow 'super' method calls inside a
closure, so you can have overrides that do things like:
override func foo() {
doSomething { super.foo() }
}
However this didn't work if the closure was a local generic
function because we didn't map the 'super' type into the
right generic context.
We have a quirk where TypeBase::getSuperclass() on DynamicSelfType
returns the underlying class type, and not the superclass of the
underlying class type. As a result, we would emit a SuperRefExpr
whose type was the type of 'self' and not the type of 'super'.
Fixes <rdar://problem/30853768>.
This lets you match `case .foo` when `foo` resolves to any static member, instead of only a `case`, albeit without the exhaustiveness checking and subpattern capabilities of proper cases. While we're here, adjust the type system we set up for unresolved patterns embedded in expressions so that we give better signal in the error messages too.
This is disabled by default but enabled under the frontend option
-propagate-constraints.
The idea here is to have a pass that enforces local consistency in our
constraint system, in order to reduce the domains of constraint
variables, speeding up the solving of the constraint system.
The initial focus will be on reducing the size of the disjunctions for
function overloads with the hope that it substantially improves the
performance of type checking many expressions.
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.
Constraint generation for interpolated string literals was
meticulously producing a constraint system that included all of the
generated calls to init(stringInterpolationSegment:). While accurate,
this is completely unnecessary (because the
ExpressibleByStringInterpolation protocol allows *anything* to be
interpolated) and leads to large, intertwined constraint systems
where:
(1) There are two additional type variables per string interpolation
segment, and
(2) Those type variables form a bridge between the string
interpolation's type variable and the type variables of each string
interpolation segment, and
(3) init(stringInterpolationSegment:) tends to be overloaded (4
overloads, down from 17 due to
29353013c0)
which left each string interpolation as a large connected component
with big disjunctions.
Drop the calls to init(stringInterpolationSegment:) from the
constraint system. This eliminates two type
variables per segment (due to (1) going away), and breaks the bridge
described in (2), so that each string interpolation segment is
treated as an separate connected component and, therefore, will be
solved independently. The actual resolution of
init(stringInterpolationSegment:) overloads is pushed to the
constraint application phase, where we are only dealing with concrete
types and *much* smaller constraint systems.
Fixes rdar://problem/29389887 more thoroughly.
The type checker introduces fresh type variables for editor
placeholders that are encountered in the source. If there are many
such editor placeholders, we'll create a large number of type
variables with very little context, which can cause poor scaling in
the type checker. Since we get very little information out of these
type variables, artificially limit the number of type variables we
create (to 2) and rotate through them.
Another piece of rdar://problem/29389887.
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.
In ConstraintGenerator::visitDictionaryExpr(), if the dictionary_expr has a
contextual type which is also a dictionary type, use it to add a new type
constraint for each of the dictionary_expr's elements. This has a huge effect
on solver performance for dictionary literals with elements that have
overloading. The approach closely follows that used in
ConstraintGenerator::visitArrayExpr(), which has included a similar
optimization (from git commit a22b391) for over two and a half years.
I've also added a couple of new test cases which would trigger the bug without
this fix.
FailureDiagnosis::visitApplyExpr is going to attempt to type-check
argument expression multiple times - with and without allowing free
type variables, since first type-check might mutate AST if (sub-expression
type-checks correctly) it's required to fix up ternary operations
represented as IfExpr to it's original condition form, because IfExpr
is going to convert Bool into implicit call `(Bool) -> () -> Int1`
upon successful type-check, which is not handled by either
ConstraintGenerator nor ExprRewriter because they don't expect
well-formed type-checked IfExpr is input.
Resolves: <rdar://problem/29850459>.
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.
Several fixes in order to make handling of types more consistent.
In particular:
- Expression types used within the constraint system itself always use
the type map.
- Prior to calling out to any TypeChecker functions, the types are
written back into the expression tree. After the call, the types are
read back into the constraint system type map.
- Some calls to directly set types on the expressions are reintroduced
in places they make sense (e.g. when building up new expressions that
are then passed to typeCheckExpressionShallow).
ConstraintSystem::setType() is still setting the type on the expression
nodes at the moment, because there is still some incorrect handling of
types that I need to track down (in particular some issues related to
closures do not appear to be handled correctly). Similarly, when we
cache the types in the constraint system map, we are not clearing them
from the expression tree yet.
The diagnostics have not been updated at all to use the types from
the constraint system where appropriate, and that will need to happen as
well before we can remove the write from ConstraintSystem::setType()
into the expression and enable the clearing of the expression tree type
when we cache it in the constraint system.
The default behavior was looking *through* the ForceValueExpr, so in this test case the LinkedExprAnalyzer thought it was dealing with Optional<Double> rather than Double. Resolves SR-1122.
Instead of returning empty type when RValue destination of the assignment
could not be determined, let's return it unresolved directly instead and
let it be handled by coerceToType, which is going to produce special expression
(UnresolvedTypeConversionExpression) which facilitates better diagnostics.
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.
Previously, bridging conversions were handled as a form of "explicit
conversion" that was treated along the same path as normal
conversions in matchTypes(). Historically, this made some
sense---bridging was just another form of conversion---however, Swift
now separates out bridging into a different kind of conversion that is
available only via an explicit "as". This change accomplishes a few
things:
* Improves type inference around "as" coercions. We were incorrectly
inferring type variables of the "x" in "x as T" in cases where a
bridging conversion was expected, which cause some type inference
failures (e.g., the SR-3319 regression).
* Detangles checking for bridging conversions from other conversions,
so it's easier to isolate when we're applying a bridging
conversion.
* Explicitly handle optionals when dealing with bridging conversions,
addressing a number of problems with incorrect diagnostics, e.g.,
complains about "unrelated type" cast failures that would succeed at
runtime.
Addresses rdar://problem/29496775 / SR-3319 / SR-2365.
Follow the pattern set by isDictionaryType() of performing the query
and extracting the underlying key/element types directly. We often
need both regardless. NFC
Previously, validateDecl() would check if the declaration had an
interface type and use that as an indication not to proceed.
However for functions we can only set an interface type after
checking the generic signature, so a recursive call to validateDecl()
on a function would "steal" the outer call and complete validation.
For generic types, this meant we could have a declaration with a
valid interface type but no generic signature.
Both cases were problematic, so narrow workarounds were put in
place with additional new flags. This made the code harder to
reason about.
This patch consolidates the flags and establishes new invariants:
- If validateDecl() returns and the declaration has no interface
type and the isBeingValidated() flag is not set, it means one
of the parent contexts is being validated by an outer recursive
call.
- If validateDecl() returns and the declaration has the
isBeingValidated() flag set, it may or may not have an interface
type. In this case, the declaration itself is being validated
by an outer recursive call.
- If validateDecl() returns and the declaration has an interface
type and the isBeingValidated() flag is not set, it means the
declaration and all of its parent contexts are fully validated
and ready for use.
In general, we still want name lookup to find things that have an
interface type but are not in a valid generic context, so for this
reason nominal types and associated types get an interface type as
early as possible.
Most other code only wants to see fully formed decls, so a new
hasValidSignature() method returns true iff the interface type is
set and the isBeingValidated() flag is not set.
For example, while resolving a type, we can resolve an unqualified
reference to a nominal type without a valid signature. However, when
applying generic parameters, the hasValidSignature() flag is used
to ensure we error out instead of crashing if the generic signature
has not yet been formed.
- 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.
Rename the old getMemberSubstitutions() to getContextSubstitutions()
and add a new getMemberSubstitutions() that takes a ValueDecl, rather
than the member's DeclContext.
This new method forwards generic parameters if the member is a generic
function.
Changes:
* Terminate all namespaces with the correct closing comment.
* Make sure argument names in comments match the corresponding parameter name.
* Remove redundant get() calls on smart pointers.
* Prefer using "override" or "final" instead of "virtual". Remove "virtual" where appropriate.
Once we've bound a type variable, we find those inactive constraints
that mention the type variable and make them active, so they'll be
simplified again. However, we weren't finding *all* constraints that
could be affected---in particular, we weren't searching everything
related to the type variables in the equivalence class, which meant
that some constraints would not get visited... and we would to
type-check simply because we didn't look at a constraint again when we
should have.
Fixes rdar://problem/29633747.
Update CSGen/CSApply/CSSolver to primarily use getType() from
ConstraintSystem.
Currently getType() just returns the type on the expression. As with
setType(), which continues to set the type on the expression, this
will be updated once all the other changes are in place.
This change also moves coerceToRValue from TypeChecker to
CosntraintSystem so that it can access the expression type map in the
constraint system.
I've been unable to reproduce the issue that hit on the builder, and
still expect this change to be NFC, so trying it out again. If it
fails, I'll revert again and try another shot at reproducing.
Original commit message:
We create new expressions that have the type on the expression
set. Make sure we capture these types in the constraint system type
map so that we can refer to types uniformally by consulting the map.
NFC.
(cherry picked from commit 57d5d974ff)
We create new expressions that have the type on the expression
set. Make sure we capture these types in the constraint system type
map so that we can refer to types uniformally by consulting the map.
NFC.