Skip to content

Commit

Permalink
Reject postfix operators after cast
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Mar 14, 2022
1 parent 097b3a2 commit 15ea927
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
25 changes: 25 additions & 0 deletions src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1365,6 +1365,7 @@ pub(crate) mod parsing {
} else if Precedence::Cast >= base && input.peek(Token![as]) {
let as_token: Token![as] = input.parse()?;
let ty = input.call(Type::without_plus)?;
check_cast(input)?;
lhs = Expr::Cast(ExprCast {
attrs: Vec::new(),
expr: Box::new(lhs),
Expand All @@ -1374,6 +1375,7 @@ pub(crate) mod parsing {
} else if Precedence::Cast >= base && input.peek(Token![:]) && !input.peek(Token![::]) {
let colon_token: Token![:] = input.parse()?;
let ty = input.call(Type::without_plus)?;
check_cast(input)?;
lhs = Expr::Type(ExprType {
attrs: Vec::new(),
expr: Box::new(lhs),
Expand Down Expand Up @@ -1421,6 +1423,7 @@ pub(crate) mod parsing {
} else if Precedence::Cast >= base && input.peek(Token![as]) {
let as_token: Token![as] = input.parse()?;
let ty = input.call(Type::without_plus)?;
check_cast(input)?;
lhs = Expr::Cast(ExprCast {
attrs: Vec::new(),
expr: Box::new(lhs),
Expand Down Expand Up @@ -2896,6 +2899,28 @@ pub(crate) mod parsing {
}
}
}

fn check_cast(input: ParseStream) -> Result<()> {
let kind = if input.peek(Token![.]) && !input.peek(Token![..]) {
if input.peek2(token::Await) {
"`.await`"
} else if input.peek2(Ident) && (input.peek3(token::Paren) || input.peek3(Token![::])) {
"a method call"
} else {
"a field access"
}
} else if input.peek(Token![?]) {
"`?`"
} else if input.peek(token::Bracket) {
"indexing"
} else if input.peek(token::Paren) {
"a function call"
} else {
return Ok(());
};
let msg = format!("casts cannot be followed by {}", kind);
Err(input.error(msg))
}
}

#[cfg(feature = "printing")]
Expand Down
4 changes: 2 additions & 2 deletions tests/test_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,6 @@ fn test_closure_vs_rangefull() {

#[test]
fn test_postfix_operator_after_cast() {
syn::parse_str::<Expr>("|| &x as T[0]").unwrap(); // FIXME
syn::parse_str::<Expr>("|| () as ()()").unwrap(); // FIXME
syn::parse_str::<Expr>("|| &x as T[0]").unwrap_err();
syn::parse_str::<Expr>("|| () as ()()").unwrap_err();
}

0 comments on commit 15ea927

Please sign in to comment.