Commit Graph

1659 Commits

Author SHA1 Message Date
practicalswift
6d1ae2a39c [gardening] 2016 → 2017 2017-01-06 16:41:22 +01:00
Mark Lacey
7f64b6853f Improve handling of types in constraint system.
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.
2017-01-05 11:54:34 -08:00
Robert Widmann
26b53a5e63 Look through IUOs when converting the scrutiny of if-exprs
Previously this would cause strange diagnostics to be emitted when
values of type Bool! were the subject of if-expression conditions.

var isBoolean: Bool! = false
let conditional = isBoolean ? "Broken" : "Heart"
// ^ type 'Bool' is broken

Instead, look through IOUs before performing the member access to cover
our bases here.
2017-01-05 03:08:06 -07:00
Mark Lacey
ed328af079 Add explicit type operands to two Exprs only created during type checking.
We need to use the types stored in the constraint system's type map when
creating these.
2017-01-04 16:21:29 -08:00
Mark Lacey
36b07395bc Add type accessor arguments to expression APIs that access types.
These are used from within constraint system code, and for those uses we
need to be reading from the constraint system type map.

Add the parallel constraint system interfaces that call into the
Expr interfaces with the appropriate accessors.
2017-01-04 14:25:38 -08:00
Slava Pestov
584f47d025 Sema: Fix crashes in CSDiag
- TypeMatchVisitor doesn't like seeing ErrorTypes -- stop if we have one.

- Common logic for replacing type parameters and variables with
  UnresolvedType.

- Fix crash in coerceToType() if one of the two types has an UnresolvedType
  in it, but not at the top level.

Fixes one compiler_crasher and some regressions with upcoming patches.
2017-01-04 01:40:19 -08:00
Slava Pestov
8f96606cb2 Sema: Remove TupleToScalar conversion, which did nothing useful except crash
As far as I can tell there's no way to trigger this from valid code.
2017-01-03 23:00:07 -08:00
Slava Pestov
b5da219d11 Sema: Fix crash when closing an existential reference necessitates tuple-to-tuple conversion 2017-01-03 21:49:44 -08:00
Slava Pestov
9db06ee36d Sema: Fixes for handling of 'Self'-returning methods
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>.
2017-01-03 21:49:00 -08:00
Slava Pestov
9f30532641 Sema: Fix closeExistential() in CSApply with invalid direct call of metatype
When we have a value 'p' of type 'P.Type' for some protocol 'P',
we require the user to write 'p.init()' rather than 'p()' to
construct an instance of a concrete type conforming to 'P'.

If they write 'p()', we suggest a fixit to insert '.init',
however if there is also a subsequent member access on the
result, for example 'p().foo', we would crash.

Another invalid case that used to crash is when you construct
a protocol metatype directly and then access a member of it,
eg. 'P().foo'.
2017-01-03 21:28:11 -08:00
Joe Groff
796df2dc44 Merge pull request #6429 from jckarter/type-of-by-overload-resolution
`withoutActuallyEscaping`
2017-01-03 18:47:29 -08:00
Robert Widmann
9bb914a3a5 [SR-3523] Coercions that implicitly look through IUOs should not propagate
Force unwrapping the expression and propagating that type down to the
rest of the tree causes crashes when we go to request a different set
of protocols than we were expecting from it later.  Make this
transformation local to the apply instead.
2017-01-03 19:03:24 -07:00
Joe Groff
0c9297862f Sema: Handle type-checking for withoutActuallyEscaping.
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.
2016-12-22 17:51:26 -08:00
Joe Groff
1889fde228 Resolve type(of:) by overload resolution rather than parse hackery.
`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.
2016-12-22 16:28:31 -08:00
Slava Pestov
ac7a3030e3 Sema: Fix inheritance of designated initializers with default arguments in generic context
We were dropping the substitutions required to call the default
argument generator on the floor, when the correct solution is to
remap them to substitutions in terms of the base class signature.

Fixes <rdar://problem/29721571>.
2016-12-22 14:33:01 -05:00
Slava Pestov
caa7045ae5 AST: Remove unnecessary ModuleDecl parameter from GenericSignature::getSubstitutions() 2016-12-22 14:33:00 -05:00
Doug Gregor
f7b5d9d69e [Type checker] Allow bridging conversions to more-optional types.
The prior formulation of bridging conversions allowed conversion to
more-optional types, e.g., converting an "NSDate" to "Date?", which
was broken by my recent refactoring in this area. Allow bridging
conversions to more-optional types by introducing extra optional
injections at the end.

Fixes rdar://problem/29780527.
2016-12-22 10:02:41 -08:00
Doug Gregor
8afeadc5ee Merge pull request #6309 from DougGregor/as-coercions-bridging
[Type checker] Clean up as/as!/as?/is casting
2016-12-21 15:53:18 -08:00
practicalswift
b253b21014 [gardening] Make sure argument names in comments match the actual parameter names 2016-12-21 22:56:01 +01:00
Doug Gregor
dcdef4f7f5 [Type checker] Improve "downcast only unwraps optionals" diagnostics.
Specialize and improve the "downcast only unwraps optionals"
diagnostic to provide specific diagnostics + Fix-Its for the various
casts of forced cast, conditional cast, and "isa" check. Specifically:

* With a forced cast, customize the diagnostic. We still insert the
  appropriate number of !'s, but now we remove the 'as! T' (if an
  implicit conversion would suffice) or replace the 'as!' with 'as'
  (if we still need a bridge)

* With a conditional cast, only emit a diagnostic if we're removing
  just one level of optional. In such cases, we either have a no-op
  (an implicit conversion would do) or we could just use 'as' to the
  optional type, so emit a customized warning to do that. If we are
  removing more than one level of optional, don't complain:
  conditional casts can remove optionals. Add the appropriate Fix-Its
  here.

* With an 'is' expression, only emit a diagnostic if we're removing
  just one level of optional. In this case, the 'is' check is
  equivalent to '!= nil'. Add a Fix-It for that.

Across the board, reduce the error to a warning. These are
semantically-well-formed casts, it's just that they could be written
better.

Fixes rdar://problem/28856049 and rdar://problem/22275685.
2016-12-21 13:47:19 -08:00
Doug Gregor
40140d6e8d [Type checker] Drop unused closure parameter in TypeChecker::typeCheckCheckedCast.
This closure parameter isn't ever actually used and isn't needed. NFC
2016-12-21 13:46:14 -08:00
Doug Gregor
fa47d57b4e [AST] Remove CheckedCastKind::BridgeFromObjectiveC.
It's not handled any differently from ValueCast, so simplify it away.
2016-12-21 13:46:14 -08:00
Doug Gregor
d9843899c4 [Type checker] Clean up handling of checked casts (as!/as?/is).
The type checker implements logic for handling checked casts in two
places: the constraint solver (for type-checking expressions
containing "as!" or "as?") and as a top-level entrypoint for
type-checking as?/as! for diagnostics and is/as patterns. Needless to
say, the two implementations were inconsistent, and in fact both were
wrong, leading to various problems---rejecting perfectly-valid "as!"
and "as?" casts outright, bogus warnings that particular as!/as? casts
always-succeed or always-fail when they wouldn't, and so on.

Start detangling the mess in two ways. First, drastically simplify the
handling of checked casts in the constraint solver, eliminating the
unprincipled "subtype" constraint checks that (among other things)
broke the handling of checked casts that involved bridging or optional
unwrapping. The simpler code is more permissive and more correct; it
essentially accepts that the user knows what she is doing with the
cast.

Second, make the type checker's checking of casts far more thorough,
which includes:

* When we're performing a collection cast, actually check that the
  element types (and key types, for a dictionary) are castable, rather
  than assuming all collection casts are legitimate. This means we'll
  get more useful "always fails" and "always succeeds" diagnostics for
  array/set/dictionary.

* Handle casts from a bridged value type to a subclass of the
  corresponding bridged class type. Previously, these would be
  incorrectly classified as "always fails".

While I'm here, eliminate a spurious diagnostic that occurs when using
a conditional cast ("as?") that could have been a coercion/bridging
conversion ("as"). The optional injection we synthesize to get the
resulting type correct was getting diagnosed as an implicit coercion,
but shouldn't have been.
2016-12-21 13:46:14 -08:00
Doug Gregor
e97ab635ea [Constraint solver] Separate bridging conversions from other conversions.
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.
2016-12-21 13:46:14 -08:00
Slava Pestov
dc3af8fc99 Sema: Don't re-typecheck multi-statement closures in lazy var initializer
Normally you have to declare a type if the lazy property
initializer is a multi-statement closure, but if the user
forgets we don't want to crash.
2016-12-21 14:20:28 -05:00
Slava Pestov
fb0f372e94 AST: Move mapType{In,OutOf}Context() out of ArchetypeBuilder and clean up headers
- 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.
2016-12-18 19:55:41 -08:00
practicalswift
38be6125e5 [gardening] C++ gardening: Terminate namespaces, fix argument names, ...
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.
2016-12-17 00:32:42 +01:00
Slava Pestov
2c6b9f71b6 AST: Change TypeAliasDecls to store an interface type as their underlying type
- TypeAliasDecl::getAliasType() is gone. Now, getDeclaredInterfaceType()
  always returns the NameAliasType.

- NameAliasTypes now always desugar to the underlying type as an
  interface type.

- The NameAliasType of a generic type alias no longer desugars to an
  UnboundGenericType; call TypeAliasDecl::getUnboundGenericType() if you
  want that.

- The "lazy mapTypeOutOfContext()" hack for deserialized TypeAliasDecls
  is gone.

- The process of constructing a synthesized TypeAliasDecl is much simpler
  now; instead of calling computeType(), setInterfaceType() and then
  setting the recursive properties in the right order, just call
  setUnderlyingType(), passing it either an interface type or a
  contextual type.

  In particular, many places weren't setting the recursive properties,
  such as the ClangImporter and deserialization. This meant that queries
  such as hasArchetype() or hasTypeParameter() would return incorrect
  results on NameAliasTypes, which caused various subtle problems.

- Finally, add some more tests for generic typealiases, most of which
  fail because they're still pretty broken.
2016-12-15 22:46:15 -08:00
Slava Pestov
a384b2a677 Don't call VarDecl::getType() on deserialized VarDecls 2016-12-15 22:46:15 -08:00
Pavel Yaskevich
be4bea917b [QoI] Look through LValueness of the type when trying to coerce from/to UnresolvedType 2016-12-14 23:14:53 -08:00
Joe Groff
ccfabd1118 Make LookupConformanceFn callbacks return Optional<ProtocolConformanceRef>.
NFC yet, but this is a step toward centralizing error handling policy for failed conformance lookups instead of leaving it ad-hoc.
2016-12-14 18:04:35 -08:00
Slava Pestov
30c4235193 Sema: Horrific simulation of Swift 3 bug with argument labels for Swift 3 mode
In Swift 3.0.1, argument labels are ignored when calling a function
having a single parameter of 'Any' type. That is, if we have:

func foo(_: Any) {}

Both of the following were accepted in a no-assert build (an assert
build would crash, but the GM builds of Xcode ship with asserts off):

foo(123)
foo(data: 123)

This behavior was fixed by 578e36a7e1,
but unfortunately we have to revert to the old behavior *and* defeat
the assertion when in Swift 3 mode.

Swift 4 mode still has the correct behavior, where the second call
'foo(data: 123)' produces a diagnostic.

Now, I have to pour myself a strong drink to forget this ever happened.

Fixes <rdar://problem/28952837>.
2016-12-14 01:45:14 -08:00
Slava Pestov
dbb9d315e3 Sema: Fix a couple of crashes in tuple arguments tests
There's a general problem where a SubscriptExpr has an argument
that's a LoadExpr loading a tuple from an lvalue. For some reason
we don't construct the ParenExpr in this case, which confused
CSDiag.

Also, in Swift 3 mode, add a total hack to fudge things in
matchCallArguments() in the case where we erroneously lost
ParenType sugar.
2016-12-13 23:22:10 -08:00
Mark Lacey
59ce1ff73c Add a function parameter to Expr::propagateLValueAccessKind.
This parameter implements getType() for the given expression, making
it possible to use this from within the constraint system, which now
has it's own side map for types of expressions.
2016-12-12 23:55:25 -08:00
Mark Lacey
c470448b67 Cache more expression types during CSApply. 2016-12-12 22:42:46 -08:00
swift-ci
cd3cc61a00 Merge pull request #6226 from rudkx/cs-typemap 2016-12-12 10:54:41 -08:00
Mark Lacey
4841869d51 Remove unused declaration. 2016-12-12 11:19:43 -07:00
practicalswift
8962c8819f Merge pull request #6139 from practicalswift/remove-never-read-variables
[gardening] Remove never-read variables + tighten scope.
2016-12-12 13:32:36 +01:00
Mark Lacey
e30afe9b96 Further updates to cache/set types in the constraint system. 2016-12-11 21:49:48 -07:00
Mark Lacey
0a8678cf19 Replace Expr::getType() with ConstraintSystem::getType().
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.
2016-12-11 17:46:34 -07:00
Mark Lacey
294f90a68b Re-apply: Cache types in the constraint system expression type map.
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)
2016-12-11 14:07:46 -07:00
Mark Lacey
6abcc32103 Revert "Cache types in the constraint system expression type map." 2016-12-11 00:38:10 -07:00
Mark Lacey
d6f9402833 Merge pull request #6203 from rudkx/cs-typemap
Cache types in the constraint system expression type map.
2016-12-10 23:52:07 -07:00
Mark Lacey
57d5d974ff Cache types in the constraint system expression type map.
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.
2016-12-10 23:12:36 -07:00
Mark Lacey
3fcac9b47b Merge pull request #6198 from rudkx/cs-typemap
Set types in the constraint system type map in CSApply.
2016-12-10 20:21:34 -07:00
Mark Lacey
e00756cda4 Set types in the constraint system type map in CSApply.
The setType() function in ConstraintSystem still sets the types on the
expressions themselves and that will continue until everything is
moved over to using the map.

Unfortunately this exposed cases where we are currently setting the
type multiple times to different values, so I've commented out the
assert that I previously added. I will circle back and start looking
into those issues once everything is moved over.

NFC for now.
2016-12-10 19:25:43 -07:00
Slava Pestov
58d4a07fa6 Sema: Clean up accessor synthesis
- Remove unnecessary calls to validateDecl() and typeCheckDecl()
- Simplify the logic around synthesizing materializeForSet
2016-12-08 23:22:16 -08:00
practicalswift
a7ae48481d [gardening] Remove never-read bool anythingShuffled. 2016-12-08 13:36:10 +01:00
Pavel Yaskevich
f1be35c178 [QoI] Add return after coercing to TupleElementExpr in ExprRewriter::coerceToType
Adds missing return statement for coercions which extract a single
element from a tuple aka tuple-to-scalar conversions in ExprRewriter::coerceToType.
2016-12-08 02:05:46 -08:00
swift-ci
20c44e6de4 Merge pull request #6095 from akyrtzi/fix-ide-crash-103 2016-12-06 09:06:31 -08:00