about summary refs log tree commit diff
path: root/compiler/rustc_parse/src/errors.rs
diff options
context:
space:
mode:
authorMatthias Krüger <476013+matthiaskrgr@users.noreply.github.com>2025-05-16 07:19:41 +0200
committerGitHub <noreply@github.com>2025-05-16 07:19:41 +0200
commite53b9f8fdd7be3357063cc82abe9a12f9014c13f (patch)
treebdbd8bf36002dce59088cb2ee0134c2de9186048 /compiler/rustc_parse/src/errors.rs
parent953905fd9e567679e868c50a734debc872815f81 (diff)
parent1267333ef102d854cf0cefef877ba0d9adb07107 (diff)
downloadrust-e53b9f8fdd7be3357063cc82abe9a12f9014c13f.tar.gz
rust-e53b9f8fdd7be3357063cc82abe9a12f9014c13f.zip
Rollup merge of #141003 - clubby789:ternary-improve, r=compiler-errors
Improve ternary operator recovery

This
- Improves the span of the error to not point at the next token
- Where possible, we use the span of the condition to further improve the span of the error to include the cond, and suggest a maybe-incorrect fix

Currently this works on free expressions, not let statements; some more refactoring would be needed to pass the span down, which I'm not sure is worth doing.

### Old
![image](https://github.com/user-attachments/assets/5688cefc-e4ef-4135-a5ba-340ce05ae6f3)

### New
![image](https://github.com/user-attachments/assets/154f5380-e0c8-42c7-9bf8-0adb3d0433fa)
Diffstat (limited to 'compiler/rustc_parse/src/errors.rs')
-rw-r--r--compiler/rustc_parse/src/errors.rs20
1 files changed, 19 insertions, 1 deletions
diff --git a/compiler/rustc_parse/src/errors.rs b/compiler/rustc_parse/src/errors.rs
index 766baf6f80c..31a48b22cfe 100644
--- a/compiler/rustc_parse/src/errors.rs
+++ b/compiler/rustc_parse/src/errors.rs
@@ -436,10 +436,28 @@ pub(crate) enum IfExpressionMissingThenBlockSub {
 
 #[derive(Diagnostic)]
 #[diag(parse_ternary_operator)]
-#[help]
 pub(crate) struct TernaryOperator {
     #[primary_span]
     pub span: Span,
+    /// If we have a span for the condition expression, suggest the if/else
+    #[subdiagnostic]
+    pub sugg: Option<TernaryOperatorSuggestion>,
+    /// Otherwise, just print the suggestion message
+    #[help(parse_use_if_else)]
+    pub no_sugg: bool,
+}
+
+#[derive(Subdiagnostic, Copy, Clone)]
+#[multipart_suggestion(parse_use_if_else, applicability = "maybe-incorrect", style = "verbose")]
+pub(crate) struct TernaryOperatorSuggestion {
+    #[suggestion_part(code = "if ")]
+    pub before_cond: Span,
+    #[suggestion_part(code = "{{")]
+    pub question: Span,
+    #[suggestion_part(code = "}} else {{")]
+    pub colon: Span,
+    #[suggestion_part(code = " }}")]
+    pub end: Span,
 }
 
 #[derive(Subdiagnostic)]