Commit Graph

79 Commits

Author SHA1 Message Date
Hamish Knight
84847bcd06 [Sema] Relax a check in VarDeclUsageChecker
We don't want to just check the first pattern, we're interested in
the first pattern that binds the given variable. That can be determined
by checking if it's canonical or not.
2025-09-09 13:48:40 +01:00
Greg Titus
2b0fa1ca05 Add diagnostic for extraneous case keyword when multiple patterns. 2024-05-31 17:42:03 -07:00
Nishith Shah
8e2e625543 [Diagnostics] Use imperative msg for protocol conformance & switch-case fixits
This commit changes fixit messages from a question/suggestion to an
imperative message for protocol conformances and switch-case. Addresses
https://github.com/apple/swift/issues/67510.
2023-08-13 22:34:26 -07:00
Luciano Almeida
22a18de1b1 [Sema] Improving integer literal as boolean diagnostic 2023-02-21 10:30:48 -03:00
Stephen Canon
33d178cf60 Merge pull request #59623 from rxwei/cherry-42611 (#61793)
* Merge pull request #59623 from rxwei/cherry-42611

* Fixup switch.swift test from bad merge.

Co-authored-by: Richard Wei <rxrwei@gmail.com>
2022-11-02 14:02:16 -04:00
Alex Hoppen
e14fa7291f [CS] Don’t fail constraint generation for ErrorExpr or if type fails to resolve
Instead of failing constraint generation by returning `nullptr` for an `ErrorExpr` or returning a null type when a type fails to be resolved, return a fresh type variable. This allows the constraint solver to continue further and produce more meaningful diagnostics.

Most importantly, it allows us to produce a solution where previously constraint generation for a syntactic element had failed, which is required to type check multi-statement closures in result builders inside the constraint system.
2022-07-20 09:46:12 +02:00
Hamish Knight
c33f363956 [test] Update Regex type for flattened captures 2022-07-06 23:01:22 +01:00
Anthony Latsis
74ee6b5d63 Add regression test to close #43334 2022-06-28 22:36:14 +03:00
Richard Wei
94e8f5393e Enable string processing by default.
Make frontend flag `-enable-experimental-string-processing` default to true.
2022-06-12 20:25:16 -07:00
Rintaro Ishizaki
eade9b7bc9 [LookupVisibleDecls] Implement shadowing for unqualified lookups
Tweaked usable check:
  * Local type/func decls are usable even before declaration
  * Outer nominal Instance member are not usable
  * Type context cannot close over values in outer type contexts

Added shadowing rule by the base name:
  * Type members don't shadow each other as long as they are in the
    same type context.
  * Local values shadow everything in outer scope
    * Except that 'func' decl doesn't shadow 'var' decl if they are in the
      same scope.

rdar://86285396
2022-04-28 16:36:54 -07:00
Alex Hoppen
bfc68f48e4 [Parser] When recovering from expression parsing don't stop at '{'
When recovering from a parser error in an expression, we resumed parsing at a '{'. I assume this was because we wanted to continue inside e.g. an if-body if parsing the condition failed, but it's actually causing more issue because when parsing e.g.

```swift
expr + has - error +

functionTakesClosure {
}
```

we continue parsing at the `{` of the trailing closure, which is a completely garbage location to continue parsing.

The motivating example for this change was (in a result builder)
```swift
Text("\(island.#^COMPLETE^#)")
takeTrailingClosure {}
```

Here `Text(…)` has an error (because it contains a code completion token) and thus we skip `takeTrailingClosure`, effectively parsing
```swift
Text(….) {}
```

which the type checker wasn’t very happy with and thus refused to provide code completion. With this change, we completely drop `takeTrailingClosure {}`. The type checker is a lot happier with that.
2022-04-07 09:19:22 +02:00
ZigiiWong
efb0639075 Improve diagnostic error message for empty cases 2021-07-15 02:03:45 +08:00
Alex Hoppen
931f3394d7 [Parse] Create SwitchStmt nodes for switch statements with errors
At the moment, if there is an error in the `switch` statement expression or if the `{` is missing, we return `nullptr` from `parseStmtSwitch`, but we consume tokens while trying to parse the `switch` statement. This causes the AST to not contain any nodes for the tokens that were consumed while trying to parse the `switch` statement.

While this doesn’t cause any issues during compilation (compiling fails anyway so not having the `switch` statement in the AST is not a problem) this causes issues when trying to complete inside an expression that was consumed while trying to parse the `switch` statement but doesn’t have a representation in the AST. The solver-based completion approach can’t find the expression that contains the completion token (because it’s not part of the AST) and thus return empty results.

To fix this, make sure we are always creating a `SwitchStmt` when consuming tokens for it.

Previously, one could always assume that a `SwitchStmt` had a valid `LBraceLoc` and `RBraceLoc`. This is no longer the case because of the recovery. In order to form the `SwitchStmt`’s `SourceRange`, I needed to add a `EndLoc` property to `SwitchStmt` that keeps track of the last token in the `SwitchStmt`. Theoretically we should be able to compute this location by traversing the right brace, case stmts, subject expression, … in reverse order until we find something that’s not missing. But if the `SubjectExpr` is an `ErrorExpr`, representing a missing expression, it might have a source range that points to one after the last token in the statement (this is due to the way the `ErrorExpr` is being constructed), therefore returning an invalid range. So overall I thought it was easier and safer to add another property.

Fixes rdar://76688441 [SR-14490]
2021-04-15 18:37:25 +02:00
Slava Pestov
5808d9beb9 Parse: Remove parse-time name lookup 2020-11-16 22:39:44 -05:00
Slava Pestov
bd36100cb3 Update tests in preparation for disabling parser lookup
I created a second copy of each test where the output changes
after disabling parser lookup. The primary copy now explicitly
calls the frontend with -disable-parser-lookup and expects the
new diagnostics; the *_parser_lookup.swift version calls the
frontend with -enable-parser-lookup and has the old expectations.

This allows us to turn parser lookup on and off by default
without disturbing tests. Once parser lookup is completely
removed we can remove the *_parser_lookup.swift variants.
2020-10-03 09:37:55 -04: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
9067ed23ca [ConstraintSystem] Specialize diagnostic for ~= to talk about expression pattern use 2020-06-12 11:47:04 -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
Owen Voorhees
166555c34f [Diagnostics] Better diagnostic for integer used as a boolean condition 2020-02-03 21:20:41 -08:00
Pavel Yaskevich
72b61f55bf [Diagnostics] Tailored diagnostic for "condition" expression
Since all condition expressions supposed to be convertible
to `Bool`, let's use that type as contextual and produce a
tailored diagnostic.
2019-09-20 12:37:35 -07:00
Jordan Rose
003850fb0d [Parse] Treat '@unknown' as the start of a statement (#22974)
...allowing a plain 'return' to work in a switch in a Void-returning
function.

https://bugs.swift.org/browse/SR-9920
2019-03-01 08:31:11 -08:00
Parker Schuh
b12fcb50db IntegerLiteralExpr now is lowered directly into SIL.
For context, String, Nil, and Bool already behave this way.

Note: Before it used to construct (call, ... (integer_literal)), and the
call would be made explicit / implicit based on if you did eg: Int(3) or
just 3. This however did not translate to the new world so this PR adds
a IsExplicitConversion bit to NumberLiteralExpr. Some side results of
all this are that some warnings changed a little and some instructions are
emitted in a different order.
2019-02-14 11:54:16 -08: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
Jordan Rose
8157e80217 Limit exhaustivity checking when weird things happen with '@unknown'
If someone uses it twice, or on a non-final case, or tries to use it
with a multiple-pattern case, don't bother checking the exhaustiveness
of the switch. (For other violations, the pattern or where-clause is
ignored.)

https://bugs.swift.org/browse/SR-7409
2018-04-12 20:31:47 -07:00
Jordan Rose
a9f26ab893 Don't crash when using @unknown default with a non-enum type.
Also improve the error message when using it with a very large space.

https://bugs.swift.org/browse/SR-7408
2018-04-11 19:28:39 -07:00
Rintaro Ishizaki
07fd8b8a4b [Parse] Handle edge case of '@unknown' for switch case
* Previously, hit assertion if '@unknown' has argument clause
* Diagnose multiple '@unknown' for single 'case'
2018-04-12 01:27:40 +09:00
Jordan Rose
6d30272bfd Merge pull request #14382 from jrose-apple/unknown-case
Implementation for `@unknown default`
2018-04-10 11:19:53 -07:00
John McCall
7815892a76 Add unique typo corrections to the main diagnostic with a fix-it.
Continue to emit notes for the candidates, but use different text.
Note that we can emit a typo correction fix-it even if there are
multiple candidates with the same name.

Also, disable typo correction in the migrator, since the operation
is quite expensive, the notes are never presented to the user, and
the fix-its can interfere with the migrator's own edits.

Our general guidance is that fix-its should be added on the main
diagnostic only when the fix-it is highly likely to be correct.
The exact threshold is debateable.  Typo correction is certainly
capable of making mistakes, but most of its edits are right, and
when it's wrong it's usually obviously wrong.  On balance, I think
this is the right thing to do.  For what it's worth, it's also
what we do in Clang.
2018-04-07 16:01:39 -04:00
Jordan Rose
1f14d03c53 Enforce restrictions on '@unknown'
- Must be a single pattern
- Must be last in the switch
- Must not have a 'where' clause
- Must specifically be the "any" pattern if using 'case'

We may lift some of these restrictions in the future, but that would
need a new proposal.
2018-04-05 17:38:06 -07:00
Jordan Rose
bdb8388721 Allow '@unknown' to match any enums not explicitly marked frozen
If a client wants to defend themselves against new cases in libraries
they use, or even in their own code, they're allowed to.
2018-04-05 16:35:15 -07:00
Jordan Rose
054658b316 Downgrade exhaustivity errors to warnings if '@unknown' is present
The other half of '@unknown' in Sema. Again, the diagnostics here
could be improved; rather than a generic "switch must be exhaustive",
it could say something about unknown case handling known cases.

One interesting detail here: '@unknown' is only supposed to match
/fully/ missing cases. If a case is /partly/ accounted for, not
handling the rest is still an error, even if an unknown case is
present.

This only works with switches over single enum values, not values that
contain an enum with unknown cases. That's coming in a later commit.
(It was easier to get this part working first.)
2018-04-05 16:35:14 -07:00
Jordan Rose
701975ad1d Add parsing support for @unknown (SE-0192)
This is our first statement attribute, made more complicated by the
fact that a 'case'/'default' isn't really a normal statement. I've
chosen /not/ to implement a general statement attribute logic like we
have for types and decls at this time, but I did get the compiler
parsing arbitrary attributes before 'case' and 'default'. As a bonus,
we now treat all cases within functions as being switch-like rather
than enum-like, which is better for recovery when not in a switch.
2018-04-05 16:35:14 -07:00
gregomni
ad0ad9f709 Check for let vs var bindings of the same variable name in multiple case patterns. 2018-03-29 23:41:55 -07:00
gregomni
0c3c0fd59b Support for fallthrough into cases with pattern variables. 2018-01-20 11:10:00 -08:00
Xi Ge
2d4d9eb202 update test. 2017-05-02 14:55:04 -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
Xi Ge
b4cf37bf7d Sema: several improvements on missing switch cases diagnostics. (#8026)
1. Make sure the actions taken by fixits are reflected in diagnostics messages.
2. Issue missing cases diagnostics at the start of the switch statement instead of its end.
3. Use <#code#> instead of <#Code#> in the stub.
2017-03-10 19:32:37 -08: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
Xi Ge
daac020c61 Sema: Reject empty switch statements during type checking so that we can issue fixits to fill the unhandled switch cases. (#7766) 2017-02-25 08:01:13 -08:00
Jacob Bandes-Storch
c98e515734 [QoI] Improvements to function call & closure diagnostics (#7224) 2017-02-07 17:36:11 -08:00
Brian King
0c57aebfea Fix unit tests 2017-01-26 10:04:41 -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
Rintaro Ishizaki
4079d7ed99 [Sema][SR-720] Fallback to ExprPattern if enum element not found for UnresolvedDotExpr
So that the pattern can refer arbitrary static member in enum type.
2016-07-26 17:11:00 +09:00
Michael Gottesman
a047bb7564 Revert "Fix the build."
This reverts commit dc24c2bd34.

Turns out Chris fixed the build but when I was looking at the bots, his fix had
not been tested yet, so I thought the tree was still red and was trying to
revert to green.
2016-07-17 16:29:18 -07:00
Michael Gottesman
dc24c2bd34 Fix the build.
This reverts commit b4cba58330.
This reverts commit a602927c75.
This reverts commit 55fbe5a763.
2016-07-17 16:17:15 -07:00
Chris Lattner
55fbe5a763 Remove Boolean as a special, privileged type used by Sema, and instead
use the concrete Bool type.  This eliminates a bunch of complexity and
makes diagnostics more concrete.
2016-07-17 15:14:24 -07:00
John McCall
3fc2291733 Add basic typo correction for unqualified lookup.
There's a lot of room for better QoI / performance here.
2016-05-20 11:04:58 -07:00
Max Moiseev
a49dab6bf8 Merge remote-tracking branch 'origin/master' into swift-3-api-guidelines 2016-02-29 12:08:52 -08:00
gregomni
63f810d2fd Variables in 'case' labels with multiple patterns.
Parser now accepts multiple patterns in switch cases that contain variables.
Every pattern must contain the same variable names, but can be in arbitrary
positions. New error for variable that doesn't exist in all patterns.

Sema now checks cases with multiple patterns that each occurence of a variable
name is bound to the same type. New error for unexpected types.

SILGen now shares basic blocks for switch cases that contain multiple
patterns. That BB takes incoming arguments from each applicable pattern match
emission with the specific var decls for the pattern that matched.

Added tests for all three of these, and some simple IDE completion
sanity tests.
2016-02-24 15:46:36 -08:00