From c86abb3e2bb95ad82563b22012125433a955293c Mon Sep 17 00:00:00 2001 From: fw Date: Thu, 5 Sep 2024 17:35:52 -0400 Subject: [PATCH] transpile: parenthesize subexpression of reference expressions if necessary --- c2rust-ast-builder/src/builder.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/c2rust-ast-builder/src/builder.rs b/c2rust-ast-builder/src/builder.rs index 252339c988..ef75b2d796 100644 --- a/c2rust-ast-builder/src/builder.rs +++ b/c2rust-ast-builder/src/builder.rs @@ -985,13 +985,13 @@ impl Builder { } pub fn addr_of_expr(self, e: Box) -> Box { - Box::new(Expr::Reference(ExprReference { + Box::new(parenthesize_if_necessary(Expr::Reference(ExprReference { attrs: self.attrs, and_token: Token![&](self.span), raw: Default::default(), mutability: self.mutbl.to_token(), expr: e, - })) + }))) } pub fn mac_expr(self, mac: Macro) -> Box { @@ -2280,7 +2280,7 @@ fn expr_precedence(e: &Expr) -> u8 { Expr::Field(_ef) => 16, Expr::Call(_) | Expr::Index(_) => 15, Expr::Try(_et) => 14, - Expr::Unary(_eu) => 13, + Expr::Unary(_) | Expr::Reference(_) => 13, Expr::Cast(_ec) => 12, Expr::Binary(eb) => 2 + binop_precedence(&eb.op), Expr::Assign(_) | Expr::AssignOp(_) => 1, @@ -2376,6 +2376,9 @@ fn parenthesize_if_necessary(mut outer: Expr) -> Expr { Expr::Unary(ref mut eu) => { parenthesize_if_gt(&mut eu.expr); } + Expr::Reference(ref mut er) => { + parenthesize_if_gt(&mut er.expr); + } Expr::Binary(ref mut eb) => { parenthesize_if_gt(&mut eb.left); // Because binops associate right, parenthesize same-precedence RHS