Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: drop unused local variables #2360

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion internal/bundler/bundler_dce_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2777,7 +2777,7 @@ func TestConstValueInliningNoBundle(t *testing.T) {
`,
"/exprs-before.js": `
function nested() {
const x = [, '', {}, 0n, /./, function() {}, () => {}]
const x_REMOVE = [, '', {}, 0n, /./, function() {}, () => {}]
const y_REMOVE = 1
function foo() {
return y_REMOVE
Expand Down
3 changes: 0 additions & 3 deletions internal/bundler/snapshots/snapshots_dce.txt
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,6 @@ x = [1, 1];

---------- /out/exprs-before.js ----------
function nested() {
const x = [, "", {}, 0n, /./, function() {
}, () => {
}];
function foo() {
return 1;
}
Expand Down
45 changes: 45 additions & 0 deletions internal/js_parser/js_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -7702,6 +7702,36 @@ func (p *parser) mangleStmts(stmts []js_ast.Stmt, kind stmtsKind) []js_ast.Stmt
}

case *js_ast.SLocal:
// Drop unused local variables
//
// The declaration must not be exported. We can't just check for the
// "export" keyword because something might do "export {id};" later on.
// Instead we just ignore all top-level declarations for now. That means
// this optimization currently only applies in nested scopes.
//
// Ignore declarations if the scope is shadowed by a direct "eval" call.
// The eval'd code may indirectly reference this symbol and the actual
// use count may be greater than 0.
if p.currentScope != p.moduleScope && !p.currentScope.ContainsDirectEval {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this costs too much, I think this condition could be p.currentScope.Parent == p.moduleScope && !p.currentScope.ContainsDirectEval instead.

// Ignore "var" declarations unless we are running in function body.
// Because we may not have visited all of their uses yet by this point.
if s.Kind != js_ast.LocalVar || kind == stmtsFnBody {
newDecls := make([]js_ast.Decl, 0)
for _, decl := range s.Decls {
if id, ok := decl.Binding.Data.(*js_ast.BIdentifier); ok {
if !p.isSymbolUsed(id.Ref, s.Kind == js_ast.LocalVar) && (decl.ValueOrNil.Data == nil || p.exprCanBeRemovedIfUnused(decl.ValueOrNil)) {
continue
}
}
newDecls = append(newDecls, decl)
}
if len(newDecls) == 0 {
continue
}
s.Decls = newDecls
}
}

// Merge adjacent local statements
if len(result) > 0 {
prevStmt := result[len(result)-1]
Expand Down Expand Up @@ -8090,6 +8120,21 @@ func (p *parser) mangleStmts(stmts []js_ast.Stmt, kind stmtsKind) []js_ast.Stmt
return result
}

func (p *parser) isSymbolUsed(ref js_ast.Ref, checkMerged bool) bool {
for {
symbol := p.symbols[ref.InnerIndex]
if symbol.UseCountEstimate > 0 {
return true
}
if !checkMerged || symbol.Link == js_ast.InvalidRef {
break
}

ref = symbol.Link
}
return false
}

func (p *parser) substituteSingleUseSymbolInStmt(stmt js_ast.Stmt, ref js_ast.Ref, replacement js_ast.Expr) bool {
var expr *js_ast.Expr

Expand Down
28 changes: 24 additions & 4 deletions internal/js_parser/js_parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2964,7 +2964,7 @@ func TestMangleIndex(t *testing.T) {
func TestMangleBlock(t *testing.T) {
expectPrintedMangle(t, "while(1) { while (1) {} }", "for (; ; )\n for (; ; )\n ;\n")
expectPrintedMangle(t, "while(1) { const x = y; }", "for (; ; ) {\n const x = y;\n}\n")
expectPrintedMangle(t, "while(1) { let x; }", "for (; ; ) {\n let x;\n}\n")
expectPrintedMangle(t, "while(1) { let x; }", "for (; ; )\n ;\n")
expectPrintedMangle(t, "while(1) { var x; }", "for (; ; )\n var x;\n")
expectPrintedMangle(t, "while(1) { class X {} }", "for (; ; ) {\n class X {\n }\n}\n")
expectPrintedMangle(t, "while(1) { function x() {} }", "for (; ; )\n var x = function() {\n };\n")
Expand Down Expand Up @@ -4187,7 +4187,7 @@ func TestMangleInlineLocals(t *testing.T) {
check("let x = arg0; return y ? x : z;", "let x = arg0;\nreturn y ? x : z;")
check("let x = arg0; return y ? z : x;", "let x = arg0;\nreturn y ? z : x;")
check("let x = arg0; return (arg1 ? 1 : 2) ? x : 3;", "return arg0;")
check("let x = arg0; return (arg1 ? 1 : 2) ? 3 : x;", "let x = arg0;\nreturn 3;")
check("let x = arg0; return (arg1 ? 1 : 2) ? 3 : x;", "return 3;")
check("let x = arg0; return (arg1 ? y : 1) ? x : 2;", "let x = arg0;\nreturn !arg1 || y ? x : 2;")
check("let x = arg0; return (arg1 ? 1 : y) ? x : 2;", "let x = arg0;\nreturn arg1 || y ? x : 2;")
check("let x = arg0; return (arg1 ? y : 1) ? 2 : x;", "let x = arg0;\nreturn !arg1 || y ? 2 : x;")
Expand Down Expand Up @@ -4344,8 +4344,8 @@ func TestTrimCodeInDeadControlFlow(t *testing.T) {
expectPrintedMangle(t, "if (1) a(); else { debugger }", "a();\n")

expectPrintedMangle(t, "if (0) {let a = 1} else a()", "a();\n")
expectPrintedMangle(t, "if (1) {let a = 1} else a()", "{\n let a = 1;\n}\n")
expectPrintedMangle(t, "if (0) a(); else {let a = 1}", "{\n let a = 1;\n}\n")
expectPrintedMangle(t, "if (1) {let a = 1} else a()", "")
expectPrintedMangle(t, "if (0) a(); else {let a = 1}", "")
expectPrintedMangle(t, "if (1) a(); else {let a = 1}", "a();\n")

expectPrintedMangle(t, "if (1) a(); else { var a = b }", "if (1)\n a();\nelse\n var a;\n")
Expand Down Expand Up @@ -5285,3 +5285,23 @@ func TestAutoPureForWeakMap(t *testing.T) {
expectPrinted(t, "new WeakMap([x, []])", "new WeakMap([x, []]);\n")
expectPrinted(t, "new WeakMap([[], x])", "new WeakMap([[], x]);\n")
}

func TestDropLocalUnusedVariable(t *testing.T) {
expectPrintedMangle(t, "var v = 0", "var v = 0;\n")
expectPrintedMangle(t, "let v = 0", "let v = 0;\n")
expectPrintedMangle(t, "const v = 0", "const v = 0;\n")
expectPrintedMangle(t, "{ var v = 0 }", "var v = 0;\n")
expectPrintedMangle(t, "{ let v = 0 }", "")
expectPrintedMangle(t, "{ let v = 3; let v2 = v + 5 }", "{\n let v2 = 3 + 5;\n}\n") // does not support multi-level
expectPrintedMangle(t, "{ const v = 3; const v2 = v + 5 }", "")
expectPrintedMangle(t, "{ const v = 0 }", "")
expectPrintedMangle(t, "{ const v = (() => 'foo')() }", "{\n const v = (() => \"foo\")();\n}\n")
expectPrintedMangle(t, "{ const v = /* #__PURE__ */ (() => 'foo')() }", "")
expectPrintedMangle(t, "{ const v = 0; console.log(v) }", "console.log(0);\n")
// expectPrintedMangle(t, "function f() { const v = 0; eval('v') }", "function f() {\n const v = 0;\n eval(\"v\");\n}\n")
Copy link
Contributor Author

@sapphi-red sapphi-red Jun 30, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test fails without this PR.
const v = 0; is dropped at here.

// Only keep this declaration if it's top-level or exported (which
// could be in a nested TypeScript namespace), otherwise erase it
if p.currentScope.Parent == nil || s.IsExport {
s.Decls[end] = d
end++
}

Created an issue: #2361

expectPrintedMangle(t, "function f() { var v }", "function f() {\n}\n")
expectPrintedMangle(t, "function f() { let v }", "function f() {\n}\n")
expectPrintedMangle(t, "function f() { var v; console.log(v); }", "function f() {\n var v;\n console.log(v);\n}\n")
expectPrintedMangle(t, "function f() { var v; function g(){ v = 2 } }", "function f() {\n var v;\n function g() {\n v = 2;\n }\n}\n")
expectPrintedMangle(t, "function f() { function g(){ v = 2 }; var v; }", "function f() {\n function g() {\n v = 2;\n }\n var v;\n}\n")
}
1 change: 1 addition & 0 deletions scripts/uglify-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ async function test_case(esbuild, test, basename) {
'let.js: issue_4229',
'let.js: issue_4245',
'let.js: use_before_init_3',
'let.js: issue_4276_1',
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


// Error difference
'dead-code.js: dead_code_2_should_warn',
Expand Down