Skip to content

Commit 1648180

Browse files
committed
Gracefully handle missing ternary operator
1 parent cb6ab95 commit 1648180

File tree

7 files changed

+220
-4
lines changed

7 files changed

+220
-4
lines changed

compiler/rustc_parse/messages.ftl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -722,6 +722,10 @@ parse_sugg_wrap_pattern_in_parens = wrap the pattern in parentheses
722722
723723
parse_switch_mut_let_order =
724724
switch the order of `mut` and `let`
725+
726+
parse_ternary_operator = Rust has no ternary operator
727+
.help = use an `if-else` expression instead
728+
725729
parse_tilde_const_lifetime = `~const` may only modify trait bounds, not lifetime bounds
726730
727731
parse_tilde_is_not_unary_operator = `~` cannot be used as a unary operator

compiler/rustc_parse/src/errors.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,14 @@ pub(crate) enum IfExpressionMissingThenBlockSub {
365365
AddThenBlock(#[primary_span] Span),
366366
}
367367

368+
#[derive(Diagnostic)]
369+
#[diag(parse_ternary_operator)]
370+
#[help]
371+
pub struct TernaryOperator {
372+
#[primary_span]
373+
pub span: Span,
374+
}
375+
368376
#[derive(Subdiagnostic)]
369377
#[suggestion(parse_extra_if_in_let_else, applicability = "maybe-incorrect", code = "")]
370378
pub(crate) struct IfExpressionLetSomeSub {

compiler/rustc_parse/src/parser/diagnostics.rs

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use crate::errors::{
1414
PatternMethodParamWithoutBody, QuestionMarkInType, QuestionMarkInTypeSugg, SelfParamNotFirst,
1515
StructLiteralBodyWithoutPath, StructLiteralBodyWithoutPathSugg, StructLiteralNeedingParens,
1616
StructLiteralNeedingParensSugg, SuggAddMissingLetStmt, SuggEscapeIdentifier, SuggRemoveComma,
17-
UnexpectedConstInGenericParam, UnexpectedConstParamDeclaration,
17+
TernaryOperator, UnexpectedConstInGenericParam, UnexpectedConstParamDeclaration,
1818
UnexpectedConstParamDeclarationSugg, UnmatchedAngleBrackets, UseEqInstead,
1919
};
2020

@@ -500,6 +500,13 @@ impl<'a> Parser<'a> {
500500

501501
// Special-case "expected `;`" errors
502502
if expected.contains(&TokenType::Token(token::Semi)) {
503+
if self.prev_token.kind == token::Question {
504+
self.maybe_ternary_lo = Some(self.prev_token.span.lo());
505+
let result = self.maybe_recover_from_ternary_operator().map(|_| true);
506+
self.maybe_ternary_lo = None;
507+
return result;
508+
}
509+
503510
if self.token.span == DUMMY_SP || self.prev_token.span == DUMMY_SP {
504511
// Likely inside a macro, can't provide meaningful suggestions.
505512
} else if !sm.is_multiline(self.prev_token.span.until(self.token.span)) {
@@ -1330,6 +1337,41 @@ impl<'a> Parser<'a> {
13301337
}
13311338
}
13321339

1340+
/// Rust has no ternary operator (`cond ? then : else`). Parse it and try
1341+
/// to recover from it if `then` and `else` are valid expressions.
1342+
pub(super) fn maybe_recover_from_ternary_operator(&mut self) -> PResult<'a, ()> {
1343+
let snapshot = self.create_snapshot_for_diagnostic();
1344+
let lo = self.prev_token.span.lo();
1345+
1346+
if self.prev_token == token::Question
1347+
&& match self.parse_expr() {
1348+
Ok(_) => true,
1349+
Err(err) => {
1350+
err.cancel();
1351+
// The colon can sometimes be mistaken for type
1352+
// ascription. Catch when this happens and continue.
1353+
self.token == token::Colon
1354+
}
1355+
}
1356+
{
1357+
if self.eat_noexpect(&token::Colon) {
1358+
match self.parse_expr() {
1359+
Ok(_) => {
1360+
self.sess.emit_err(TernaryOperator { span: self.token.span.with_lo(lo) });
1361+
}
1362+
Err(err) => {
1363+
err.cancel();
1364+
self.restore_snapshot(snapshot);
1365+
}
1366+
};
1367+
}
1368+
} else {
1369+
self.restore_snapshot(snapshot);
1370+
};
1371+
1372+
Ok(())
1373+
}
1374+
13331375
pub(super) fn maybe_recover_from_bad_type_plus(&mut self, ty: &Ty) -> PResult<'a, ()> {
13341376
// Do not add `+` to expected tokens.
13351377
if !self.token.is_like_plus() {
@@ -2111,7 +2153,7 @@ impl<'a> Parser<'a> {
21112153
}
21122154
_ => (
21132155
self.token.span,
2114-
format!("expected expression, found {}", super::token_descr(&self.token),),
2156+
format!("expected expression, found {}", super::token_descr(&self.token)),
21152157
),
21162158
};
21172159
let mut err = self.struct_span_err(span, msg);

compiler/rustc_parse/src/parser/mod.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ use rustc_errors::{
3737
use rustc_session::parse::ParseSess;
3838
use rustc_span::source_map::{Span, DUMMY_SP};
3939
use rustc_span::symbol::{kw, sym, Ident, Symbol};
40+
use rustc_span::BytePos;
4041
use std::ops::Range;
4142
use std::{cmp, mem, slice};
4243
use thin_vec::ThinVec;
@@ -157,12 +158,17 @@ pub struct Parser<'a> {
157158
/// Whether the parser is allowed to do recovery.
158159
/// This is disabled when parsing macro arguments, see #103534
159160
pub recovery: Recovery,
161+
/// The low part of a ternary operator (`cond ? then : else`).
162+
/// FIXME(Centri3): This is currently only used so that type ascription is
163+
/// not mentioned in the error. Once the error in `stmt.rs` is removed, this
164+
/// can be removed.
165+
maybe_ternary_lo: Option<BytePos>,
160166
}
161167

162168
// This type is used a lot, e.g. it's cloned when matching many declarative macro rules with nonterminals. Make sure
163169
// it doesn't unintentionally get bigger.
164170
#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
165-
rustc_data_structures::static_assert_size!(Parser<'_>, 272);
171+
rustc_data_structures::static_assert_size!(Parser<'_>, 280);
166172

167173
/// Stores span information about a closure.
168174
#[derive(Clone)]
@@ -475,6 +481,7 @@ impl<'a> Parser<'a> {
475481
},
476482
current_closure: None,
477483
recovery: Recovery::Allowed,
484+
maybe_ternary_lo: None,
478485
};
479486

480487
// Make parser point to the first token.

compiler/rustc_parse/src/parser/stmt.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -576,7 +576,9 @@ impl<'a> Parser<'a> {
576576
Applicability::MaybeIncorrect,
577577
);
578578
}
579-
if self.sess.unstable_features.is_nightly_build() {
579+
if self.sess.unstable_features.is_nightly_build()
580+
&& self.maybe_ternary_lo.is_none()
581+
{
580582
// FIXME(Nilstrieb): Remove this again after a few months.
581583
err.note("type ascription syntax has been removed, see issue #101728 <https://github.com/rust-lang/rust/issues/101728>");
582584
}

tests/ui/parser/ternary_operator.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
fn a() {
2+
let x = 5 > 2 ? true : false;
3+
//~^ ERROR Rust has no ternary operator
4+
//~| HELP use an `if-else` expression instead
5+
//~| ERROR the `?` operator can only be applied to values that implement `Try` [E0277]
6+
//~| HELP the trait `Try` is not implemented for `{integer}`
7+
//~| ERROR the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) [E0277]
8+
//~| HELP the trait `FromResidual<_>` is not implemented for `()`
9+
}
10+
11+
fn b() {
12+
let x = 5 > 2 ? { true } : { false };
13+
//~^ ERROR Rust has no ternary operator
14+
//~| HELP use an `if-else` expression instead
15+
//~| ERROR the `?` operator can only be applied to values that implement `Try` [E0277]
16+
//~| HELP the trait `Try` is not implemented for `{integer}`
17+
//~| ERROR the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) [E0277]
18+
//~| HELP the trait `FromResidual<_>` is not implemented for `()`
19+
}
20+
21+
fn c() {
22+
let x = 5 > 2 ? f32::MAX : f32::MIN;
23+
//~^ ERROR Rust has no ternary operator
24+
//~| HELP use an `if-else` expression instead
25+
//~| ERROR the `?` operator can only be applied to values that implement `Try` [E0277]
26+
//~| HELP the trait `Try` is not implemented for `{integer}`
27+
//~| ERROR the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) [E0277]
28+
//~| HELP the trait `FromResidual<_>` is not implemented for `()`
29+
}
30+
31+
fn main() {
32+
let x = 5 > 2 ? { let x = vec![]: Vec<u16>; x } : { false };
33+
//~^ ERROR Rust has no ternary operator
34+
//~| HELP use an `if-else` expression instead
35+
//~| expected one of `.`, `;`, `?`, `else`, or an operator, found `:`
36+
//~| ERROR the `?` operator can only be applied to values that implement `Try` [E0277]
37+
//~| HELP the trait `Try` is not implemented for `{integer}`
38+
//~| ERROR the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`) [E0277]
39+
//~| HELP the trait `FromResidual<_>` is not implemented for `()`
40+
}
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
error: Rust has no ternary operator
2+
--> $DIR/ternary_operator.rs:2:19
3+
|
4+
LL | let x = 5 > 2 ? true : false;
5+
| ^^^^^^^^^^^^^^^
6+
|
7+
= help: use an `if-else` expression instead
8+
9+
error: Rust has no ternary operator
10+
--> $DIR/ternary_operator.rs:12:19
11+
|
12+
LL | let x = 5 > 2 ? { true } : { false };
13+
| ^^^^^^^^^^^^^^^^^^^^^^^
14+
|
15+
= help: use an `if-else` expression instead
16+
17+
error: Rust has no ternary operator
18+
--> $DIR/ternary_operator.rs:22:19
19+
|
20+
LL | let x = 5 > 2 ? f32::MAX : f32::MIN;
21+
| ^^^^^^^^^^^^^^^^^^^^^^
22+
|
23+
= help: use an `if-else` expression instead
24+
25+
error: expected one of `.`, `;`, `?`, `else`, or an operator, found `:`
26+
--> $DIR/ternary_operator.rs:32:37
27+
|
28+
LL | let x = 5 > 2 ? { let x = vec![]: Vec<u16>; x } : { false };
29+
| ^ expected one of `.`, `;`, `?`, `else`, or an operator
30+
31+
error: Rust has no ternary operator
32+
--> $DIR/ternary_operator.rs:32:19
33+
|
34+
LL | let x = 5 > 2 ? { let x = vec![]: Vec<u16>; x } : { false };
35+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
36+
|
37+
= help: use an `if-else` expression instead
38+
39+
error[E0277]: the `?` operator can only be applied to values that implement `Try`
40+
--> $DIR/ternary_operator.rs:2:17
41+
|
42+
LL | let x = 5 > 2 ? true : false;
43+
| ^^^ the `?` operator cannot be applied to type `{integer}`
44+
|
45+
= help: the trait `Try` is not implemented for `{integer}`
46+
47+
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
48+
--> $DIR/ternary_operator.rs:2:19
49+
|
50+
LL | fn a() {
51+
| ------ this function should return `Result` or `Option` to accept `?`
52+
LL | let x = 5 > 2 ? true : false;
53+
| ^ cannot use the `?` operator in a function that returns `()`
54+
|
55+
= help: the trait `FromResidual<_>` is not implemented for `()`
56+
57+
error[E0277]: the `?` operator can only be applied to values that implement `Try`
58+
--> $DIR/ternary_operator.rs:12:17
59+
|
60+
LL | let x = 5 > 2 ? { true } : { false };
61+
| ^^^ the `?` operator cannot be applied to type `{integer}`
62+
|
63+
= help: the trait `Try` is not implemented for `{integer}`
64+
65+
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
66+
--> $DIR/ternary_operator.rs:12:19
67+
|
68+
LL | fn b() {
69+
| ------ this function should return `Result` or `Option` to accept `?`
70+
LL | let x = 5 > 2 ? { true } : { false };
71+
| ^ cannot use the `?` operator in a function that returns `()`
72+
|
73+
= help: the trait `FromResidual<_>` is not implemented for `()`
74+
75+
error[E0277]: the `?` operator can only be applied to values that implement `Try`
76+
--> $DIR/ternary_operator.rs:22:17
77+
|
78+
LL | let x = 5 > 2 ? f32::MAX : f32::MIN;
79+
| ^^^ the `?` operator cannot be applied to type `{integer}`
80+
|
81+
= help: the trait `Try` is not implemented for `{integer}`
82+
83+
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
84+
--> $DIR/ternary_operator.rs:22:19
85+
|
86+
LL | fn c() {
87+
| ------ this function should return `Result` or `Option` to accept `?`
88+
LL | let x = 5 > 2 ? f32::MAX : f32::MIN;
89+
| ^ cannot use the `?` operator in a function that returns `()`
90+
|
91+
= help: the trait `FromResidual<_>` is not implemented for `()`
92+
93+
error[E0277]: the `?` operator can only be applied to values that implement `Try`
94+
--> $DIR/ternary_operator.rs:32:17
95+
|
96+
LL | let x = 5 > 2 ? { let x = vec![]: Vec<u16>; x } : { false };
97+
| ^^^ the `?` operator cannot be applied to type `{integer}`
98+
|
99+
= help: the trait `Try` is not implemented for `{integer}`
100+
101+
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
102+
--> $DIR/ternary_operator.rs:32:19
103+
|
104+
LL | fn main() {
105+
| --------- this function should return `Result` or `Option` to accept `?`
106+
LL | let x = 5 > 2 ? { let x = vec![]: Vec<u16>; x } : { false };
107+
| ^ cannot use the `?` operator in a function that returns `()`
108+
|
109+
= help: the trait `FromResidual<_>` is not implemented for `()`
110+
111+
error: aborting due to 13 previous errors
112+
113+
For more information about this error, try `rustc --explain E0277`.

0 commit comments

Comments
 (0)