Skip to content

Commit

Permalink
JS: keep assignments with side-effects when removing let/const declar…
Browse files Browse the repository at this point in the history
…ation in block, fixes #487
  • Loading branch information
tdewolff committed Jun 4, 2022
1 parent b31a40e commit c1fb3fc
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
1 change: 1 addition & 0 deletions js/js_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -770,6 +770,7 @@ func TestJS(t *testing.T) {
{`var a=1;g();a=2;let b=3`, `var a=1;g(),a=2;let b=3`}, // #474
{`if(!(0<1&&1<2)){throw new Error()}`, `if(!(0<1&&1<2))throw new Error`}, // #479
{`class A{set x(e){}}`, `class A{set x(e){}}`}, // #481
{`if(a){let b=c(d)}`, `a&&c(d)`}, // #487
}

m := minify.New()
Expand Down
22 changes: 17 additions & 5 deletions js/stmtlist.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,12 +111,24 @@ func optimizeStmt(i js.IStmt) js.IStmt {
// merge body and remove braces if it is not a lexical declaration
blockStmt.List = optimizeStmtList(blockStmt.List, defaultBlock)
if len(blockStmt.List) == 1 {
varDecl, isVarDecl := blockStmt.List[0].(*js.VarDecl)
_, isClassDecl := blockStmt.List[0].(*js.ClassDecl)
if !isClassDecl && (!isVarDecl || varDecl.TokenType == js.VarToken) {
return optimizeStmt(blockStmt.List[0])
if _, ok := blockStmt.List[0].(*js.ClassDecl); ok {
return &js.EmptyStmt{}
} else if varDecl, ok := blockStmt.List[0].(*js.VarDecl); ok && varDecl.TokenType != js.VarToken {
// remove let or const declaration in otherwise empty scope, but keep assignments
exprs := []js.IExpr{}
for _, item := range varDecl.List {
if item.Default != nil && hasSideEffects(item.Default) {
exprs = append(exprs, item.Default)
}
}
if len(exprs) == 0 {
return &js.EmptyStmt{}
} else if len(exprs) == 1 {
return &js.ExprStmt{exprs[0]}
}
return &js.ExprStmt{&js.CommaExpr{exprs}}
}
return &js.EmptyStmt{}
return optimizeStmt(blockStmt.List[0])
} else if len(blockStmt.List) == 0 {
return &js.EmptyStmt{}
}
Expand Down

0 comments on commit c1fb3fc

Please sign in to comment.