Commit Graph

1513 Commits

Author SHA1 Message Date
Chris Lattner
de79b60c89 Introduce a new UnresolvedType to the type system, and have CSDiags start to use it
as a way to get more type information out of incorrect subexpressions.  UnresolvedType
generally just propagates around the type system like a type variable:
 - it magically conforms to all protocols
 - it CSGens as an unconstrained type variable.
 - it ASTPrints as _, just like a type variable.

The major difference is that UnresolvedType can be used outside the context of a
ConstraintSystem, which is useful for CSGen since it sets up several of them to 
diagnose subexpressions w.r.t. their types.

For now, our use of this is extremely limited: when a closureexpr has no contextual
type available and its parameters are invalid, we wipe them out with UnresolvedType
(instead of the previous nulltype dance) to get ambiguities later on.

We also introduce a new FreeTypeVariableBinding::UnresolvedType approach for
constraint solving (and use this only in one place in CSDiags so far, to resolve
the callee of a CallExpr) which solves a system and rewrites any leftover type 
variables as UnresolvedTypes.  This allows us to get more precise information out,
for example, diagnosing:

 func r22162441(lines: [String]) {
   lines.map { line in line.fooBar() }
 }

with: value of type 'String' has no member 'fooBar'
instead of: type of expression is ambiguous without more context

This improves a number of other diagnostics as well, but is just the infrastructural
stepping stone for greater things.



Swift SVN r31105
2015-08-10 06:18:27 +00:00
Chris Lattner
442de4d4b0 fix <rdar://problem/22162441> Crash from failing to diagnose nonexistent method access inside closure
When CSGen was analyzing a DeclRefExpr reference, it was accidentally 
applying some magic only to anonymous closure parameters, not named ones,
leading to a silent CSGen failure.  Fix this by handling all closure parameters
the same way.



Swift SVN r31098
2015-08-08 19:09:15 +00:00
Jordan Rose
185326755c 'try?' is supposed to stack optionals, not merge them.
More rdar://problem/21692467

Swift SVN r31059
2015-08-06 21:02:40 +00:00
Jordan Rose
2801d47e59 Add Parse and Sema support for 'try?'.
rdar://problem/21692467

Swift SVN r31030
2015-08-05 22:17:25 +00:00
Jordan Rose
953424072e Guard "object literals" feature with SWIFT_ENABLE_OBJECT_LITERALS.
This is not a feature we're releasing at the moment, so provide a way
to turn it off.

rdar://problem/21935551

Swift SVN r30966
2015-08-04 00:16:52 +00:00
Slava Pestov
6171df6a13 Sema: Don't favor extension methods over protocol requirements
This bug triggered when three pre-conditions held:

- A protocol requirement method signature involves archetypes built
  from associated types
- A protocol extension provides a default implementation of this method
- The method is called from another method in the same extension,
  with a parameter of the associated type

In this case, the archetypes in the signature would match exactly
and we would end up picking the extension method over the protocol
method, which would not even be considered. As a result, the
extension method would be dispatch statically instead of using
witness method dispatch, which is wrong.

Hopefully one day we can model default implementations as real
overrides and not overloads.

Note that the test is a SILGen test even though the bug is in Sema,
since its easier to detect the problem at the SIL level.

Fixes <rdar://problem/21995666>.

Swift SVN r30847
2015-07-31 04:46:35 +00:00
Slava Pestov
d1d5bcfb8c Small cleanups to overload-related code, NFC
ProtocolType::get() is weird...

Swift SVN r30846
2015-07-31 04:46:33 +00:00
John McCall
b75f5f2450 Type-check catch patterns in closures as necessary in order
to decide whether they're exhaustive.

Unfortunately, we can't actually just type-check the pattern
because it might be dependent on other local type-checking state,
like the types of arguments or variables defined within the closure.
So instead we try to recognize a very specific pattern shape that
should be safe to coerce.

Also, this potentially introduces redundant diagnostics because
of the double-check, but it's tricky to do anything about it.
I think it's better to have these potential redundancies than
to infer a throwing closure type with 'catch let e as NSError',
though.

rdar://21715350

Swift SVN r30701
2015-07-27 22:57:47 +00:00
Slava Pestov
65b317fa36 Sema: Fix infinite recursion when checking if class with circular inheritance has failable initializer
Fixes <rdar://problem/19919421>.

Swift SVN r30677
2015-07-27 00:40:45 +00:00
Chris Lattner
449e835941 this went with the former patch, bad cherrypick
Swift SVN r30657
2015-07-26 18:58:46 +00:00
Chris Lattner
622b6469fe rename a local variable, nfc
Swift SVN r30649
2015-07-26 05:18:23 +00:00
Chris Lattner
04cca603c8 Start peering through the fog of ClosureExprs, using ambiguously typed subexprs to
diagnose problems inside of them instead of punting on them completely.

This leads to substantially better error messages in many cases, fixing:
 <rdar://problem/19870975> Incorrect diagnostic for failed member lookups within closures passed as arguments ("(_) -> _")
 <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back
 <rdar://problem/20712541> QoI: Int/UInt mismatch produces useless error inside a block

and possibly others.  We are not yet capitalizing on available type information we do
have about closure exprs, so there are some cases where we produce
  "error: type of expression is ambiguous without more context"
when this isn't strictly true, but this is still a huge step forward.



Swift SVN r30547
2015-07-23 20:31:43 +00:00
Doug Gregor
f00e5bc6ab Allow a variadic parameter anywhere in the parameter list.
Requiring a variadic parameter to come at the end of the parameter
list is an old restriction that makes no sense nowadays, and which we
had all thought we had already lifted. It made variadic parameters
unusable with trailing closures or defaulted arguments, and made our
new print() design unimplementable.

Remove this restriction, replacing it with a less onerous and slightly
less silly restriction that we not have more than one variadic
parameter in a given parameter clause. Fixes rdar://problem/20127197.

Swift SVN r30542
2015-07-23 18:45:29 +00:00
Joe Pamer
a900fd7bc2 Fix a couple of common crashers related to functions with default arguments. (rdar://problem/21799331 and rdar://problem/21643052, plus dupes.)
If a function declaration possessed default parameters, and was invoked with a single argument expression that was modeled as a type variable, the compiler would often crash during type application.  This was due to the fact that during simplification, we would bind the type variable to the full tuple type of the parameter list. Later on, during constraint application, we would then look to whatever expression created the type variable for information on its default arguments - even if no such thing was possible. (E.g., we would examine, say, an IfExpr expecting to find information on its default arguments.) In these cases, we should have instead been binding the argument type variable to the first element of the parameter tuple.

Swift SVN r30486
2015-07-22 01:19:08 +00:00
John McCall
50a667b295 Instead of assuming that the return type of a closure
with no returns *must* be (), add a defaulting constraint
so that it will be inferred as () in the absence of
other possibilities.

The chief benefit here is that it allows better QoI when
the user simply hasn't yet written the return statement.

Doing this does regress a corner case where an attempt
to recover from an uncalled function leads to the
type-checker inferring a result for a closure that
doesn't make any sense at all.

Swift SVN r30476
2015-07-22 00:13:02 +00:00
Chris Lattner
79838f6dbe fix a case in CSGen where it gets an ErrorType back and splats it onto the AST,
instead of treating it as an erroneous subexpr.  This was causing <<error type>> to pop
out in diagnostics, and had a hackaround that dissolves now from CSDiags.



Swift SVN r30442
2015-07-21 05:03:38 +00:00
John McCall
bc3b47b98a Infer the return type of a closure to be () if it contains no
return statements, or a return statement with no operand.

Also, fix a special-case diagnostic about converting a return
expression to (1) only apply to converting the actual return
expression, not an arbitrary sub-expression, and (2) use the
actual operand and return types, not the drilled-down types
that caused the failure.

Swift SVN r30420
2015-07-20 21:52:18 +00:00
Devin Coughlin
c1caddae62 Remove experimental support for treating unavailable symbols as optional.
This has always been off by default and is a language direction we have decided not to
pursue.

Swift SVN r30355
2015-07-18 01:56:25 +00:00
John McCall
a0ee7b2772 Don't look through 'try!' in getSemanticsProvidingExpr().
To support this, make 'try' and 'try!' no longer IdentityExprs
and give them a common base class to simplify the sorts of
analyses and transformations that do want to treat them
as identity-like.

Note that getSPE() still looks through normal 'try', since
the overwhelming proportion of clients will consider it
semantically equivalent to the undecorated expression.

Change getValueProvidingExpr() to look through try!, since
it's allowed to return something with slightly different
semantics, and use it in the unused-result diagnostic.

Fixes a large number of bugs, mostly uncaught, with SILGen
peepholes that use getSPE() and therefore were accidentally
looking through try!.  <rdar://21515402>

Swift SVN r30224
2015-07-15 19:34:18 +00:00
Joe Pamer
3edab3db8d When walking overload groups during constraint analysis, defend against function/decl type mismatches. (rdar://problem/20162476)
Swift SVN r30202
2015-07-14 22:58:54 +00:00
Chris Lattner
8637bb4c01 fix <rdar://problem/21679169> compiler crashes on "{(=_=_)in"
Swift SVN r29914
2015-07-06 04:46:56 +00:00
Slava Pestov
e7d8c3c4bc Sema: Fix synthesis of materializeForSet for subscripts in protocol extensions
Since each override of a subscript protocol requirement provides
its own materializeForSet, there is no need to do dynamic dispatch,
a peer call to the setter suffices. However, since CodeSynthesis
runs at the AST level, it would create a SubscriptExpr which
overload resolution would later bind to the protocol requirement
subscript rather than the static witness in the extension.

This triggered an assertion. Solve the problem by binding the
actual ConcreteDeclRef of the SubscriptExpr at synthesis time,
and modifying CSGen to special-case SubscriptExprs that already
have a ConcreteDeclRef set.

Fixes <rdar://problem/21370629>.

Swift SVN r29906
2015-07-03 02:25:26 +00:00
Chris Willmore
99058b45a5 Only strip implicit self parameter from func decl type if the func decl
has an implicit self decl. Follow-up to r29732.

Swift SVN r29742
2015-06-26 17:15:20 +00:00
Chris Willmore
fd5812be50 Don't assume that a ValueDecl in a type DeclContext with function type
is an instance method. Make sure it's a non-static function before
attempting to strip the implicit self parameter from the type.

<rdar://problem/20886179> compiler error

Swift SVN r29732
2015-06-26 05:39:38 +00:00
Ben Langmuir
1be2a778c1 [CodeCompletion] Avoid choking on a doubly-typechecked expr
First, fix a case of type checking an expression twice, which is against
the design of the type checker. We hit this because we can type check
the "context" in
  let x = foo.#^COMPLETE^#
and then type check the "parsed expression", which is contained in the
context here.

Second, make the hack from rdar://20738314 more robust so that if we
*do* double typecheck for some reason we won't just choke on an
AutoClosureExpr.  I filed rdar://21466394 to audit for other cases of
double typechecking and remove this hack.

Fixes rdar://21346928

Swift SVN r29527
2015-06-19 22:16:07 +00:00
Joe Groff
bebfa969bd Sema: Allow 'x.init' references on metatype expressions.
If 'x.init' appears as a member reference other than 'self.init' or 'super.init' within an initializer, treat it as a regular static member lookup for 'init' members. This allows a more explicit syntax for dynamic initializations; 'self.someMetatype()' looks too much like it's invoking a method. It also allows for partial applications of initializers using 'someMetatype.init' (though this needs some SILGen fixes, coming up next). While we're in the neighborhood, do some other correctness and QoI fixes:

- Only lookup initializers as members of metatypes, not instances, and add a fixit (instead of crashing) to insert '.dynamicType' if the initializer is found on an instance.
- Make it so that constructing a class-constrained archetype type correctly requires a 'required' or protocol initializer.
- Warn on unused initializer results. This seems to me like just the right thing to do, but is also a small guard against the fact that 'self.init' is now valid in a static method, but produces a newly-constructed value instead of delegating initialization (and evaluating to void).

Swift SVN r29344
2015-06-08 04:11:28 +00:00
Joe Groff
1479a56ab3 Sema: Move semantic constraints on super/self.init out of the parser.
Instead of forcing full application of '{super,self}.init' in the parser, and installing the RebindSelf semantic expr node early, make these constraints to Sema-time checks, and parse '<expr>.init' as a regular postfix production. This is a better separation of concerns, and also opens the door to supporting 'metatype.init()' in more general expression contexts (though that part still needs some follow-up sema work).

Swift SVN r29343
2015-06-08 04:11:16 +00:00
Jordan Rose
2d66428272 Clean up KnownIdentifiers.def.
- Remove unused names.
- Define IDENTIFIER in terms of IDENTIFIER_WITH_NAME.
- Adjust each name to always match the corresponding value in case.
- Add an IDENTIFIER_ macro for the common case of defining an underscored name.
- Avoid creating names with double underscores, which are technically reserved
  by the C++ standard.

There are two special cases I left in here for the identifiers '_code' and
'_domain'. I didn't want to call these simply 'Id_code' and 'Id_domain' for
fear someone would try to use them as 'code' and 'domain', so I made them into
'Id_code_' and 'Id_domain_' for now.

No intended functionality change.

Swift SVN r29291
2015-06-04 04:01:06 +00:00
Ben Langmuir
477ea489c7 [CodeCompletion] Avoid assert when top-level if contains an autoclosure
We have an unreachable in the visitor for auto closures, so avoid
visiting it.  It would be great to have a clearer picture of what needs
to happen for AutoClosure vs ClosureExpr. It's hard to tell exactly
where AutoClosure is supposed to be handled if at all.

Swift SVN r29037
2015-05-26 20:09:42 +00:00
Chris Lattner
e517ad9182 Fix unreachable code handling to properly diagnose things like:
throw x 
whatever()  

as being unreachable after the throw.



Swift SVN r28680
2015-05-17 15:13:35 +00:00
Dmitri Hrybenko
0a1f7c09df Revert "Fix unreachable code handling to properly diagnose things like:"
This reverts commit 28678.  It broke the IDE/complete_exception.swift
test.

Swift SVN r28679
2015-05-17 12:27:57 +00:00
Chris Lattner
5ead9764bd Fix unreachable code handling to properly diagnose things like:
throw x
  whatever()

as being unreachable after the throw.



Swift SVN r28678
2015-05-17 05:56:02 +00:00
John McCall
5d4fa0b7b6 A better fix: stop storing the address of a type in the constraint
system in the first place, because it's totally immutable on all
access paths.

Swift SVN r28595
2015-05-15 01:05:56 +00:00
Joe Pamer
9bf1f91893 Prevent the type checker from going exponential on straightforward bindings of named patterns to nested array literals. I have a more principled fix for these kinds of issues in the works, but this will unblock a lot of users until those changes land. (rdar://problem/19810828)
Swift SVN r28544
2015-05-14 00:15:57 +00:00
Chris Lattner
8a7b3f414e Revise the parser and AST representation of #available to be part of StmtCondition
instead of being an expression.

To the user, this has a couple of behavior changes, stemming from its non-expression-likeness.
 - #available cannot be parenthesized anymore
 - #available is in its own clause, not used in a 'where' clause of if/let.

Also, the implementation in the compiler is simpler and fits the model better.  This
fixes:
<rdar://problem/20904820> Following a "let" condition with #available is incorrectly rejected



Swift SVN r28521
2015-05-13 19:00:40 +00:00
Doug Gregor
2653a6569b Eliminate ModuleExpr; DeclRefExpr is good enough for anyone.
Swift SVN r28285
2015-05-07 21:10:53 +00:00
Joe Pamer
3b57cabae7 Consider default argument patterns, as they relate to actual arguments, when deciding on a specific overload to favor for a function application. Doing so addresses another class of exponential behavior bugs in the type checker (rdar://problem/19779591 and rdar://problem/20772053). There's still some work left to do, though - hence the change to Concatenate.swift, to work around rdar://problem/20789500.
Swift SVN r28221
2015-05-06 22:32:07 +00:00
John McCall
204bb04f04 In closure 'throws' inference, infer 'throw' as throwing.
Also, walk into 'do' bodies when the catches aren't
exhaustive, but don't walk into try! operands.

Swift SVN r28092
2015-05-02 19:50:21 +00:00
Doug Gregor
a30ca2a60d Replace bool parameter to TypeChecker::conformsToProtocol() with an option set.
NFC; we can extend this option set more readily later.

Swift SVN r27894
2015-04-29 00:08:22 +00:00
Chris Lattner
6c8e9ac276 change some calls to dyn_cast in boolean contexts to isa.
Swift SVN r27724
2015-04-25 23:34:38 +00:00
Chris Lattner
d18740d603 Fix <rdar://problem/19773562> Closures executed immediately { like this }() are not automatically @noescape
In addition to being better for performance in these cases, this disables the "self." 
requirement in these blocks.  {}() constructs are often used to work around statements
that are not exprs in Swift, so they are reasonably important.

Fixing this takes a couple of pieces working together:
 - Add a new 'extraFunctionAttrs' map to the ConstraintSystem for solution
   invariant function attributes that are inferred (like @noescape).
 - Teach constraint simplification of function applications to propagate 
   @noescape between unified function types.
 - Teach CSGen of ApplyExprs to mark the callee functiontype as noescape
   when it is obviously a ClosureExpr.

This is a very limited fix in some ways: you could argue that ApplyExpr should
*always* mark its callee as noescape.  However, doing so would just introduce a
ton of function conversions to remove it again, so we don't do that.




Swift SVN r27723
2015-04-25 23:34:18 +00:00
Joe Pamer
d4e744b2ed Use "isa" instead of "dyn_cast".
Swift SVN r27606
2015-04-22 21:35:57 +00:00
Joe Pamer
220c92a09b Revert "Revert "A couple of 'throws' inference fix-ups:""
This reverts commit r27576.

(In some cases of catastrophic error recovery, ctor types may still be null during constraint solving, so it was wrong of me to assume otherwise.)

Swift SVN r27599
2015-04-22 20:34:05 +00:00
Dmitri Hrybenko
4229e8a14f Revert "A couple of 'throws' inference fix-ups:"
This reverts commit r27568 to unblock the buildbot.  It regressed three
compiler crashers:

    Swift :: compiler_crashers_fixed/0367-llvm-errs.swift
    Swift :: compiler_crashers_fixed/1769-getselftypeforcontainer.swift
    Swift :: compiler_crashers_fixed/1916-swift-nominaltypedecl-getdeclaredtypeincontext.swift

Swift SVN r27576
2015-04-22 08:42:21 +00:00
Joe Pamer
70fd1d6360 A couple of 'throws' inference fix-ups:
- When inferring 'throws' for a closure function type, look inside of catchless do blocks for 'try' expressions.
- When simplifying overload constriants for applications of throwing initializers, the bound member type of the initializer should also be marked as throwing.
  (Not doing so would cause us to incorrectly reject the overload.)

Swift SVN r27568
2015-04-22 06:39:39 +00:00
Chris Willmore
d4db635e3d Add object literal syntax and _{Color,Image}LiteralConvertible protocols
Add syntax "[#Color(...)#]" for object literals, to be used by
Playgrounds for inline color wells etc. The arguments are forwarded to
the relevant constructor (although we will probably change this soon,
since (colorLiteralRed:... blue:... green:... alpha) is kind of
verbose). Add _ColorLiteralConvertible and _ImageLiteralConvertible
protocols, and link them to the new expressions in the type checker.
CSApply replaces the object literal expressions with a call to the
appropriate protocol witness.

Swift SVN r27479
2015-04-20 12:55:56 +00:00
Joe Pamer
006c182c13 Begin inferring throwing function types for closures. (There's more work to do here - hence the thin tests - but I need to investigate a couple of sema bugs before moving forward.)
Swift SVN r27438
2015-04-17 19:06:52 +00:00
Joe Pamer
e4f7fee4f4 When gathering "linked" expressions to determine a favored constraint, consider top-level literals to be fair game.
This unblocks standard library work by preventing us from going exponential when extending existing struct types to have failable initializers. (rdar://problem/20336356)
On my laptop, it also results in a 7% end-to-end improvement in the time it takes to run our unit tests under DebugAssert (previously: 591.63s, now: 552.64s). Though, as usual, YMMV.

Swift SVN r27156
2015-04-09 01:54:34 +00:00
Chris Lattner
79ed57f9f2 standardize naming of tuples and tuple patterns on "elements".
Previously some parts of the compiler referred to them as "fields",
and most referred to them as "elements".  Use the more generic 'elements'
nomenclature because that's what we refer to other things in the compiler
(e.g. the elements of a bracestmt).

At the same time, make the API better by providing "getElement" consistently
and using it, instead of getElements()[i].

NFC.



Swift SVN r26894
2015-04-02 20:23:49 +00:00
Chris Lattner
f7fe8a5f4a Fix <rdar://problem/20392122> Destructuring tuple with labels doesn't work
This pushes tuple pattern labels forward:
  - Actually record them in TuplePatternElt.
  - Remove the tuple shuffle ban that prevents some cases
    (e.g. the one in the radar) of a tuple with labels being shuffled
    onto a tuple without labels.
  - Remove dead code enabled by removing the restriction.



Swift SVN r26852
2015-04-02 04:23:54 +00:00