Commit Graph

844 Commits

Author SHA1 Message Date
Joe Groff
f662ed86b3 Sema: Assert that bridging constraints aren't formed when ObjC interop is disabled. 2017-03-03 13:18:08 -08:00
Joe Groff
d998692b60 Sema/SIL: NSError has no special powers without ObjC interop.
In particular, it doesn't "toll-free bridge" to the Error existential on non-ObjC-interop platforms, and we would miscompile as if it could. This should fix SR-585.
2017-02-25 09:20:24 -08:00
Slava Pestov
46ea929072 Sema: Remove TMF_UnwrappingOptional
We should remove the only remaining TMF flag one day too, since it looks
completely bogus.
2017-02-13 16:59:13 -08:00
Slava Pestov
e9c255bfca Sema: Better fix for banning the '() -> T' => '() -> ()?' implicit conversion
Previously we would check TMF_UnwrappingOptional flag, which does not
stick with the constraint, so it would not always persist. Now, add a
new OptionalPayload locator element, which is more correct.

Fixes <rdar://problem/30429709>.
2017-02-13 16:59:09 -08:00
Hugh Bellamy
f001b7562b Use relatively new LLVM_FALLLTHROUGH instead of our own SWIFT_FALLTHROUGH 2017-02-12 10:47:03 +07:00
Mark Lacey
00cc26004b [Sema] Penalize conversions to Any.
We previously penalized bindings to Any, and that resulted in
inappropriately rejecting solutions where we bind a decl that is
explicitly typed Any. That penalty was removed in
170dc8acd7, but that has led to a variety
of source compatibility issues.

So now, we'll reintroduce a penalty for Any-typed things, but instead of
penalizing bindings (which happen both because of explicitly-typed
values in the source, and implicitly due to attempting various types for
a particular type variable), penalize casts, which are always present in
some form in the source.

Thanks go to John for the suggestion.

Fixes
  SR-3817 (aka rdar://problem/30311052)
  SR-3786 (aka rdar://problem/30268529)
  rdar://problem/29907555
2017-02-02 17:37:02 -08:00
Mark Lacey
13a6574a12 Disallow most other conversions when we need an lvalue-to-rvalue conversion.
This change is needed by a separate change I have that penalizes
conversions to Any. That change exposed a problem where we ended up
doing a direct lvalue-to-Any conversion without first loading as part of
an lvalue-to-rvalue conversion.

We should really only be doing most of these other conversions/fixes on
rvalues.

Unfortunately I don't know of a way to hit this without the other
change, and thus don't have a test case.

As a side note, this also helps some (perhaps most, but definitely not
all) of the exponential type inference cases involving arrays and
dictionaries. Unfortunately again, we don't currently have a testing
mechanism in place to ensure we don't regress those cases, and I don't
want to add a test that will completely hang every bot if it does
regress, so...*sad face*...no test case for that either.
2017-02-02 17:37:02 -08:00
Jordan Rose
eed34d15e7 Sema: Explicitly allow Optional-to-IUO when converting functions. (#7153)
We limit Optional-to-IUO as an implicit conversion to avoid making
common expressions ambiguous. However, this runs into trouble with
function-to-function conversions, which always look for a "Subtype"
relationship for their inputs and outputs. This is a conservative way
for Sema to avoid emitting conversions that SILGen cannot handle.

The problem case here is converting a closure with type '(Any!) ->
Void' to a value of type '(Any?) -> Void':

    let f: ((Any?) -> Void) = { (arg: Any!) in }

This is clearly a safe conversion, since 'Any!' and 'Any?' have the
same representation at run time, but historically we've disallowed it
because of the above rules. However, in Swift 3.0 this particular case
was permitted, with the type checker deciding that the 'Any?' argument
to 'f' could first itself be put into an 'Any', then /that/ value
could go through a value-to-optional conversion to make 'Any!'.
Fortunately the emitted code didn't follow this incorrect conversion
path.

This patch doesn't even try to emulate the old behavior. Instead, it
just weakens the restriction on Optional-to-IUO via a new type
matching flag that only applies within the context of matching
function types.

We can consider opening up function conversions in Swift 4 to anything
that supports conversion---not just subtyping---now that SILGen knows
how to automatically reabstract most such things. But whether we do or
not, Optional/IUO is a special case.

https://bugs.swift.org/browse/SR-3758
2017-01-31 13:42:09 -08:00
Slava Pestov
b3cabb0745 Use llvm casts in various places instead of looking at {Expr,Decl,TypeBase}::getKind()
Also add some FIXMEs for some code in debug info emission that
looks incorrect.
2017-01-30 00:08:53 -08:00
Slava Pestov
93bab2b072 Sema: There's no implicit conversion from a closure result of optional Void 2017-01-28 18:35:24 -08:00
Jordan Rose
7c8117301a In Swift 3 mode, allow "tuple unsplatting" in certain cases. (#7077)
Swift 3.0 allowed constructing an enum or calling a function-typed
property with multiple arguments even when a single argument of tuple
type was expected. Emulate that in Swift 3 mode by wrapping in an
extra level of parentheses when the situation comes up.

Last vestiges of fallout from SE-0110. Hopefully last, anyway. A nice
follow-up to this commit might be to /warn/ in Swift 3 mode when this
happens.

rdar://problem/30171399
2017-01-27 11:19:07 -08:00
swift-ci
48029307ee Merge pull request #7065 from DougGregor/bridge-then-convert 2017-01-26 15:08:56 -08:00
Doug Gregor
fab0371eba [Type checker] Allow bridging followed by a conversion to existential.
When I refactored the handling of bridging conversions (e.g.,
valueType as? NSClassType), I broke the path that performed a bridging
conversion followed by a conversion to an existential, e.g.,
"some-bridged-value-type as CVarArg". Reinstate such use cases.

Fixes rdar://problem/30195862.
2017-01-26 14:26:11 -08:00
John McCall
98aa9f3b04 Merge pull request #7047 from rjmccall/track-access-dc-in-constraints
Track the actual DC of a member access in the constraint system.
2017-01-26 14:09:32 -05:00
John McCall
39b65f49a0 Track the actual DC of a member access in the constraint system.
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.
2017-01-26 00:14:21 -05:00
Mark Lacey
c57dc58dab Revert "Disallow conversions from IUOs to extistentials."
Revert 7c665c105b because it results in a
much worse source compatibility regression than the one it was intended
to fix.

The problem is that it results in force-unwrapping IUOs, which can lead
to cases where we prefer type-checking solutions that choose methods
over properties where we used to choose properties. So for example a
collection literal like [x] will result in a collection with a method
named 'x' in it rather than a property named 'x'.

I'll be looking at other solutions which fix both the original
compatibility regression as well as retain the behavior in the new test
added here.

Fixes SR-3715 and rdar://problem/30176166.
2017-01-25 17:04:18 -08:00
practicalswift
a9d6d8938c [gardening] Fix recently introduced typos 2017-01-22 20:40:45 +01:00
Doug Gregor
ecfea608db [Type checker] Classify the various optional conversion kinds.
1efafbcd9b restricted our classification
of various optional-related conversions (implicit forcing of IUOs,
optional-to-optional conversions, value-to-optional conversions) to
produce a single potential classification. However, in the presence of
type variables, we cannot always determine which particular conversion
restriction might apply. Prior to 1efafb, we produced too many
options; after 1efafb, we produced too few. Here, enumerate a more
bounded (but complete) set of potential conversions, taking into
account embedded type variables.

This is a better fix for rdar://problem/29977523 than simply reverting
1efafb, because it bounds the set of optional conversions we attempt.
2017-01-17 13:10:26 -08:00
Mark Lacey
c301833e15 Reapply: Collapse the three optional-to-optional restriction kinds.
This reapply's Doug's change d79ba781c6,
which had previously been applied on top of
1efafbcd9b, the latter of which resulted
in a source compatibility break.
2017-01-15 22:34:40 -07:00
Mark Lacey
fc73e79b74 Revert "Fix one source of exponential behavior in the type checker."
This reverts commit 1efafbcd9b because
results in a regression in source compatibility with Swift 3.

It also adds a test demonstrating what was broken by the change.

I will take another look at fixing the exponential behavior that this
was attempting to fix.

Fixes rdar://problem/29977523.
2017-01-15 22:33:57 -07:00
Mark Lacey
7dd2489151 Revert "[Constraint solver] Collapse the three optional-to-optional restriction kinds."
This reverts commit d79ba781c6 so that I
can revert 1efafbcd9b, which caused a
source compatibility regression.
2017-01-15 22:01:45 -07:00
swift-ci
a716d403d6 Merge pull request #6774 from jckarter/nsnumber-conditional-casting 2017-01-13 15:20:12 -08:00
Joe Groff
c03371afc1 Sema: NSValue-to-value-type casts are failable and should be checked.
In Swift 4 mode, no longer consider e.g. 'nsNumber as Int' or 'nsValue as NSRange' to be valid coercions. This would break compatibility with Swift 3, so in Swift 3 mode, accept the coercion, but *also* accept a checked cast without a warning, and raise a migration warning about the unchecked coercion.
2017-01-13 13:51:27 -08:00
swift-ci
c7f7706658 Merge pull request #6773 from DougGregor/simplify-iuo-kinds 2017-01-12 21:01:52 -08:00
Doug Gregor
d79ba781c6 [Constraint solver] Collapse the three optional-to-optional restriction kinds.
All three of these conversion restriction kinds were handled in
exactly the same way, so just treat them as one.
2017-01-12 17:11:13 -08:00
Mark Lacey
5c6c7ff651 Disallow conversions from IUOs to extistentials.
Commit 170dc8acd7 removed a penalty that
we used to have for conversions to Any. In some unusual circumstances
not having that penalty can result in new amiguities where we should
have nothing ambiguous about an expression according to our type rules.

This change attempts to ensure that we make that less likely or
impossible by not allowing direct conversions from IUOs to Any (instead
forcing these to first be force-unchecked, leading to more expensive
solutions). We never should have allowed these conversions anyway,
independent of removing the penalty for conversions to Any.

This change is intentionally very narrow to avoid further potential
source breakage.

Fixes rdar://problem/29907555.
2017-01-12 16:45:53 -08:00
Roman Levenstein
29180ca1a0 Add support for layout requirements with layout constraints.
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.
2017-01-11 19:21:45 -08:00
Slava Pestov
c04c6c9c61 Merge pull request #6586 from xedin/SR_3520
Generic function taking closure with inout parameter returns erroneous results
2017-01-09 12:25:20 -08:00
Pavel Yaskevich
0f716e643b [QoI] Fix inference of inout closure parameters in generic contexts
Convert subtype constraints with inout on one side and type variable
on the other into fixed binding. Constriants like `inout T0 subtype T1`
where (T0 must be materializable) are created when closures are part
of the generic function parameters e.g. `func foo<T>(_ t: T, (inout T) -> Void) {}`
so when such function gets called e.g.
```
  var x = 42
  foo(x) { $0 = 0 }
```
it's going to try and map closure parameters type (inout T0) - where
is opened generic parameter T - to argument type (T1), which can
be 'inout' but it's uncertain at this stage, but since closure
'declaration' `{ $0 = 0 }` is wrapped inside of a function call,
it has to 'map' parameters to arguments instead of converting them,
see `ConstraintSystem::matchFunctionTypes`.

Resolves: SR-3520, SR-1976, SR-3073, SR-3479.
2017-01-09 00:23:00 -08:00
Brian Gesiak
663b92ece9 [AST] Completely replace Module with ModuleDecl
The typedef `swift::Module` was a temporary solution that allowed
`swift::Module` to be renamed to `swift::ModuleDecl` without requiring
every single callsite to be modified.

Modify all the callsites, and get rid of the typedef.
2017-01-08 00:36:08 -05:00
Mark Lacey
bd5f05cbda Merge pull request #6629 from rudkx/fix-iuo-collections
Fix one source of exponential behavior in the type checker.
2017-01-06 18:56:58 -08:00
Mark Lacey
1efafbcd9b Fix one source of exponential behavior in the type checker.
For collection literals that contained implicitly unwrapped optionals,
we were attempting three different conversions per element of the
collection, resulting in exponential type checking time.

We should only ever attempt one of these conversions for any pair of
types where one or both is optional.

We had several reports of this as it seems quite common for people to
write expressions that create a collection of IUOs from class/struct
elements, and then either return the collection or some variation that
has been filtered and mapped.

I am looking at adding the appropriate instrumentation to the type
checker so that I can add a scale-test for this and other type checker
test cases related to slow type checking so that we can avoid regressing
in the future.
2017-01-06 16:04:38 -08:00
practicalswift
6d1ae2a39c [gardening] 2016 → 2017 2017-01-06 16:41:22 +01:00
Slava Pestov
18adb53226 Sema: Tighten up name lookup routines to not look through metatypes/lvalues/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.
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
fdaace5af5 Sema: Fix terrible bug with the '() -> T' => '() -> ()' implicit conversion
We have an implicit conversion where a closure with a non-Void
result type can be passed as a function value with a Void
result; this makes single-expression closures more usable in
the case where you want the single expression to be a
statement -- discarding it's result.

Unfortunately we were checking if the locator contains a
ClosureResult component *anywhere* in the path. This is too
permissive. The correct check is that the *last* path component
is a ClosureResult.

Otherwise, we happily convert anything to () *anywhere*
in a closure result, which crashes immediately in SILGen.

Fixes <https://bugs.swift.org/browse/SR-403>.
2017-01-03 20:13:44 -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
Pavel Yaskevich
dab14d3759 [TypeChecker] Fix isAnyHashableType to check type variables
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.
2016-12-26 01:16:56 -08: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
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
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
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
Doug Gregor
642c8ed3eb [Constraint solver] Collapse getBaseTypeFor(Array|Set)Type into is(Array|Set)Type.
Follow the pattern set by isDictionaryType() of performing the query
and extracting the underlying key/element types directly. We often
need both regardless. NFC
2016-12-21 13:46:13 -08:00
Mark Lacey
170dc8acd7 Do not penalize binding or equality constraints involving Any.
We currently have an element in the solution score related to whether we
had a binding or equality constraint involving Any.

Doing this yields some strange results, e.g. if overload resolution
results in a property declared as Any we end up discarding that solution
in favor of solutions that involve other overloads that are not declared
as Any but are also not actually better solutions (e.g. overloads that
are declared as function types).

We really want to retain both solutions in this case and allow the
ranking step of the solver to decide on the better choice.

Fixes rdar://problem/29374163, rdar://problem/29691909.
2016-12-20 13:38:14 -08:00
Slava Pestov
4ed17f0f63 AST: Add a new 'isBeingValidated' flag to replace a couple of other flags
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.
2016-12-19 01:38:23 -08: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
Slava Pestov
a384b2a677 Don't call VarDecl::getType() on deserialized VarDecls 2016-12-15 22:46:15 -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