Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reject postfix operators after cast #1142

Merged
merged 2 commits into from Mar 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/expr.rs
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
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();
}