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

Default behavior does not insert synthetic parens for precedence #81

Open
fowles opened this issue Sep 23, 2024 · 1 comment
Open

Default behavior does not insert synthetic parens for precedence #81

fowles opened this issue Sep 23, 2024 · 1 comment

Comments

@fowles
Copy link

fowles commented Sep 23, 2024

prettyplease will generate rust code that does not accurately reflect the Expr tree that goes into it. There is a workaround using to_token_stream.

  let mut file = syn::File {
    shebang: None,
    attrs: vec![],
    items: vec![],
  };
  let mut func: syn::ItemFn = parse_quote!(fn foo(n: i32) -> i32 { });
  let lhs: syn:Expr = parse_quote!(n + n);
  let rhs: syn:Expr = parse_quote!(n + n);
  func.block.stmts.push(
    syn::ExprBinary {
      attrs: vec![],
      op: parse_quote!(*),
      left: Box::new(lhs),
      right: Box::new(rhs),
    }
    .into()
  );

  let pretty_direct = prettyplease::unparse(&file);
  // INCORRECT: fn foo(n: i32) -> i32 { n + n * n + n }

  let munged: syn::File = syn::parse2(rust.to_token_stream()).unwrap();
  let pretty_indirect =  prettyplease::unparse(&munged)).unwrap();
  // CORRECT: fn foo(n: i32) -> i32 { (n + n) * (n + n) }

Apologies if this doesn't quite compile, but it should give you the general gist of the issue.

@fowles
Copy link
Author

fowles commented Oct 14, 2024

Do the owners consider this a bug? If so, would they be amenable to PRs fixing it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant