Skip to content

Commit

Permalink
Merge pull request #1142 from dtolnay/castsuffix
Browse files Browse the repository at this point in the history
Reject postfix operators after cast
  • Loading branch information
dtolnay authored Mar 14, 2022
2 parents fd6f0bf + 15ea927 commit 3f0cfc1
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 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
6 changes: 6 additions & 0 deletions tests/test_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,3 +318,9 @@ fn test_closure_vs_rangefull() {
}
"###);
}

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

0 comments on commit 3f0cfc1

Please sign in to comment.