Commit Graph

127 Commits

Author SHA1 Message Date
Pavel Yaskevich
13e3269d16 [CSFix] Fix a null pointer dereference in getStructuralTypeContext
First problem - the logic used constraint system, which shouldn't
be required, second - it expects the type to be always present in
`ContextualTypeInfo` but that's not the case for some patterns.

Resolves: rdar://131819800
2025-02-24 13:57:28 -08:00
Hamish Knight
d6d8d08608 [CS] Better diagnose conformance failures for EnumElementPatterns
Previously we could end up with a
ContextualMismatch fix and a MissingConformance fix
for different elements of the `matchTypes` disjunction,
leading to an ambiguity. Instead, avoid recording
the ContextualMismatch if we're matching an
existential, and tweak the MissingConformance
failure to have a custom diagnostic for
EnumElementPattern matching.
2024-07-15 12:47:50 +01:00
Holly Borla
9ba481ad53 [Diagnostics] Clarify the wording of error_in_future_swift_version. 2024-03-01 12:05:51 -08:00
Pavel Yaskevich
10c794e568 [CSDiagnostics] Produce a diagnostic for patterns with extraneous elements
Extend `ExtraneousArgumentsFailure` to handle enum element
pattern mismatches.

Resolves: rdar://123466496
2024-02-26 14:30:29 -08:00
Doug Gregor
be6393b7ca Use any Error for caught error type of an exhaustive, non-throwing do..catch
Prior to the introduction of typed throws, a `do..catch` always had a caught
error type of `any Error`, even if there were no throwing sites within
the `do` body. With typed throws, such a `do..catch` would have a
caught error type of `Never`, because it never throws. Unfortunately,
this causes code like the following to produce an error, because
`Never` cannot be pattern-matched to `HomeworkError.forgot`:

    func test() {
      do {
        try nonthrowing()
      } catch HomeworkError.forgot {
      } catch {
      }
    }

For source-compatibility reasons, adjust the caught error type to
`any Error` in this case, so we continue to accept the code above.
Don't do this adjustment under `FullTypedThrows`, because it's only
there for compatibility.

Fixes rdar://121526201.
2024-01-24 14:42:56 -08:00
Freddy Kellison-Linn
d13e997d07 [TypeCheckPattern] Attempt ExprPattern conversion before failing pattern coercion to optional 2023-07-23 12:04:38 -04:00
Hamish Knight
390f5c3e3a [CS] Avoid crashing if we have no contextual type for initialization
For `CTP_Initialization`, there's no contextual
type to record if the pattern is not a
`TypedPattern`. As such, tweak
`RequirementFailure::getDeclRef` to handle this
case.

We probably ought to reconsider how we handle
contextual types here, using a ContextualType
locator when there is no contextual type recorded
seems a bit weird, though in most cases we want
to treat initializations the same regardless of
if a TypedPattern was used. For now I'm leaving
that as future work.

rdar://111009224
2023-06-20 13:09:48 +01:00
Hamish Knight
eaa61a0469 [test] Add test case that exercises lots of ~= overloads 2023-06-07 00:42:45 +01:00
Hamish Knight
da86703e2a [CS] Fix coercePatternToType enum cast handling
Previously if the cast was unresolved, we would
emit a warning and bail with `nullptr`. This is
wrong, because the caller expects a `nullptr`
return to mean we emitted an error. Change the
diagnostic to an error to fix this. This may
appear source breaking, but in reality previously
we were failing to add the cast at all in this case,
which lead to a crash in SILGen. We really do
want to reject these cases as errors, as this
will give us a better opportunity to fall back to
type-checking as ExprPatterns, and better matches
the constraint solver type-checking.

Also while we're here, change the diagnostic for
the case where we don't have an existential context
type from the confusing "enum doesn't have member"
diagnostic to the pattern mismatch diagnostic.

rdar://107420031
2023-06-07 00:35:02 +01:00
Hamish Knight
7a137d6756 [CS] Allow ExprPatterns to be type-checked in the solver
Previously we would wait until CSApply, which
would trigger their type-checking in
`coercePatternToType`. This caused a number of
bugs, and hampered solver-based completion, which
does not run CSApply. Instead, form a conjunction
of all the ExprPatterns present, which preserves
some of the previous isolation behavior (though
does not provide complete isolation).

We can then modify `coercePatternToType` to accept
a closure, which allows the solver to take over
rewriting the ExprPatterns it has already solved.

This then sets the stage for the complete removal
of `coercePatternToType`, and doing all pattern
type-checking in the solver.
2023-06-07 00:35:01 +01:00
Hamish Knight
8d2f2baff0 [CS] Remove external type logic from getTypeForPattern
This shouldn't be necessary, we should be able to
solve with type variables instead. This makes sure
we don't end up with weird special cases that only
occur when an external type is present.
2023-06-07 00:35:00 +01:00
Hamish Knight
592733b350 [Sema] Don't set FunctionRefKind::Compound for an implicit ~=
It's not clear to me why it was ever set this way,
but it prevents IUOs from working with the match
operator. Unset it, and let pre-checking correctly
assign it a `FunctionRefKind::SingleApply`.
2023-03-07 15:16:36 +00:00
Michael Gottesman
0ad5a18d40 Update test output. 2023-03-03 18:19:26 -08:00
Michael Gottesman
c97121d3ee [reference-binding] Add support for inout binding parsing/serialization. 2023-03-01 20:48:54 -08:00
Pavel Yaskevich
e313c533b6 [ConstraintSystem] Teach getCalleeLocator about pattern matching
Requesting a callee locator from locator in pattern matching context
should always yield pattern match.
2023-02-07 11:13:32 -08:00
Anthony Latsis
8f096bf6a8 Merge pull request #60617 from AnthonyLatsis/migrate-test-suite-to-gh-issues-6
Gardening: Migrate test suite to GH issues p. 6
2022-08-20 19:52:06 +03:00
Anthony Latsis
06be02636c Gardening: Migrate test suite to GH issues: Constraints (3/5) 2022-08-18 05:36:07 +03:00
Pavel Yaskevich
8cd88544fd Merge pull request #60504 from LucianoPAlmeida/any-pattern-hole
[test] Add any_pattern in tuple pattern element extra tests
2022-08-12 09:46:12 -07:00
Luciano Almeida
89c1a4e597 [tests] Add extra test case for _ pattern hole 2022-08-12 10:03:21 -03:00
Pavel Yaskevich
f5456bd2ac [CSGen] Adjust locators for sub-patterns of parens
In cases like `.<name>(_)`, the `_` sub-pattern should not assume
locator of the parent paren, just like it doesn't in case of tuple
i.e. `.<name>(_, ...)` where each element gets a `PatternMatch(<elt>)`
locator.
2022-08-03 17:30:06 -07:00
Pavel Yaskevich
5331e276d5 Merge pull request #41730 from xedin/se-0326-solve-pattern-bindings-via-conjunctions
[SE-0326] Re-enable multi-statement closure inference by default
2022-03-15 13:21:03 -07:00
Pavel Yaskevich
966f58f044 [Tests] NFC: Adjust all the test-cases improved by multi-statement inference 2022-03-08 01:13:44 -08:00
Holly Borla
12459cff80 [Diagnostics] Print 'any' in diagnostic arguments. 2022-03-05 14:26:45 -08:00
Pavel Yaskevich
bc54bc6bb7 Revert "[TypeChecker] SE-0326: Enable multi-statement closure inference by default" 2021-11-29 17:26:08 -08:00
Pavel Yaskevich
67d87e104f [Tests] NFC: Adjust all the test-cases improved by multi-statement inference 2021-11-15 16:42:06 -08:00
Pavel Yaskevich
2f6407db82 [TypeChecker] NFC: Add a test-case for for-each with where clause 2021-07-26 10:57:22 -07:00
jiaren wang
c5de1f0800 [SR-14824] Improve diagnostic for multi-statement closures instead of saying "too complex closure return type" 2021-06-30 14:36:38 +08:00
Anthony Latsis
792da10925 Revert "Sema: Make type resolution for EnumElementPattern less eager" 2020-08-10 16:02:28 +03:00
Frederick Kellison-Linn
eb625f7b2a [Sema] Allow inference of binding to type var of differing lvalue-ness…
when we have an optional type. This uncovered an error with unresolved member lookup where we allowed an unresolved value member constraint to fail if lookup failed in an optional type wrapping a type variable.

This resolves SR-13357.
2020-08-08 08:53:16 -04:00
Anthony Latsis
9462de1f30 Sema: Make type resolution for EnumElementPattern less eager 2020-07-31 15:26:00 +03:00
Robert Widmann
8a7a1d98f5 Teach the VarDeclUsageChecker About Variables Bound in Patterns
The VDUC was missing a class of AST nodes that can bind variables:
patterns in switch statements. For these, it was falling back to
requesting a simple replacement of the bound variable name with _. But
for patterns, this means there's a two-step dance the user has to go
through where the first fixit does this:

.pattern(let x) -> .pattern(let _)

Then a second round of compilation would emit a fixit to do this:

.pattern(let _) -> .pattern(_)

Instead, detect "simple" variable bindings - for now, variable patterns
that are immediately preceded by a `let` or `var` binding pattern - and
collapse two steps into one.

Resolves rdar://47240768
2020-07-21 12:33:14 -07:00
Pavel Yaskevich
caab4f4ead [CSGen] Handle incorrect patterns (e.g. referencing unknown types)
Currently `generateInitPatternConstraints` assumes that all
patterns have types but it's not the case for patterns that
e.g. reference unknown types or have other structural issues.

Let's fail `generateInitPatternConstraints` if constraint
generation fails.

Resolves: rdar://problem/64157451
2020-06-29 12:06:28 -07:00
Pavel Yaskevich
b0070f5739 [Diagnostics] Check whether all contextual mismatches has the same type before diagnosing ambiguity
Instead of requiring sub-classes of `ContextualMismatch` to implement
`diagnoseForAmbiguity` let's implement it directly on `ContextualMismatch`
itself and check whether all of the aggregated fixes have same types on
both sides and if so, diagnose as-if it was a single fix.
2020-06-12 11:47:04 -07:00
Robert Widmann
2371e5c260 Strip TypeLoc from EnumElementPattern 2020-06-10 14:22:46 -07:00
Pavel Yaskevich
b14d9655ca [CSGen] Allow is patterns to infer type from enclosing context
Instead of assuming type of its sub-pattern `is` should be able
to infer type from context and then propagate that to the sub-pattern
via conversion. This enables support for patterns like `.foo(_ as Foo)`
where `is` would have a type different from `_` which gets inferred
from associated value of `foo` and converted to `Foo` that becomes
a type of `_` pattern.

Resolves: rdar://problem/63510989
2020-06-03 10:26:27 -07:00
Varun Gandhi
a1716fe2a6 [Diagnostics] Update compiler diagnostics to use less jargon. (#31315)
Fixes rdar://problem/62375243.
2020-04-28 14:11:39 -07:00
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