Commit Graph

91 Commits

Author SHA1 Message Date
Pavel Yaskevich
1f222f307e [ConstraintSystem] Make sure pattern matching tuple destructuring works both ways
Consider following example:

```swift
enum E {
  case foo((x: Int, y: Int))
  case bar(x: Int, y: Int)
}

func test(e: E) {
  if case .foo(let x, let y) = e {}
  if case .bar(let tuple) = e {}
}
```

Both of `if case` expressions have to be supported:

1. `case .foo(let x, let y) = e` allows a single tuple
   parameter to be "destructured" into multiple arguments.

2. `case .bar(let tuple) = e` allows to match multiple
   parameters with a single tuple argument.

Resolves: rdar://problem/60061646
2020-03-05 14:05:35 -08:00
Pavel Yaskevich
87878a65eb [ConstraintSystem] Preserve label matching rules in pattern matching context
Since constraint system now handles pattern matching it has
to preverse label matching semantics which existed in original
code: if pattern element has a label it has to match the one
in the tuple type it's matched against.

Resolves: rdar://problem/60048356
2020-03-04 23:09:31 -08:00
Doug Gregor
dcf7ddeb3a [Constraint system] Generate constraints for EnumElement patterns.
Generate a complete set of constraints for EnumElement patterns, e.g.,

    case let .something(x, y)

Most of the complication here comes from the implicit injection of optionals,
e.g., this case can be matched to an optional of the enum type of which
`something` is a member. To effect this change, introduce a locator for
pattern matching and use it to permit implicit unwrapping during member
lookup without triggering an error.

Note also labels are dropped completely when performing the match,
because labels can be added or removed when pattern matching. Label
conflict are currently diagnosed as part of coercePatternToType, which
suffices so long as overloading cases based on argument labels is not
permitted.

The primary observable change from this commit is in diagnostics: rather
than diagnostics being triggered by `TypeChecker::coercePatternToType`,
diagnostics for matching failures here go through the diagnostics machinery
of the constraint solver. This is currently a regression, because
there are no custom diagnostics for pattern match failures within the
constraint system. This regression will be addressed in a subsequent
commit; for now, leave those tests failing.
2020-02-24 00:48:15 -08:00
Holly Borla
d1f6b3e2ef [Diagnostics] When diagnosing an ambiguous overload, don't mention "call"
if the expression is not a function application.
2020-02-11 14:53:27 -08:00
Pavel Yaskevich
8bcc192591 [Diagnostics] Diagnose inability to infer (complex) closure return type 2019-12-19 12:16:30 -08:00
Slava Pestov
1df3d1a33c Frontend: Don't interleave parsing and typechecking for the main file
SIL files still require this behavior; if we cleaned that up we
could simplify a fair bit of code here.

Fixes <https://bugs.swift.org/browse/SR-284>,
<https://bugs.swift.org/browse/SR-4426>.
2019-12-05 08:45:55 -05:00
Pavel Yaskevich
94b4052321 [CSDiag] NFC: Remove all of the obsolete diagnoseGeneral*Failures logic 2019-12-03 12:07:16 -08:00
Pavel Yaskevich
11644b3f31 [Diagnostics] Diagnose assignment type mismatches related to unresolved members 2019-11-05 12:43:32 -08:00
Holly Borla
561e527848 [ConstraintSystem] Extend the ExplicitlySpecifyGenericArguments fix to cover
all cases of missing generic parameters.

In `ComponentStep::take` when there are no bindings or disjunctions, use hole
propagation to default remaining free type variables that aren't for generic
parameters and continue solving. Rather than using a defaultable constraint for
holes, assign a fixed type directly when we have no bindings to try.
2019-11-05 09:15:13 -08:00
Robert Widmann
0267384e11 Fixup SourceKit and Tests
Patch up all the places that are making a syntactic judgement about the
isInvalid() bit in a ValueDecl.  They may continue to use that query,
but most guard themselves on whether the interface type has been set.
2019-10-30 15:09:14 -07:00
Robert Widmann
742f6b2102 Drastically Simplify VarDecl Validation
This is an amalgam of simplifications to the way VarDecls are checked
and assigned interface types.

First, remove TypeCheckPattern's ability to assign the interface and
contextual types for a given var decl.  Instead, replace it with the
notion of a "naming pattern".  This is the pattern that semantically
binds a given VarDecl into scope, and whose type will be used to compute
the interface type. Note that not all VarDecls have a naming pattern
because they may not be canonical.

Second, remove VarDecl's separate contextual type member, and force the
contextual type to be computed the way it always was: by mapping the
interface type into the parent decl context.

Third, introduce a catch-all diagnostic to properly handle the change in
the way that circularity checking occurs.  This is also motivated by
TypeCheckPattern not being principled about which parts of the AST it
chooses to invalidate, especially the parent pattern and naming patterns
for a given VarDecl.  Once VarDecls are invalidated along with their
parent patterns, a large amount of this diagnostic churn can disappear.
Unfortunately, if this isn't here, we will fail to catch a number of
obviously circular cases and fail to emit a diagnostic.
2019-10-14 12:06:50 -07:00
Suyash Srijan
5d77258843 [Typechecker] Relax the check only for non-final classes 2019-08-31 00:50:49 +01:00
Pavel Yaskevich
3e9287cb9a [Diagnostics] Fix diagnostic improved after labeling changes 2019-07-26 11:53:15 -07:00
Doug Gregor
54bdd7b840 [Constraint solver] Migrate ConstraintGraph::gatherConstraints() off adjacencies list.
Use the adjacencies implied by the constraints of a node rather than looking
at the "adjacency" list, and try to simplify this code path a bit. The
diagnostic change is because we are now uniformly recording the
members of the equivalence class.
2019-07-25 01:54:06 -04:00
Suyash Srijan
f7837c1694 [test] update cast diagnostics for existing tests 2019-03-21 00:22:51 +00:00
Joe Groff
7011f32d3a Merge pull request #22486 from theblixguy/fix/SR-7799
[Typechecker] Allow matching an enum case against an optional enum without '?'
2019-03-04 09:50:06 -08:00
Doug Gregor
69ef7895a8 [Constraint solver] Match argument labels for unresolved member expressions. 2019-03-01 23:11:34 -08:00
Suyash Srijan
407c38e9cd [typechecker] look through all optionals 2019-02-27 23:13:30 +00:00
Suyash Srijan
82da03733a Merge branch 'master' into fix/SR-7799 2019-02-27 22:43:08 +00:00
Pavel Yaskevich
d4b67bf3f7 [Diagnostics] Improve argument labeling diagnostics
Extend new labeling diagnostics (via fixes) to support
member references and subscripts.
2019-02-21 16:42:56 -08:00
Suyash Srijan
4e56b54b94 [typechecker] [test] cleanup 2019-02-09 17:24:12 +00:00
Suyash Srijan
7356f41881 [typechecker] allow non-optional enum case match with optional enum 2019-02-08 23:29:33 +00:00
Pavel Yaskevich
1c79380a12 [CSFix] Couple of small cleanups related to ForceOptional
* Make sure that base and unwrapped types aren't null
* Don't allocate `ForceOptional` fix if nothing has been unwrapped
  in `simplifyApplicableFnConstraint`
* Add sugar reconstitution support to `FailureDiagnostic::resolveType`
* Format diagnostics a bit better
2019-01-26 00:48:01 -08:00
Suyash Srijan
5b7fd8cc97 [test] Updates diagnostic messages for existing tests 2019-01-25 17:27:09 +00:00
Pavel Yaskevich
74a8ee177e [Diagnostics] Diagnose missing members via fixes
Try to fix constraint system in a way where member
reference is going to be defined in terms of its use,
which makes it seem like parameters match arguments
exactly. Such helps to produce solutions and diagnose
failures related to missing members precisely.

These changes would be further extended to diagnose use
of unavailable members and other structural member failures.

Resolves: rdar://problem/34583132
Resolves: rdar://problem/36989788
Resolved: rdar://problem/39586166
Resolves: rdar://problem/40537782
Resolves: rdar://problem/46211109
2019-01-09 17:29:49 -08:00
Pavel Yaskevich
dc6f86d9b7 [CSRanking] Fix solution filtering not to erase everything when set is completely ambiguous
Since constraint solver has been improved to diagnose more problems
via "fixes", sometimes applying fixes might lead to producing solutions
which are completely ambiguous when compared to each other, and/or are
incomparable, which leads to `findBestSolutions` erasing all of them
while trying to compute best "partial" solution, which is incorrect.

Resolves: rdar://problem/42678836
2018-08-06 17:25:58 -07:00
gregomni
775cca60b6 Constrain type checking of expressions in optional pattern bindings
so that they must result in an optional type.

Add constraint locator path for identifying constraints/variables that are part of the convert type passed into the system.
2018-07-27 18:05:21 -07:00
Doug Gregor
945c09b1cc [Type checker] Improve diagnostics when an optional value is not unwrapped.
When we determine that an optional value needs to be unwrapped to make
an expression type check, use notes to provide several different
Fix-It options (with descriptions) rather than always pushing users
toward '!'. Specifically, the errors + Fix-Its now looks like this:

    error: value of optional type 'X?' must be unwrapped to a value of
        type 'X'
      f(x)
        ^
    note: coalesce using '??' to provide a default when the optional
        value contains 'nil'
      f(x)
        ^
          ?? <#default value#>
    note: force-unwrap using '!' to abort execution if the optional
        value contains 'nil'
      f(x)
         ^
         !

Fixes rdar://problem/42081852.
2018-07-13 11:02:04 -07:00
Mark Lacey
ddc671c0c6 Split test case verifying we're no longer exponential type checking tuples.
Split the test case out into multiple validation scale-tests.

Add a new test for 'weak' as well.
2018-03-28 17:08:25 -07:00
Mark Lacey
9385dbb3fb Fix exponential type checking of tuple literals.
This fixes two easy cases where we would go exponential in type
checking tuple literals.

Instead of generating a conversion to a single type variable (which
results in one large constraint system), we generate a conversion ot
the same type that appears in the initializer expression (which for
tuples is a tuple type, which naturally splits the constraint system).

I experimented with trying to generalize this further, but ran into
problems getting it working, so for now this will have to do.

Fixes rdar://problem/20233198.
2018-03-26 14:46:03 -07:00
Doug Gregor
ba6f605d47 Fix some tests due to Equatable Optional/Array/Dictionary change. 2017-11-27 21:09:50 -08:00
Greg Parker
e8475cc130 Revert "Use conditional conformances to implement Equatable for Optional, Array and Dictionary" 2017-11-15 14:17:22 -08:00
Doug Gregor
9f68fdae80 [Conditional conformances] Fix up test cases that changed for the better. 2017-11-14 16:23:20 -08:00
Doug Gregor
e1e0deca33 Reject unbound generic types in case patterns.
Fixes SR-6100 / rdar://problem/34898452.
2017-10-25 23:19:28 -07:00
Pavel Yaskevich
5f57183654 [QoI] Add fix-it for cases in switch with optional chaining
When type-checking switch statements with patterns let's
check if we have an optional type and try to see if the case
exists in its base type, if so we can suggest a fix-it.

Resolves: rdar://problem/32241441
2017-06-28 22:20:55 -07:00
Alex Hoppen
99acf816f4 [Diag] Correct fixit location of "?" when pattern matching optional with non-optional
Trying to pattern match an optional with a non-optional should provide
a fixit inserting a "?" after the last token and not before it.
2017-06-07 07:25:46 -07:00
Robert Widmann
4e2f36c763 Lift case redundancy checks into Sema 2017-05-01 01:32:02 -04:00
Robert Widmann
39494b2ba2 Rearrange test code for exhaustiveness 2017-04-28 02:06:39 -04:00
Joe Groff
fc16cb5dda Sema: Let .foo patterns fall back to being ExprPatterns if they don't match an enum case.
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.
2017-02-28 21:51:39 -08:00
Brian King
c231b8cab3 Fix a test failure 2017-01-27 22:26:10 -05:00
Slava Pestov
1cb656314b Sema: Fix crash with unresolved 'is' pattern 2016-12-21 14:20:28 -05:00
David Farler
b7d17b25ba Rename -parse flag to -typecheck
A parse-only option is needed for parse performance tracking and the
current option also includes semantic analysis.
2016-11-28 10:50:55 -08:00
Mark Lacey
401ca24532 Emit a warning when optionals are coerced to Any.
Emit a warning for optionals that are implicitly converted to Any, and
add fixits giving options to:
- Add '??' with a default value after
- Force-unwrap the optional with '!'
- Explicitly cast to 'as Any' to silence the warning

This covers diagnostics aspect of SE-0140.

rdar://problem/28196843
2016-09-20 22:33:45 -07:00
practicalswift
fa7fbdb8b0 [gardening] Remove redundant nil-initialization of optional variable
From the Swift documentation:

"If you define an optional variable without providing a default value,
 the variable is automatically set to nil for you."
2016-09-18 07:40:07 +02:00
Chris Lattner
807345a909 When we get an abiguity problem with a multi-statement closure return type, it is
almost always the case that the user didn't know what the rules are between
single expression and multistatement closures, and they often don't know how to
fix the problem.

Address this by doing some heroics when we detect this situation.  We now go dive
into the closure body, type check the explicit returns within it, and can usually
divine the right answer.  When we do that, generate a fixit hint that generates a
modification to the existing signature, or synthesizes the entire signature from
scratch.  This addresses:
<rdar://problem/22123191> QoI: multi-line closure with failure to infer result type should add a fixit
2016-07-30 14:36:47 -07:00
Chris Lattner
764d0fc371 improve the diagnostics for when a multi-statement closure has no inferred result type.
Previously:

error: generic parameter 'T' could not be inferred
now:
error: unable to infer closure return type in current context

There is still more to do, but this fixes:
<rdar://problem/23570873> QoI: Poor error calling map without being able to infer "U" (closure result inference)
2016-07-29 17:49:23 -07:00
Jacob Bandes-Storch
c3126e9f4f Fix ParenPattern resolution when subexpression is a NilLiteralExpr 2016-07-17 15:24:58 -07:00
Robert Widmann
a7ee8ba9cf Merge pull request #3488 from ahoppen/SR-2057-match-opt-enum
[Sema] Fix compiler crash when pattern matching optional enum
2016-07-13 08:54:56 -07:00
Alex Hoppen
a97585cbdd [Sema] Fix compiler crash when pattern matching optional enum
TypeCheckPattern was able to take the path checking if `Optional.None`
should be renamed to lowercase `Optional.none` and if this wasn't
necessary still failed but without generating a diagnostic.
Now it always provides a diagnostic when failing.

This fixes SR-2057.
2016-07-13 09:19:04 +02:00
Robert Widmann
f97e5dcb0e [SE-0115][1/2] Rename *LiteralConvertible protocols to ExpressibleBy*Literal. This
change includes both the necessary protocol updates and the deprecation
warnings
suitable for migration.  A future patch will remove the renamings and
make this
a hard error.
2016-07-12 15:25:24 -07:00