fix(codegen): format new expression + call expression with the correct parentheses (#2330)

closes #2328
This commit is contained in:
Boshen 2024-02-06 22:06:12 +08:00 committed by GitHub
parent 40e9541cec
commit 721f6cb74e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 22 additions and 3 deletions

View file

@ -4,7 +4,8 @@ bitflags! {
#[derive(Debug, Clone, Copy)]
pub struct Context: u8 {
/// [In]
const In = 1 << 0;
const In = 1 << 0;
const FORBID_CALL = 1 << 1;
}
}
@ -20,12 +21,23 @@ impl Context {
self.contains(Self::In)
}
#[inline]
pub fn has_forbid_call(self) -> bool {
self.contains(Self::FORBID_CALL)
}
#[inline]
#[must_use]
pub fn and_in(self, include: bool) -> Self {
self.and(Self::In, include)
}
#[inline]
#[must_use]
pub fn and_forbid_call(self, include: bool) -> Self {
self.and(Self::FORBID_CALL, include)
}
#[inline]
fn and(self, flag: Self, set: bool) -> Self {
if set {

View file

@ -1254,7 +1254,9 @@ impl<'a, const MINIFY: bool> GenExpr<MINIFY> for PrivateFieldExpression<'a> {
impl<'a, const MINIFY: bool> GenExpr<MINIFY> for CallExpression<'a> {
fn gen_expr(&self, p: &mut Codegen<{ MINIFY }>, precedence: Precedence, ctx: Context) {
p.wrap(precedence > self.precedence(), |p| {
let wrap = precedence > self.precedence() || ctx.has_forbid_call();
let ctx = ctx.and_forbid_call(false);
p.wrap(wrap, |p| {
self.callee.gen_expr(p, self.precedence(), ctx);
if self.optional {
p.print_str(b"?.");
@ -1800,7 +1802,7 @@ impl<'a, const MINIFY: bool> GenExpr<MINIFY> for NewExpression<'a> {
fn gen_expr(&self, p: &mut Codegen<{ MINIFY }>, precedence: Precedence, ctx: Context) {
p.wrap(precedence > self.precedence(), |p| {
p.print_str(b"new ");
self.callee.gen_expr(p, self.precedence(), ctx);
self.callee.gen_expr(p, Precedence::NewWithoutArgs, ctx.and_forbid_call(true));
p.wrap(true, |p| {
p.print_list(&self.arguments, ctx);
});

View file

@ -108,3 +108,8 @@ fn module_decl() {
test("import {} from './foo.js' with {}", "import './foo.js' with {\n};\n");
test("export * from './foo.js' with {}", "export * from './foo.js' with {\n};\n");
}
#[test]
fn new_expr() {
test("new (foo()).bar();", "new (foo()).bar();\n");
}