From 702b574afb13e4aad7dbd4179b87cdd958990e58 Mon Sep 17 00:00:00 2001 From: Dunqing <29533304+Dunqing@users.noreply.github.com> Date: Fri, 11 Oct 2024 02:04:27 +0000 Subject: [PATCH] refactor(codegen): only print necessary parentheses in TSAsExpression (#6429) Part of fixing #6385 --- crates/oxc_codegen/src/gen.rs | 14 +++++++------- .../tests/integration/snapshots/ts.snap | 17 ++++++++++++++++- crates/oxc_codegen/tests/integration/ts.rs | 5 ++++- 3 files changed, 27 insertions(+), 9 deletions(-) diff --git a/crates/oxc_codegen/src/gen.rs b/crates/oxc_codegen/src/gen.rs index 93fc53b9fd29b..a815a3c01880a 100644 --- a/crates/oxc_codegen/src/gen.rs +++ b/crates/oxc_codegen/src/gen.rs @@ -2092,13 +2092,13 @@ impl<'a> GenExpr for NewExpression<'a> { impl<'a> GenExpr for TSAsExpression<'a> { fn gen_expr(&self, p: &mut Codegen, precedence: Precedence, ctx: Context) { - p.print_char(b'('); - p.print_char(b'('); - self.expression.print_expr(p, precedence, Context::default()); - p.print_char(b')'); - p.print_str(" as "); - self.type_annotation.print(p, ctx); - p.print_char(b')'); + let wrap = precedence >= Precedence::Shift; + + p.wrap(wrap, |p| { + self.expression.print_expr(p, Precedence::Exponentiation, ctx); + p.print_str(" as "); + self.type_annotation.print(p, ctx); + }); } } diff --git a/crates/oxc_codegen/tests/integration/snapshots/ts.snap b/crates/oxc_codegen/tests/integration/snapshots/ts.snap index c5bb3fddcaae7..727c54bba0952 100644 --- a/crates/oxc_codegen/tests/integration/snapshots/ts.snap +++ b/crates/oxc_codegen/tests/integration/snapshots/ts.snap @@ -159,7 +159,7 @@ a = x!; ########## 25 b = (x as y); ---------- -b = ((x) as y); +b = x as y; ########## 26 c = foo; @@ -210,3 +210,18 @@ export type Component< E extends EmitsOptions | Record = {}, S extends Record = any > = ConcreteComponent | ComponentPublicInstanceConstructor; + +########## 32 +(a || b) as any +---------- +(a || b) as any; + +########## 33 +(a ** b) as any +---------- +(a ** b) as any; + +########## 34 +(function g() {}) as any +---------- +(function g() {}) as any; diff --git a/crates/oxc_codegen/tests/integration/ts.rs b/crates/oxc_codegen/tests/integration/ts.rs index 1ee5d448b786f..69c805f7e1b7f 100644 --- a/crates/oxc_codegen/tests/integration/ts.rs +++ b/crates/oxc_codegen/tests/integration/ts.rs @@ -50,7 +50,10 @@ export type Component< > = | ConcreteComponent | ComponentPublicInstanceConstructor -" +", +"(a || b) as any", +"(a ** b) as any", +"(function g() {}) as any", ]; snapshot("ts", &cases);