Auto merge of #114028 - Centri3:ternary-operator, r=compiler-errors
Gracefully handle ternary operator Fixes #112578 ~~May not be the best way to do this as it doesn't check for a single `:`, so it could perhaps appear even when the actual issue is just a missing semicolon. May not be the biggest deal, though?~~ Nevermind, got it working properly now ^^
This commit is contained in:
commit
a04e649c09
5 changed files with 241 additions and 2 deletions
|
@ -724,6 +724,10 @@ parse_sugg_wrap_pattern_in_parens = wrap the pattern in parentheses
|
||||||
|
|
||||||
parse_switch_mut_let_order =
|
parse_switch_mut_let_order =
|
||||||
switch the order of `mut` and `let`
|
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_const_lifetime = `~const` may only modify trait bounds, not lifetime bounds
|
||||||
|
|
||||||
parse_tilde_is_not_unary_operator = `~` cannot be used as a unary operator
|
parse_tilde_is_not_unary_operator = `~` cannot be used as a unary operator
|
||||||
|
|
|
@ -365,6 +365,14 @@ pub(crate) enum IfExpressionMissingThenBlockSub {
|
||||||
AddThenBlock(#[primary_span] Span),
|
AddThenBlock(#[primary_span] Span),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Diagnostic)]
|
||||||
|
#[diag(parse_ternary_operator)]
|
||||||
|
#[help]
|
||||||
|
pub struct TernaryOperator {
|
||||||
|
#[primary_span]
|
||||||
|
pub span: Span,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Subdiagnostic)]
|
#[derive(Subdiagnostic)]
|
||||||
#[suggestion(parse_extra_if_in_let_else, applicability = "maybe-incorrect", code = "")]
|
#[suggestion(parse_extra_if_in_let_else, applicability = "maybe-incorrect", code = "")]
|
||||||
pub(crate) struct IfExpressionLetSomeSub {
|
pub(crate) struct IfExpressionLetSomeSub {
|
||||||
|
|
|
@ -14,7 +14,7 @@ use crate::errors::{
|
||||||
PatternMethodParamWithoutBody, QuestionMarkInType, QuestionMarkInTypeSugg, SelfParamNotFirst,
|
PatternMethodParamWithoutBody, QuestionMarkInType, QuestionMarkInTypeSugg, SelfParamNotFirst,
|
||||||
StructLiteralBodyWithoutPath, StructLiteralBodyWithoutPathSugg, StructLiteralNeedingParens,
|
StructLiteralBodyWithoutPath, StructLiteralBodyWithoutPathSugg, StructLiteralNeedingParens,
|
||||||
StructLiteralNeedingParensSugg, SuggAddMissingLetStmt, SuggEscapeIdentifier, SuggRemoveComma,
|
StructLiteralNeedingParensSugg, SuggAddMissingLetStmt, SuggEscapeIdentifier, SuggRemoveComma,
|
||||||
UnexpectedConstInGenericParam, UnexpectedConstParamDeclaration,
|
TernaryOperator, UnexpectedConstInGenericParam, UnexpectedConstParamDeclaration,
|
||||||
UnexpectedConstParamDeclarationSugg, UnmatchedAngleBrackets, UseEqInstead,
|
UnexpectedConstParamDeclarationSugg, UnmatchedAngleBrackets, UseEqInstead,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -500,6 +500,10 @@ impl<'a> Parser<'a> {
|
||||||
|
|
||||||
// Special-case "expected `;`" errors
|
// Special-case "expected `;`" errors
|
||||||
if expected.contains(&TokenType::Token(token::Semi)) {
|
if expected.contains(&TokenType::Token(token::Semi)) {
|
||||||
|
if self.prev_token == token::Question && self.maybe_recover_from_ternary_operator() {
|
||||||
|
return Ok(true);
|
||||||
|
}
|
||||||
|
|
||||||
if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
|
if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
|
||||||
// Likely inside a macro, can't provide meaningful suggestions.
|
// Likely inside a macro, can't provide meaningful suggestions.
|
||||||
} else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
|
} else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
|
||||||
|
@ -1330,6 +1334,45 @@ 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. 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
self.restore_snapshot(snapshot);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.restore_snapshot(snapshot);
|
||||||
|
};
|
||||||
|
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) fn maybe_recover_from_bad_type_plus(&mut self, ty: &Ty) -> PResult<'a, ()> {
|
pub(super) fn maybe_recover_from_bad_type_plus(&mut self, ty: &Ty) -> PResult<'a, ()> {
|
||||||
// Do not add `+` to expected tokens.
|
// Do not add `+` to expected tokens.
|
||||||
if !self.token.is_like_plus() {
|
if !self.token.is_like_plus() {
|
||||||
|
@ -2111,7 +2154,7 @@ impl<'a> Parser<'a> {
|
||||||
}
|
}
|
||||||
_ => (
|
_ => (
|
||||||
self.token.span,
|
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);
|
let mut err = self.struct_span_err(span, msg);
|
||||||
|
|
69
tests/ui/parser/ternary_operator.rs
Normal file
69
tests/ui/parser/ternary_operator.rs
Normal file
|
@ -0,0 +1,69 @@
|
||||||
|
// 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
|
||||||
|
//~| 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 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() { //~ 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
|
||||||
|
//~| 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 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() { //~ 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
|
||||||
|
//~| 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 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() { //~ NOTE this function should return `Result` or `Option` to accept `?`
|
||||||
|
let x = 5 > 2 ? { let x = vec![]: Vec<u16>; x } : { false };
|
||||||
|
//~^ ERROR Rust has no ternary operator
|
||||||
|
//~| HELP use an `if-else` expression instead
|
||||||
|
//~| 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 <https://github.com/rust-lang/rust/issues/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 `?`
|
||||||
|
}
|
115
tests/ui/parser/ternary_operator.stderr
Normal file
115
tests/ui/parser/ternary_operator.stderr
Normal file
|
@ -0,0 +1,115 @@
|
||||||
|
error: Rust has no ternary operator
|
||||||
|
--> $DIR/ternary_operator.rs:5: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:21: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:37: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:53:37
|
||||||
|
|
|
||||||
|
LL | let x = 5 > 2 ? { let x = vec![]: Vec<u16>; x } : { false };
|
||||||
|
| ^ expected one of `.`, `;`, `?`, `else`, or an operator
|
||||||
|
|
|
||||||
|
= note: type ascription syntax has been removed, see issue #101728 <https://github.com/rust-lang/rust/issues/101728>
|
||||||
|
|
||||||
|
error: Rust has no ternary operator
|
||||||
|
--> $DIR/ternary_operator.rs:53:19
|
||||||
|
|
|
||||||
|
LL | let x = 5 > 2 ? { let x = vec![]: Vec<u16>; 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:5: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:5: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:21: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:21: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:37: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:37: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:53:17
|
||||||
|
|
|
||||||
|
LL | let x = 5 > 2 ? { let x = vec![]: Vec<u16>; 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:53:19
|
||||||
|
|
|
||||||
|
LL | fn main() {
|
||||||
|
| --------- this function should return `Result` or `Option` to accept `?`
|
||||||
|
LL | let x = 5 > 2 ? { let x = vec![]: Vec<u16>; 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`.
|
Loading…
Add table
Add a link
Reference in a new issue