Skip to content

Commit

Permalink
JS: don't remove group around optional chaining expressions when it's…
Browse files Browse the repository at this point in the history
… the left side of a dot expression, fixes #724
  • Loading branch information
tdewolff committed Jul 10, 2024
1 parent 3354711 commit 9fab517
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
11 changes: 8 additions & 3 deletions js/js.go
Original file line number Diff line number Diff line change
Expand Up @@ -1039,6 +1039,7 @@ func (m *jsMinifier) minifyExpr(i js.IExpr, prec js.OpPrec) {
m.minifyExpr(expr.X, unaryPrecMap[expr.Op])
}
case *js.DotExpr:
optionalLeft := false
if group, ok := expr.X.(*js.GroupExpr); ok {
if lit, ok := group.X.(*js.LiteralExpr); ok && (lit.TokenType == js.DecimalToken || lit.TokenType == js.IntegerToken) {
if lit.TokenType == js.DecimalToken {
Expand All @@ -1050,12 +1051,16 @@ func (m *jsMinifier) minifyExpr(i js.IExpr, prec js.OpPrec) {
m.write(dotBytes)
m.write(expr.Y.Data)
break
} else if dot, ok := group.X.(*js.DotExpr); ok {
optionalLeft = dot.Optional
} else if call, ok := group.X.(*js.CallExpr); ok {
optionalLeft = call.Optional
}
}
if prec < js.OpMember {
m.minifyExpr(expr.X, js.OpCall)
} else {
if js.OpMember <= prec || optionalLeft {
m.minifyExpr(expr.X, js.OpMember)
} else {
m.minifyExpr(expr.X, js.OpCall)
}
if expr.Optional {
m.write(questionBytes)
Expand Down
7 changes: 4 additions & 3 deletions js/js_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -545,8 +545,9 @@ func TestJS(t *testing.T) {
{`(a()).b(c)`, `a().b(c)`},
{`(a()[5]).b(c)`, `a()[5].b(c)`},
{"(a()`tmpl`).b(c)", "a()`tmpl`.b(c)"},
{`(a?.b).c(d)`, `a?.b.c(d)`},
{`(a?.(c)).d(e)`, `a?.(c).d(e)`},
{`(a?.b).c(d)`, `(a?.b).c(d)`},
{`(a?.(c)).d(e)`, `(a?.(c)).d(e)`},
{`(a?.b.c).d`, `a?.b.c.d`},
{`class a extends (new b){}`, `class a extends new b{}`},
{`(new.target)`, `new.target`},
{`(import.meta)`, `(import.meta)`},
Expand Down Expand Up @@ -756,7 +757,7 @@ func TestJS(t *testing.T) {
{`/[^a\-\--\-\-\-]/`, `/[^a\-\-----]/`},

// edge-cases
{`let o=null;try{o=(o?.a).b||"FAIL"}catch(x){}console.log(o||"PASS")`, `let o=null;try{o=o?.a.b||"FAIL"}catch{}console.log(o||"PASS")`},
{`let o=null;try{o=(o?.a).b||"FAIL"}catch(x){}console.log(o||"PASS")`, `let o=null;try{o=(o?.a).b||"FAIL"}catch{}console.log(o||"PASS")`},
{`1..a`, `1..a`},
{`1.5.a`, `1.5.a`},
{`1e4.a`, `1e4.a`},
Expand Down

0 comments on commit 9fab517

Please sign in to comment.