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

Fix parenthesization of field expressions in function calls #1786

Merged
merged 3 commits into from
Nov 29, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 16 additions & 20 deletions src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1036,6 +1036,16 @@ impl IdentFragment for Member {
}
}

#[cfg(any(feature = "parsing", feature = "printing"))]
impl Member {
pub(crate) fn is_named(&self) -> bool {
match self {
Member::Named(_) => true,
Member::Unnamed(_) => false,
}
}
}

ast_struct! {
/// The index of an unnamed tuple struct field.
#[cfg_attr(docsrs, doc(cfg(any(feature = "full", feature = "derive"))))]
Expand Down Expand Up @@ -3021,15 +3031,6 @@ pub(crate) mod parsing {
Ok(!trailing_dot)
}

impl Member {
pub(crate) fn is_named(&self) -> bool {
match self {
Member::Named(_) => true,
Member::Unnamed(_) => false,
}
}
}

#[cfg(feature = "full")]
#[cfg_attr(docsrs, doc(cfg(feature = "parsing")))]
impl Parse for PointerMutability {
Expand Down Expand Up @@ -3405,22 +3406,17 @@ pub(crate) mod printing {
fn print_expr_call(e: &ExprCall, tokens: &mut TokenStream, fixup: FixupContext) {
outer_attrs_to_tokens(&e.attrs, tokens);

let call_precedence = if let Expr::Field(_) = &*e.func {
Precedence::MIN
} else {
Precedence::Unambiguous
};
let func_fixup = fixup.leftmost_subexpression_with_begin_operator(
#[cfg(feature = "full")]
true,
false,
);
print_subexpression(
&e.func,
func_fixup.leading_precedence(&e.func) < call_precedence,
tokens,
func_fixup,
);
let needs_group = if let Expr::Field(func) = &*e.func {
func.member.is_named()
} else {
func_fixup.leading_precedence(&e.func) < Precedence::Unambiguous
};
print_subexpression(&e.func, needs_group, tokens, func_fixup);

e.paren_token.surround(tokens, |tokens| {
e.args.to_tokens(tokens);
Expand Down
1 change: 1 addition & 0 deletions tests/test_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -703,6 +703,7 @@ fn test_fixup() {
quote! { (1 < 2) == (3 < 4) },
quote! { { (let _ = ()) } },
quote! { (#[attr] thing).field },
quote! { (self.f)() },
] {
let original: Expr = syn::parse2(tokens).unwrap();

Expand Down