Skip to content

Commit

Permalink
Add test of parenthesis insertion by Expr's ToTokens
Browse files Browse the repository at this point in the history
    ---- test_fixup stdout ----
    thread 'test_fixup' panicked at tests/test_expr.rs:665:5:
    original: 2 * (1 + 1)
    reconstructed: 2 * 1 + 1
  • Loading branch information
dtolnay committed May 16, 2024
1 parent 83ea289 commit 1b6a450
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions tests/test_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ mod macros;

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};

#[test]
Expand Down Expand Up @@ -639,3 +641,31 @@ fn test_assign_range_precedence() {
syn::parse_str::<Expr>("() .. () = ()").unwrap_err();
syn::parse_str::<Expr>("() .. () += ()").unwrap_err();
}

#[test]
fn test_fixup() {
struct FlattenParens;

impl VisitMut for FlattenParens {
fn visit_expr_mut(&mut self, e: &mut Expr) {
while let Expr::Paren(paren) = e {
*e = mem::replace(&mut *paren.expr, Expr::PLACEHOLDER);
}
visit_mut::visit_expr_mut(self, e);
}
}

let tokens = quote!(2 * (1 + 1));
let original: Expr = syn::parse2(tokens).unwrap();

let mut flat = original.clone();
FlattenParens.visit_expr_mut(&mut flat);
let reconstructed: Expr = syn::parse2(flat.to_token_stream()).unwrap();

assert!(
original == reconstructed,
"original: {}\nreconstructed: {}",
original.to_token_stream(),
reconstructed.to_token_stream(),
);
}

0 comments on commit 1b6a450

Please sign in to comment.