From 16481807f5b106a6dcc627075fbdcd14add9495d Mon Sep 17 00:00:00 2001 From: Catherine Flores Date: Tue, 25 Jul 2023 18:27:24 +0000 Subject: [PATCH 1/3] Gracefully handle missing ternary operator --- compiler/rustc_parse/messages.ftl | 4 + compiler/rustc_parse/src/errors.rs | 8 ++ .../rustc_parse/src/parser/diagnostics.rs | 46 ++++++- compiler/rustc_parse/src/parser/mod.rs | 9 +- compiler/rustc_parse/src/parser/stmt.rs | 4 +- tests/ui/parser/ternary_operator.rs | 40 +++++++ tests/ui/parser/ternary_operator.stderr | 113 ++++++++++++++++++ 7 files changed, 220 insertions(+), 4 deletions(-) create mode 100644 tests/ui/parser/ternary_operator.rs create mode 100644 tests/ui/parser/ternary_operator.stderr diff --git a/compiler/rustc_parse/messages.ftl b/compiler/rustc_parse/messages.ftl index 9787d98c1a4..86e41253b29 100644 --- a/compiler/rustc_parse/messages.ftl +++ b/compiler/rustc_parse/messages.ftl @@ -722,6 +722,10 @@ parse_sugg_wrap_pattern_in_parens = wrap the pattern in parentheses parse_switch_mut_let_order = switch the order of `mut` and `let` + +parse_ternary_operator = Rust has no ternary operator + .help = use an `if-else` expression instead + parse_tilde_const_lifetime = `~const` may only modify trait bounds, not lifetime bounds parse_tilde_is_not_unary_operator = `~` cannot be used as a unary operator diff --git a/compiler/rustc_parse/src/errors.rs b/compiler/rustc_parse/src/errors.rs index 96e1c0e3c6d..903b0e07876 100644 --- a/compiler/rustc_parse/src/errors.rs +++ b/compiler/rustc_parse/src/errors.rs @@ -365,6 +365,14 @@ pub(crate) enum IfExpressionMissingThenBlockSub { AddThenBlock(#[primary_span] Span), } +#[derive(Diagnostic)] +#[diag(parse_ternary_operator)] +#[help] +pub struct TernaryOperator { + #[primary_span] + pub span: Span, +} + #[derive(Subdiagnostic)] #[suggestion(parse_extra_if_in_let_else, applicability = "maybe-incorrect", code = "")] pub(crate) struct IfExpressionLetSomeSub { diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index c3cf6437afa..8f422d90175 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -14,7 +14,7 @@ use crate::errors::{ PatternMethodParamWithoutBody, QuestionMarkInType, QuestionMarkInTypeSugg, SelfParamNotFirst, StructLiteralBodyWithoutPath, StructLiteralBodyWithoutPathSugg, StructLiteralNeedingParens, StructLiteralNeedingParensSugg, SuggAddMissingLetStmt, SuggEscapeIdentifier, SuggRemoveComma, - UnexpectedConstInGenericParam, UnexpectedConstParamDeclaration, + TernaryOperator, UnexpectedConstInGenericParam, UnexpectedConstParamDeclaration, UnexpectedConstParamDeclarationSugg, UnmatchedAngleBrackets, UseEqInstead, }; @@ -500,6 +500,13 @@ impl<'a> Parser<'a> { // Special-case "expected `;`" errors if expected.contains(&TokenType::Token(token::Semi)) { + if self.prev_token.kind == token::Question { + self.maybe_ternary_lo = Some(self.prev_token.span.lo()); + let result = self.maybe_recover_from_ternary_operator().map(|_| true); + self.maybe_ternary_lo = None; + return result; + } + if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP { // Likely inside a macro, can't provide meaningful suggestions. } else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) { @@ -1330,6 +1337,41 @@ impl<'a> Parser<'a> { } } + /// Rust has no ternary operator (`cond ? then : else`). Parse it and try + /// to recover from it if `then` and `else` are valid expressions. + pub(super) fn maybe_recover_from_ternary_operator(&mut self) -> PResult<'a, ()> { + let snapshot = self.create_snapshot_for_diagnostic(); + let lo = self.prev_token.span.lo(); + + if self.prev_token == token::Question + && match self.parse_expr() { + Ok(_) => true, + Err(err) => { + err.cancel(); + // The colon can sometimes be mistaken for type + // ascription. Catch when this happens and continue. + self.token == token::Colon + } + } + { + if self.eat_noexpect(&token::Colon) { + match self.parse_expr() { + Ok(_) => { + self.sess.emit_err(TernaryOperator { span: self.token.span.with_lo(lo) }); + } + Err(err) => { + err.cancel(); + self.restore_snapshot(snapshot); + } + }; + } + } else { + self.restore_snapshot(snapshot); + }; + + Ok(()) + } + pub(super) fn maybe_recover_from_bad_type_plus(&mut self, ty: &Ty) -> PResult<'a, ()> { // Do not add `+` to expected tokens. if !self.token.is_like_plus() { @@ -2111,7 +2153,7 @@ impl<'a> Parser<'a> { } _ => ( self.token.span, - format!("expected expression, found {}", super::token_descr(&self.token),), + format!("expected expression, found {}", super::token_descr(&self.token)), ), }; let mut err = self.struct_span_err(span, msg); diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index 2e1a61e634e..20515b36fa1 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -37,6 +37,7 @@ use rustc_errors::{ use rustc_session::parse::ParseSess; use rustc_span::source_map::{Span, DUMMY_SP}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; +use rustc_span::BytePos; use std::ops::Range; use std::{cmp, mem, slice}; use thin_vec::ThinVec; @@ -157,12 +158,17 @@ pub struct Parser<'a> { /// Whether the parser is allowed to do recovery. /// This is disabled when parsing macro arguments, see #103534 pub recovery: Recovery, + /// The low part of a ternary operator (`cond ? then : else`). + /// FIXME(Centri3): This is currently only used so that type ascription is + /// not mentioned in the error. Once the error in `stmt.rs` is removed, this + /// can be removed. + maybe_ternary_lo: Option, } // This type is used a lot, e.g. it's cloned when matching many declarative macro rules with nonterminals. Make sure // it doesn't unintentionally get bigger. #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] -rustc_data_structures::static_assert_size!(Parser<'_>, 272); +rustc_data_structures::static_assert_size!(Parser<'_>, 280); /// Stores span information about a closure. #[derive(Clone)] @@ -475,6 +481,7 @@ impl<'a> Parser<'a> { }, current_closure: None, recovery: Recovery::Allowed, + maybe_ternary_lo: None, }; // Make parser point to the first token. diff --git a/compiler/rustc_parse/src/parser/stmt.rs b/compiler/rustc_parse/src/parser/stmt.rs index 9fcf51a04ec..5a7f3aa53dc 100644 --- a/compiler/rustc_parse/src/parser/stmt.rs +++ b/compiler/rustc_parse/src/parser/stmt.rs @@ -576,7 +576,9 @@ impl<'a> Parser<'a> { Applicability::MaybeIncorrect, ); } - if self.sess.unstable_features.is_nightly_build() { + if self.sess.unstable_features.is_nightly_build() + && self.maybe_ternary_lo.is_none() + { // FIXME(Nilstrieb): Remove this again after a few months. err.note("type ascription syntax has been removed, see issue #101728 "); } diff --git a/tests/ui/parser/ternary_operator.rs b/tests/ui/parser/ternary_operator.rs new file mode 100644 index 00000000000..c41a20f481f --- /dev/null +++ b/tests/ui/parser/ternary_operator.rs @@ -0,0 +1,40 @@ +fn a() { + let x = 5 > 2 ? true : false; + //~^ ERROR Rust has no ternary operator + //~| HELP use an `if-else` expression instead + //~| ERROR the `?` operator can only be applied to values that implement `Try` [E0277] + //~| HELP the trait `Try` is not implemented for `{integer}` + //~| ERROR the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) [E0277] + //~| HELP the trait `FromResidual<_>` is not implemented for `()` +} + +fn b() { + let x = 5 > 2 ? { true } : { false }; + //~^ ERROR Rust has no ternary operator + //~| HELP use an `if-else` expression instead + //~| ERROR the `?` operator can only be applied to values that implement `Try` [E0277] + //~| HELP the trait `Try` is not implemented for `{integer}` + //~| ERROR the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) [E0277] + //~| HELP the trait `FromResidual<_>` is not implemented for `()` +} + +fn c() { + let x = 5 > 2 ? f32::MAX : f32::MIN; + //~^ ERROR Rust has no ternary operator + //~| HELP use an `if-else` expression instead + //~| ERROR the `?` operator can only be applied to values that implement `Try` [E0277] + //~| HELP the trait `Try` is not implemented for `{integer}` + //~| ERROR the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) [E0277] + //~| HELP the trait `FromResidual<_>` is not implemented for `()` +} + +fn main() { + let x = 5 > 2 ? { let x = vec![]: Vec; x } : { false }; + //~^ ERROR Rust has no ternary operator + //~| HELP use an `if-else` expression instead + //~| expected one of `.`, `;`, `?`, `else`, or an operator, found `:` + //~| ERROR the `?` operator can only be applied to values that implement `Try` [E0277] + //~| HELP the trait `Try` is not implemented for `{integer}` + //~| ERROR the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) [E0277] + //~| HELP the trait `FromResidual<_>` is not implemented for `()` +} diff --git a/tests/ui/parser/ternary_operator.stderr b/tests/ui/parser/ternary_operator.stderr new file mode 100644 index 00000000000..bf08666c8a4 --- /dev/null +++ b/tests/ui/parser/ternary_operator.stderr @@ -0,0 +1,113 @@ +error: Rust has no ternary operator + --> $DIR/ternary_operator.rs:2:19 + | +LL | let x = 5 > 2 ? true : false; + | ^^^^^^^^^^^^^^^ + | + = help: use an `if-else` expression instead + +error: Rust has no ternary operator + --> $DIR/ternary_operator.rs:12:19 + | +LL | let x = 5 > 2 ? { true } : { false }; + | ^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: use an `if-else` expression instead + +error: Rust has no ternary operator + --> $DIR/ternary_operator.rs:22:19 + | +LL | let x = 5 > 2 ? f32::MAX : f32::MIN; + | ^^^^^^^^^^^^^^^^^^^^^^ + | + = help: use an `if-else` expression instead + +error: expected one of `.`, `;`, `?`, `else`, or an operator, found `:` + --> $DIR/ternary_operator.rs:32:37 + | +LL | let x = 5 > 2 ? { let x = vec![]: Vec; x } : { false }; + | ^ expected one of `.`, `;`, `?`, `else`, or an operator + +error: Rust has no ternary operator + --> $DIR/ternary_operator.rs:32:19 + | +LL | let x = 5 > 2 ? { let x = vec![]: Vec; x } : { false }; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: use an `if-else` expression instead + +error[E0277]: the `?` operator can only be applied to values that implement `Try` + --> $DIR/ternary_operator.rs:2:17 + | +LL | let x = 5 > 2 ? true : false; + | ^^^ the `?` operator cannot be applied to type `{integer}` + | + = help: the trait `Try` is not implemented for `{integer}` + +error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) + --> $DIR/ternary_operator.rs:2:19 + | +LL | fn a() { + | ------ this function should return `Result` or `Option` to accept `?` +LL | let x = 5 > 2 ? true : false; + | ^ cannot use the `?` operator in a function that returns `()` + | + = help: the trait `FromResidual<_>` is not implemented for `()` + +error[E0277]: the `?` operator can only be applied to values that implement `Try` + --> $DIR/ternary_operator.rs:12:17 + | +LL | let x = 5 > 2 ? { true } : { false }; + | ^^^ the `?` operator cannot be applied to type `{integer}` + | + = help: the trait `Try` is not implemented for `{integer}` + +error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) + --> $DIR/ternary_operator.rs:12:19 + | +LL | fn b() { + | ------ this function should return `Result` or `Option` to accept `?` +LL | let x = 5 > 2 ? { true } : { false }; + | ^ cannot use the `?` operator in a function that returns `()` + | + = help: the trait `FromResidual<_>` is not implemented for `()` + +error[E0277]: the `?` operator can only be applied to values that implement `Try` + --> $DIR/ternary_operator.rs:22:17 + | +LL | let x = 5 > 2 ? f32::MAX : f32::MIN; + | ^^^ the `?` operator cannot be applied to type `{integer}` + | + = help: the trait `Try` is not implemented for `{integer}` + +error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) + --> $DIR/ternary_operator.rs:22:19 + | +LL | fn c() { + | ------ this function should return `Result` or `Option` to accept `?` +LL | let x = 5 > 2 ? f32::MAX : f32::MIN; + | ^ cannot use the `?` operator in a function that returns `()` + | + = help: the trait `FromResidual<_>` is not implemented for `()` + +error[E0277]: the `?` operator can only be applied to values that implement `Try` + --> $DIR/ternary_operator.rs:32:17 + | +LL | let x = 5 > 2 ? { let x = vec![]: Vec; x } : { false }; + | ^^^ the `?` operator cannot be applied to type `{integer}` + | + = help: the trait `Try` is not implemented for `{integer}` + +error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) + --> $DIR/ternary_operator.rs:32:19 + | +LL | fn main() { + | --------- this function should return `Result` or `Option` to accept `?` +LL | let x = 5 > 2 ? { let x = vec![]: Vec; x } : { false }; + | ^ cannot use the `?` operator in a function that returns `()` + | + = help: the trait `FromResidual<_>` is not implemented for `()` + +error: aborting due to 13 previous errors + +For more information about this error, try `rustc --explain E0277`. From faa73953c07530bc02c9a89e4d719beb3f4a376e Mon Sep 17 00:00:00 2001 From: Catherine Flores Date: Tue, 25 Jul 2023 18:37:56 +0000 Subject: [PATCH 2/3] Remove unnecessary `maybe_ternary_lo` field --- .../rustc_parse/src/parser/diagnostics.rs | 10 ++--- compiler/rustc_parse/src/parser/mod.rs | 9 +--- compiler/rustc_parse/src/parser/stmt.rs | 4 +- tests/ui/parser/ternary_operator.rs | 41 ++++++++++++++++--- tests/ui/parser/ternary_operator.stderr | 28 +++++++------ 5 files changed, 55 insertions(+), 37 deletions(-) diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 8f422d90175..ef5581e1efe 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -501,10 +501,8 @@ impl<'a> Parser<'a> { // Special-case "expected `;`" errors if expected.contains(&TokenType::Token(token::Semi)) { if self.prev_token.kind == token::Question { - self.maybe_ternary_lo = Some(self.prev_token.span.lo()); - let result = self.maybe_recover_from_ternary_operator().map(|_| true); - self.maybe_ternary_lo = None; - return result; + self.maybe_recover_from_ternary_operator(); + return Ok(true); } if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP { @@ -1339,7 +1337,7 @@ impl<'a> Parser<'a> { /// Rust has no ternary operator (`cond ? then : else`). Parse it and try /// to recover from it if `then` and `else` are valid expressions. - pub(super) fn maybe_recover_from_ternary_operator(&mut self) -> PResult<'a, ()> { + pub(super) fn maybe_recover_from_ternary_operator(&mut self) { let snapshot = self.create_snapshot_for_diagnostic(); let lo = self.prev_token.span.lo(); @@ -1368,8 +1366,6 @@ impl<'a> Parser<'a> { } else { self.restore_snapshot(snapshot); }; - - Ok(()) } pub(super) fn maybe_recover_from_bad_type_plus(&mut self, ty: &Ty) -> PResult<'a, ()> { diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index 20515b36fa1..2e1a61e634e 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -37,7 +37,6 @@ use rustc_errors::{ use rustc_session::parse::ParseSess; use rustc_span::source_map::{Span, DUMMY_SP}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::BytePos; use std::ops::Range; use std::{cmp, mem, slice}; use thin_vec::ThinVec; @@ -158,17 +157,12 @@ pub struct Parser<'a> { /// Whether the parser is allowed to do recovery. /// This is disabled when parsing macro arguments, see #103534 pub recovery: Recovery, - /// The low part of a ternary operator (`cond ? then : else`). - /// FIXME(Centri3): This is currently only used so that type ascription is - /// not mentioned in the error. Once the error in `stmt.rs` is removed, this - /// can be removed. - maybe_ternary_lo: Option, } // This type is used a lot, e.g. it's cloned when matching many declarative macro rules with nonterminals. Make sure // it doesn't unintentionally get bigger. #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] -rustc_data_structures::static_assert_size!(Parser<'_>, 280); +rustc_data_structures::static_assert_size!(Parser<'_>, 272); /// Stores span information about a closure. #[derive(Clone)] @@ -481,7 +475,6 @@ impl<'a> Parser<'a> { }, current_closure: None, recovery: Recovery::Allowed, - maybe_ternary_lo: None, }; // Make parser point to the first token. diff --git a/compiler/rustc_parse/src/parser/stmt.rs b/compiler/rustc_parse/src/parser/stmt.rs index 5a7f3aa53dc..9fcf51a04ec 100644 --- a/compiler/rustc_parse/src/parser/stmt.rs +++ b/compiler/rustc_parse/src/parser/stmt.rs @@ -576,9 +576,7 @@ impl<'a> Parser<'a> { Applicability::MaybeIncorrect, ); } - if self.sess.unstable_features.is_nightly_build() - && self.maybe_ternary_lo.is_none() - { + if self.sess.unstable_features.is_nightly_build() { // FIXME(Nilstrieb): Remove this again after a few months. err.note("type ascription syntax has been removed, see issue #101728 "); } diff --git a/tests/ui/parser/ternary_operator.rs b/tests/ui/parser/ternary_operator.rs index c41a20f481f..23d537e77f7 100644 --- a/tests/ui/parser/ternary_operator.rs +++ b/tests/ui/parser/ternary_operator.rs @@ -1,4 +1,7 @@ -fn a() { +// A good chunk of these errors aren't shown to the user, but are still +// required in the test for it to pass. + +fn a() { //~ NOTE this function should return `Result` or `Option` to accept `?` let x = 5 > 2 ? true : false; //~^ ERROR Rust has no ternary operator //~| HELP use an `if-else` expression instead @@ -6,9 +9,15 @@ fn a() { //~| HELP the trait `Try` is not implemented for `{integer}` //~| ERROR the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) [E0277] //~| HELP the trait `FromResidual<_>` is not implemented for `()` + //~| NOTE in this expansion of desugaring of operator `?` + //~| NOTE the `?` operator cannot be applied to type `{integer}` + //~| NOTE in this expansion of desugaring of operator `?` + //~| NOTE in this expansion of desugaring of operator `?` + //~| NOTE cannot use the `?` operator in a function that returns `()` + //~| NOTE in this expansion of desugaring of operator `?` } -fn b() { +fn b() { //~ NOTE this function should return `Result` or `Option` to accept `?` let x = 5 > 2 ? { true } : { false }; //~^ ERROR Rust has no ternary operator //~| HELP use an `if-else` expression instead @@ -16,9 +25,15 @@ fn b() { //~| HELP the trait `Try` is not implemented for `{integer}` //~| ERROR the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) [E0277] //~| HELP the trait `FromResidual<_>` is not implemented for `()` + //~| NOTE in this expansion of desugaring of operator `?` + //~| NOTE the `?` operator cannot be applied to type `{integer}` + //~| NOTE in this expansion of desugaring of operator `?` + //~| NOTE in this expansion of desugaring of operator `?` + //~| NOTE cannot use the `?` operator in a function that returns `()` + //~| NOTE in this expansion of desugaring of operator `?` } -fn c() { +fn c() { //~ NOTE this function should return `Result` or `Option` to accept `?` let x = 5 > 2 ? f32::MAX : f32::MIN; //~^ ERROR Rust has no ternary operator //~| HELP use an `if-else` expression instead @@ -26,15 +41,29 @@ fn c() { //~| HELP the trait `Try` is not implemented for `{integer}` //~| ERROR the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) [E0277] //~| HELP the trait `FromResidual<_>` is not implemented for `()` + //~| NOTE in this expansion of desugaring of operator `?` + //~| NOTE the `?` operator cannot be applied to type `{integer}` + //~| NOTE in this expansion of desugaring of operator `?` + //~| NOTE in this expansion of desugaring of operator `?` + //~| NOTE cannot use the `?` operator in a function that returns `()` + //~| NOTE in this expansion of desugaring of operator `?` } -fn main() { +fn main() { //~ NOTE this function should return `Result` or `Option` to accept `?` let x = 5 > 2 ? { let x = vec![]: Vec; x } : { false }; //~^ ERROR Rust has no ternary operator //~| HELP use an `if-else` expression instead - //~| expected one of `.`, `;`, `?`, `else`, or an operator, found `:` - //~| ERROR the `?` operator can only be applied to values that implement `Try` [E0277] + //~| ERROR expected one of `.`, `;`, `?`, `else`, or an operator, found `:` + //~| NOTE expected one of `.`, `;`, `?`, `else`, or an operator + //~| ERROR the `?` operator can only be applied to values that implement `Try` [E0277] //~| HELP the trait `Try` is not implemented for `{integer}` //~| ERROR the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) [E0277] //~| HELP the trait `FromResidual<_>` is not implemented for `()` + //~| NOTE type ascription syntax has been removed, see issue #101728 + //~| NOTE in this expansion of desugaring of operator `?` + //~| NOTE the `?` operator cannot be applied to type `{integer}` + //~| NOTE in this expansion of desugaring of operator `?` + //~| NOTE in this expansion of desugaring of operator `?` + //~| NOTE cannot use the `?` operator in a function that returns `()` + //~| NOTE in this expansion of desugaring of operator `?` } diff --git a/tests/ui/parser/ternary_operator.stderr b/tests/ui/parser/ternary_operator.stderr index bf08666c8a4..af9565bbead 100644 --- a/tests/ui/parser/ternary_operator.stderr +++ b/tests/ui/parser/ternary_operator.stderr @@ -1,5 +1,5 @@ error: Rust has no ternary operator - --> $DIR/ternary_operator.rs:2:19 + --> $DIR/ternary_operator.rs:5:19 | LL | let x = 5 > 2 ? true : false; | ^^^^^^^^^^^^^^^ @@ -7,7 +7,7 @@ LL | let x = 5 > 2 ? true : false; = help: use an `if-else` expression instead error: Rust has no ternary operator - --> $DIR/ternary_operator.rs:12:19 + --> $DIR/ternary_operator.rs:21:19 | LL | let x = 5 > 2 ? { true } : { false }; | ^^^^^^^^^^^^^^^^^^^^^^^ @@ -15,7 +15,7 @@ LL | let x = 5 > 2 ? { true } : { false }; = help: use an `if-else` expression instead error: Rust has no ternary operator - --> $DIR/ternary_operator.rs:22:19 + --> $DIR/ternary_operator.rs:37:19 | LL | let x = 5 > 2 ? f32::MAX : f32::MIN; | ^^^^^^^^^^^^^^^^^^^^^^ @@ -23,13 +23,15 @@ LL | let x = 5 > 2 ? f32::MAX : f32::MIN; = help: use an `if-else` expression instead error: expected one of `.`, `;`, `?`, `else`, or an operator, found `:` - --> $DIR/ternary_operator.rs:32:37 + --> $DIR/ternary_operator.rs:53:37 | LL | let x = 5 > 2 ? { let x = vec![]: Vec; x } : { false }; | ^ expected one of `.`, `;`, `?`, `else`, or an operator + | + = note: type ascription syntax has been removed, see issue #101728 error: Rust has no ternary operator - --> $DIR/ternary_operator.rs:32:19 + --> $DIR/ternary_operator.rs:53:19 | LL | let x = 5 > 2 ? { let x = vec![]: Vec; x } : { false }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -37,7 +39,7 @@ LL | let x = 5 > 2 ? { let x = vec![]: Vec; x } : { false }; = help: use an `if-else` expression instead error[E0277]: the `?` operator can only be applied to values that implement `Try` - --> $DIR/ternary_operator.rs:2:17 + --> $DIR/ternary_operator.rs:5:17 | LL | let x = 5 > 2 ? true : false; | ^^^ the `?` operator cannot be applied to type `{integer}` @@ -45,7 +47,7 @@ LL | let x = 5 > 2 ? true : false; = help: the trait `Try` is not implemented for `{integer}` error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) - --> $DIR/ternary_operator.rs:2:19 + --> $DIR/ternary_operator.rs:5:19 | LL | fn a() { | ------ this function should return `Result` or `Option` to accept `?` @@ -55,7 +57,7 @@ LL | let x = 5 > 2 ? true : false; = help: the trait `FromResidual<_>` is not implemented for `()` error[E0277]: the `?` operator can only be applied to values that implement `Try` - --> $DIR/ternary_operator.rs:12:17 + --> $DIR/ternary_operator.rs:21:17 | LL | let x = 5 > 2 ? { true } : { false }; | ^^^ the `?` operator cannot be applied to type `{integer}` @@ -63,7 +65,7 @@ LL | let x = 5 > 2 ? { true } : { false }; = help: the trait `Try` is not implemented for `{integer}` error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) - --> $DIR/ternary_operator.rs:12:19 + --> $DIR/ternary_operator.rs:21:19 | LL | fn b() { | ------ this function should return `Result` or `Option` to accept `?` @@ -73,7 +75,7 @@ LL | let x = 5 > 2 ? { true } : { false }; = help: the trait `FromResidual<_>` is not implemented for `()` error[E0277]: the `?` operator can only be applied to values that implement `Try` - --> $DIR/ternary_operator.rs:22:17 + --> $DIR/ternary_operator.rs:37:17 | LL | let x = 5 > 2 ? f32::MAX : f32::MIN; | ^^^ the `?` operator cannot be applied to type `{integer}` @@ -81,7 +83,7 @@ LL | let x = 5 > 2 ? f32::MAX : f32::MIN; = help: the trait `Try` is not implemented for `{integer}` error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) - --> $DIR/ternary_operator.rs:22:19 + --> $DIR/ternary_operator.rs:37:19 | LL | fn c() { | ------ this function should return `Result` or `Option` to accept `?` @@ -91,7 +93,7 @@ LL | let x = 5 > 2 ? f32::MAX : f32::MIN; = help: the trait `FromResidual<_>` is not implemented for `()` error[E0277]: the `?` operator can only be applied to values that implement `Try` - --> $DIR/ternary_operator.rs:32:17 + --> $DIR/ternary_operator.rs:53:17 | LL | let x = 5 > 2 ? { let x = vec![]: Vec; x } : { false }; | ^^^ the `?` operator cannot be applied to type `{integer}` @@ -99,7 +101,7 @@ LL | let x = 5 > 2 ? { let x = vec![]: Vec; x } : { false }; = help: the trait `Try` is not implemented for `{integer}` error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) - --> $DIR/ternary_operator.rs:32:19 + --> $DIR/ternary_operator.rs:53:19 | LL | fn main() { | --------- this function should return `Result` or `Option` to accept `?` From 79b6ed0e0860dc4a75af50a975d47efabdd95cbc Mon Sep 17 00:00:00 2001 From: Catherine Flores Date: Tue, 25 Jul 2023 19:15:19 +0000 Subject: [PATCH 3/3] Only early return if recovered --- .../rustc_parse/src/parser/diagnostics.rs | 37 +++++++++++-------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index ef5581e1efe..7d04a335c9e 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -500,8 +500,7 @@ impl<'a> Parser<'a> { // Special-case "expected `;`" errors if expected.contains(&TokenType::Token(token::Semi)) { - if self.prev_token.kind == token::Question { - self.maybe_recover_from_ternary_operator(); + if self.prev_token == token::Question && self.maybe_recover_from_ternary_operator() { return Ok(true); } @@ -1336,26 +1335,30 @@ impl<'a> Parser<'a> { } /// Rust has no ternary operator (`cond ? then : else`). Parse it and try - /// to recover from it if `then` and `else` are valid expressions. - pub(super) fn maybe_recover_from_ternary_operator(&mut self) { - let snapshot = self.create_snapshot_for_diagnostic(); - let lo = self.prev_token.span.lo(); + /// to recover from it if `then` and `else` are valid expressions. Returns + /// whether it was a ternary operator. + pub(super) fn maybe_recover_from_ternary_operator(&mut self) -> bool { + if self.prev_token != token::Question { + return false; + } - if self.prev_token == token::Question - && match self.parse_expr() { - Ok(_) => true, - Err(err) => { - err.cancel(); - // The colon can sometimes be mistaken for type - // ascription. Catch when this happens and continue. - self.token == token::Colon - } + let lo = self.prev_token.span.lo(); + let snapshot = self.create_snapshot_for_diagnostic(); + + if match self.parse_expr() { + Ok(_) => true, + Err(err) => { + err.cancel(); + // The colon can sometimes be mistaken for type + // ascription. Catch when this happens and continue. + self.token == token::Colon } - { + } { if self.eat_noexpect(&token::Colon) { match self.parse_expr() { Ok(_) => { self.sess.emit_err(TernaryOperator { span: self.token.span.with_lo(lo) }); + return true; } Err(err) => { err.cancel(); @@ -1366,6 +1369,8 @@ impl<'a> Parser<'a> { } else { self.restore_snapshot(snapshot); }; + + false } pub(super) fn maybe_recover_from_bad_type_plus(&mut self, ty: &Ty) -> PResult<'a, ()> {