Skip to content

Commit 111724f

Browse files
authored
Rollup merge of #68985 - daboross:fix-35813, r=Centril
Parse & reject postfix operators after casts This adds an explicit error messages for when parsing `x as Type[0]` or similar expressions. Our add an extra parse case for parsing any postfix operator (dot, indexing, method calls, await) that triggers directly after parsing `as` expressions. My friend and I worked on this together, but they're still deciding on a github username and thus I'm submitting this for both of us. It will immediately error out, but will also provide the rest of the parser with a useful parse tree to deal with. There's one decision we made in how this produces the parse tree. In the situation `&x as T[0]`, one could imagine this parsing as either `&((x as T)[0])` or `((&x) as T)[0]`. We chose the latter for ease of implementation, and as it seemed the most intuitive. Feedback welcome! This is our first change to the parser section, and it might be completely horrible. Fixes #35813.
2 parents e8bb6c0 + 453c505 commit 111724f

File tree

7 files changed

+671
-15
lines changed

7 files changed

+671
-15
lines changed

src/librustc_parse/parser/expr.rs

+58-5
Original file line numberDiff line numberDiff line change
@@ -544,8 +544,8 @@ impl<'a> Parser<'a> {
544544
// Save the state of the parser before parsing type normally, in case there is a
545545
// LessThan comparison after this cast.
546546
let parser_snapshot_before_type = self.clone();
547-
match self.parse_ty_no_plus() {
548-
Ok(rhs) => Ok(mk_expr(self, rhs)),
547+
let cast_expr = match self.parse_ty_no_plus() {
548+
Ok(rhs) => mk_expr(self, rhs),
549549
Err(mut type_err) => {
550550
// Rewind to before attempting to parse the type with generics, to recover
551551
// from situations like `x as usize < y` in which we first tried to parse
@@ -599,17 +599,70 @@ impl<'a> Parser<'a> {
599599
)
600600
.emit();
601601

602-
Ok(expr)
602+
expr
603603
}
604604
Err(mut path_err) => {
605605
// Couldn't parse as a path, return original error and parser state.
606606
path_err.cancel();
607607
mem::replace(self, parser_snapshot_after_type);
608-
Err(type_err)
608+
return Err(type_err);
609609
}
610610
}
611611
}
612-
}
612+
};
613+
614+
self.parse_and_disallow_postfix_after_cast(cast_expr)
615+
}
616+
617+
/// Parses a postfix operators such as `.`, `?`, or index (`[]`) after a cast,
618+
/// then emits an error and returns the newly parsed tree.
619+
/// The resulting parse tree for `&x as T[0]` has a precedence of `((&x) as T)[0]`.
620+
fn parse_and_disallow_postfix_after_cast(
621+
&mut self,
622+
cast_expr: P<Expr>,
623+
) -> PResult<'a, P<Expr>> {
624+
// Save the memory location of expr before parsing any following postfix operators.
625+
// This will be compared with the memory location of the output expression.
626+
// If they different we can assume we parsed another expression because the existing expression is not reallocated.
627+
let addr_before = &*cast_expr as *const _ as usize;
628+
let span = cast_expr.span;
629+
let with_postfix = self.parse_dot_or_call_expr_with_(cast_expr, span)?;
630+
let changed = addr_before != &*with_postfix as *const _ as usize;
631+
632+
// Check if an illegal postfix operator has been added after the cast.
633+
// If the resulting expression is not a cast, or has a different memory location, it is an illegal postfix operator.
634+
if !matches!(with_postfix.kind, ExprKind::Cast(_, _) | ExprKind::Type(_, _)) || changed {
635+
let msg = format!(
636+
"casts cannot be followed by {}",
637+
match with_postfix.kind {
638+
ExprKind::Index(_, _) => "indexing",
639+
ExprKind::Try(_) => "?",
640+
ExprKind::Field(_, _) => "a field access",
641+
ExprKind::MethodCall(_, _) => "a method call",
642+
ExprKind::Call(_, _) => "a function call",
643+
ExprKind::Await(_) => "`.await`",
644+
_ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"),
645+
}
646+
);
647+
let mut err = self.struct_span_err(span, &msg);
648+
// If type ascription is "likely an error", the user will already be getting a useful
649+
// help message, and doesn't need a second.
650+
if self.last_type_ascription.map_or(false, |last_ascription| last_ascription.1) {
651+
self.maybe_annotate_with_ascription(&mut err, false);
652+
} else {
653+
let suggestions = vec![
654+
(span.shrink_to_lo(), "(".to_string()),
655+
(span.shrink_to_hi(), ")".to_string()),
656+
];
657+
err.multipart_suggestion(
658+
"try surrounding the expression in parentheses",
659+
suggestions,
660+
Applicability::MachineApplicable,
661+
);
662+
}
663+
err.emit();
664+
};
665+
Ok(with_postfix)
613666
}
614667

615668
fn parse_assoc_op_ascribe(&mut self, lhs: P<Expr>, lhs_span: Span) -> PResult<'a, P<Expr>> {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
// edition:2018
2+
#![crate_type = "lib"]
3+
#![feature(type_ascription)]
4+
use std::future::Future;
5+
use std::pin::Pin;
6+
7+
// This tests the parser for "x as Y[z]". It errors, but we want to give useful
8+
// errors and parse such that further code gives useful errors.
9+
pub fn index_after_as_cast() {
10+
vec![1, 2, 3] as Vec<i32>[0];
11+
//~^ ERROR: casts cannot be followed by indexing
12+
vec![1, 2, 3]: Vec<i32>[0];
13+
//~^ ERROR: casts cannot be followed by indexing
14+
}
15+
16+
pub fn index_after_cast_to_index() {
17+
(&[0]) as &[i32][0];
18+
//~^ ERROR: casts cannot be followed by indexing
19+
(&[0i32]): &[i32; 1][0];
20+
//~^ ERROR: casts cannot be followed by indexing
21+
}
22+
23+
pub fn cast_after_cast() {
24+
if 5u64 as i32 as u16 == 0u16 {
25+
26+
}
27+
if 5u64: u64: u64 == 0u64 {
28+
29+
}
30+
let _ = 5u64: u64: u64 as u8 as i8 == 9i8;
31+
let _ = 0i32: i32: i32;
32+
let _ = 0 as i32: i32;
33+
let _ = 0i32: i32 as i32;
34+
let _ = 0 as i32 as i32;
35+
let _ = 0i32: i32: i32 as u32 as i32;
36+
}
37+
38+
pub fn cast_cast_method_call() {
39+
let _ = 0i32: i32: i32.count_ones();
40+
//~^ ERROR: casts cannot be followed by a method call
41+
let _ = 0 as i32: i32.count_ones();
42+
//~^ ERROR: casts cannot be followed by a method call
43+
let _ = 0i32: i32 as i32.count_ones();
44+
//~^ ERROR: casts cannot be followed by a method call
45+
let _ = 0 as i32 as i32.count_ones();
46+
//~^ ERROR: casts cannot be followed by a method call
47+
let _ = 0i32: i32: i32 as u32 as i32.count_ones();
48+
//~^ ERROR: casts cannot be followed by a method call
49+
let _ = 0i32: i32.count_ones(): u32;
50+
//~^ ERROR: casts cannot be followed by a method call
51+
let _ = 0 as i32.count_ones(): u32;
52+
//~^ ERROR: casts cannot be followed by a method call
53+
let _ = 0i32: i32.count_ones() as u32;
54+
//~^ ERROR: casts cannot be followed by a method call
55+
let _ = 0 as i32.count_ones() as u32;
56+
//~^ ERROR: casts cannot be followed by a method call
57+
let _ = 0i32: i32: i32.count_ones() as u32 as i32;
58+
//~^ ERROR: casts cannot be followed by a method call
59+
}
60+
61+
pub fn multiline_error() {
62+
let _ = 0
63+
as i32
64+
.count_ones();
65+
//~^^^ ERROR: casts cannot be followed by a method call
66+
}
67+
68+
// this tests that the precedence for `!x as Y.Z` is still what we expect
69+
pub fn precedence() {
70+
let x: i32 = &vec![1, 2, 3] as &Vec<i32>[0];
71+
//~^ ERROR: casts cannot be followed by indexing
72+
}
73+
74+
pub fn method_calls() {
75+
0 as i32.max(0);
76+
//~^ ERROR: casts cannot be followed by a method call
77+
0: i32.max(0);
78+
//~^ ERROR: casts cannot be followed by a method call
79+
}
80+
81+
pub fn complex() {
82+
let _ = format!(
83+
"{} and {}",
84+
if true { 33 } else { 44 } as i32.max(0),
85+
//~^ ERROR: casts cannot be followed by a method call
86+
if true { 33 } else { 44 }: i32.max(0)
87+
//~^ ERROR: casts cannot be followed by a method call
88+
);
89+
}
90+
91+
pub fn in_condition() {
92+
if 5u64 as i32.max(0) == 0 {
93+
//~^ ERROR: casts cannot be followed by a method call
94+
}
95+
if 5u64: u64.max(0) == 0 {
96+
//~^ ERROR: casts cannot be followed by a method call
97+
}
98+
}
99+
100+
pub fn inside_block() {
101+
let _ = if true {
102+
5u64 as u32.max(0) == 0
103+
//~^ ERROR: casts cannot be followed by a method call
104+
} else { false };
105+
let _ = if true {
106+
5u64: u64.max(0) == 0
107+
//~^ ERROR: casts cannot be followed by a method call
108+
} else { false };
109+
}
110+
111+
static bar: &[i32] = &(&[1,2,3] as &[i32][0..1]);
112+
//~^ ERROR: casts cannot be followed by indexing
113+
114+
static bar2: &[i32] = &(&[1i32,2,3]: &[i32; 3][0..1]);
115+
//~^ ERROR: casts cannot be followed by indexing
116+
117+
118+
pub fn cast_then_try() -> Result<u64,u64> {
119+
Err(0u64) as Result<u64,u64>?;
120+
//~^ ERROR: casts cannot be followed by ?
121+
Err(0u64): Result<u64,u64>?;
122+
//~^ ERROR: casts cannot be followed by ?
123+
Ok(1)
124+
}
125+
126+
127+
pub fn cast_then_call() {
128+
type F = fn(u8);
129+
// type ascription won't actually do [unique drop fn type] -> fn(u8) casts.
130+
let drop_ptr = drop as fn(u8);
131+
drop as F();
132+
//~^ ERROR: parenthesized type parameters may only be used with a `Fn` trait [E0214]
133+
drop_ptr: F();
134+
//~^ ERROR: parenthesized type parameters may only be used with a `Fn` trait [E0214]
135+
}
136+
137+
pub fn cast_to_fn_should_work() {
138+
let drop_ptr = drop as fn(u8);
139+
drop as fn(u8);
140+
drop_ptr: fn(u8);
141+
}
142+
143+
pub fn parens_after_cast_error() {
144+
let drop_ptr = drop as fn(u8);
145+
drop as fn(u8)(0);
146+
//~^ ERROR: casts cannot be followed by a function call
147+
drop_ptr: fn(u8)(0);
148+
//~^ ERROR: casts cannot be followed by a function call
149+
}
150+
151+
pub async fn cast_then_await() {
152+
Box::pin(noop()) as Pin<Box<dyn Future<Output = ()>>>.await;
153+
//~^ ERROR: casts cannot be followed by `.await`
154+
155+
Box::pin(noop()): Pin<Box<_>>.await;
156+
//~^ ERROR: casts cannot be followed by `.await`
157+
}
158+
159+
pub async fn noop() {}
160+
161+
#[derive(Default)]
162+
pub struct Foo {
163+
pub bar: u32,
164+
}
165+
166+
pub fn struct_field() {
167+
Foo::default() as Foo.bar;
168+
//~^ ERROR: cannot be followed by a field access
169+
Foo::default(): Foo.bar;
170+
//~^ ERROR: cannot be followed by a field access
171+
}

0 commit comments

Comments
 (0)