about summary refs log tree commit diff
path: root/compiler/rustc_parse/src/errors.rs
diff options
context:
space:
mode:
authorDylan DPC <99973273+Dylan-DPC@users.noreply.github.com>2023-03-01 23:40:19 +0530
committerGitHub <noreply@github.com>2023-03-01 23:40:19 +0530
commit27fa7b5e6d2eaeba5daf6354df9de0d03cdf795c (patch)
tree5ed9ee91dfd808cf79037ba5f994114eda7af339 /compiler/rustc_parse/src/errors.rs
parent38461f8b8aa3979f5008005c049cd84c4e216ace (diff)
parent0758c05c9792700dbc482eda8cd464c39d5ebed5 (diff)
downloadrust-27fa7b5e6d2eaeba5daf6354df9de0d03cdf795c.tar.gz
rust-27fa7b5e6d2eaeba5daf6354df9de0d03cdf795c.zip
Rollup merge of #108427 - y21:for-else-diagnostic, r=compiler-errors
Recover from for-else and while-else

This recovers from attempts at writing for-else or while-else loops, which might help users coming from e.g. Python.
```rs
for _ in 0..0 {
  // ...
} else {
  // ...
}
```
Combined with trying to store it in a let binding, the current diagnostic can be a bit confusing. It mentions let-else and suggests wrapping the loop in parentheses, which the user probably doesn't want. let-else doesn't make sense for `for` and `while` loops, as they are of type `()` (which already is an irrefutable pattern and doesn't need let-else).
<details>
<summary>Current diagnostic</summary>

```rs
error: right curly brace `}` before `else` in a `let...else` statement not allowed
 --> src/main.rs:4:5
  |
4 |     } else {
  |     ^
  |
help: wrap the expression in parentheses
  |
2 ~     let _x = (for _ in 0..0 {
3 |
4 ~     }) else {
  |
```
</details>

Some questions:
- Can the wording for the error message be improved? Would "for...else loops are not allowed" fit better?
- Should we be more "conservative" in case we want to support this in the future (i.e. say "for...else loops are **currently** not allowed/supported")?
- Is there a better way than storing a `&'static str` for the loop type? It is used for substituting the placeholder in the locale file (since it can emit either `for...else` or `while...else`). Maybe there is an enum I could use that I couldn't find
Diffstat (limited to 'compiler/rustc_parse/src/errors.rs')
-rw-r--r--compiler/rustc_parse/src/errors.rs11
1 files changed, 11 insertions, 0 deletions
diff --git a/compiler/rustc_parse/src/errors.rs b/compiler/rustc_parse/src/errors.rs
index c746a870964..1662db36d10 100644
--- a/compiler/rustc_parse/src/errors.rs
+++ b/compiler/rustc_parse/src/errors.rs
@@ -452,6 +452,17 @@ pub(crate) struct MissingExpressionInForLoop {
 }
 
 #[derive(Diagnostic)]
+#[diag(parse_loop_else)]
+#[note]
+pub(crate) struct LoopElseNotSupported {
+    #[primary_span]
+    pub span: Span,
+    pub loop_kind: &'static str,
+    #[label(parse_loop_keyword)]
+    pub loop_kw: Span,
+}
+
+#[derive(Diagnostic)]
 #[diag(parse_missing_comma_after_match_arm)]
 pub(crate) struct MissingCommaAfterMatchArm {
     #[primary_span]