Skip to content

Commit

Permalink
Switch from Paren to Group for automatic grouping
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed May 16, 2024
1 parent f464193 commit 2b7bac0
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 9 deletions.
4 changes: 2 additions & 2 deletions src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3052,7 +3052,7 @@ pub(crate) mod printing {
};

if needs_group {
token::Paren::default().surround(tokens, do_print_expr);
token::Group::default().surround(tokens, do_print_expr);
} else {
do_print_expr(tokens);
}
Expand Down Expand Up @@ -3108,7 +3108,7 @@ pub(crate) mod printing {
};

if needs_group {
token::Paren::default().surround(tokens, do_print_expr);
token::Group::default().surround(tokens, do_print_expr);
} else {
do_print_expr(tokens);
}
Expand Down
33 changes: 26 additions & 7 deletions tests/test_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
#[macro_use]
mod macros;

use crate::macros::debug::Lite;
use proc_macro2::{Delimiter, Group};
use quote::{quote, ToTokens as _};
use std::mem;
use syn::punctuated::Punctuated;
use syn::visit_mut::{self, VisitMut};
use syn::{parse_quote, token, Expr, ExprRange, ExprTuple, Stmt, Token};
use syn::{parse_quote, token, Expr, ExprGroup, ExprRange, ExprTuple, Stmt, Token};

#[test]
fn test_expr_parse() {
Expand Down Expand Up @@ -655,6 +656,23 @@ fn test_fixup() {
}
}

struct ConvertParensToGroup;

impl VisitMut for ConvertParensToGroup {
fn visit_expr_mut(&mut self, e: &mut Expr) {
if let Expr::Paren(original) = e {
*e = Expr::Group(ExprGroup {
attrs: mem::take(&mut original.attrs),
group_token: token::Group {
span: original.paren_token.span.join(),
},
expr: Box::new(mem::replace(&mut *original.expr, Expr::PLACEHOLDER)),
});
}
visit_mut::visit_expr_mut(self, e);
}
}

for tokens in [
quote! { 2 * (1 + 1) },
quote! { 0 + (0 + 0) },
Expand All @@ -668,8 +686,6 @@ fn test_fixup() {
quote! { &mut (x as i32) },
quote! { -(x as i32) },
quote! { if (S {} == 1) {} },
quote! { { (m! {}) - 1 } },
quote! { match m { _ => ({}) - 1 } },
quote! { if let _ = (a && b) && c {} },
quote! { if let _ = (S {}) {} },
] {
Expand All @@ -682,11 +698,14 @@ fn test_fixup() {
Err(err) => panic!("failed to parse `{}`: {}", flat.to_token_stream(), err),
};

let mut expected = original.clone();
ConvertParensToGroup.visit_expr_mut(&mut expected);

assert!(
original == reconstructed,
"original: {}\nreconstructed: {}",
original.to_token_stream(),
reconstructed.to_token_stream(),
expected == reconstructed,
"expected: {:#?}\nreconstructed: {:#?}",
Lite(&expected),
Lite(&reconstructed),
);
}
}

0 comments on commit 2b7bac0

Please sign in to comment.