From 62d2817d6cd29189e65aaba531c7c3ceb1792a65 Mon Sep 17 00:00:00 2001 From: "Alex Lam S.L" Date: Tue, 28 Nov 2017 22:54:21 +0800 Subject: [PATCH] reduce `this` in block scopes (#2526) fixes #2455 --- lib/ast.js | 4 ++-- lib/compress.js | 4 +++- lib/scope.js | 6 +----- test/compress/reduce_vars.js | 18 ++++++++++++++++++ 4 files changed, 24 insertions(+), 8 deletions(-) diff --git a/lib/ast.js b/lib/ast.js index 172e1964..4db6c13d 100644 --- a/lib/ast.js +++ b/lib/ast.js @@ -313,9 +313,9 @@ var AST_Scope = DEFNODE("Scope", "variables functions uses_with uses_eval parent enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes", cname: "[integer/S] current index for mangling variables (used internally by the mangler)", }, - get_defun_scope: function () { + get_defun_scope: function() { var self = this; - while (self.is_block_scope() && self.parent_scope) { + while (self.is_block_scope()) { self = self.parent_scope; } return self; diff --git a/lib/compress.js b/lib/compress.js index 550cbbef..07626336 100644 --- a/lib/compress.js +++ b/lib/compress.js @@ -4645,8 +4645,10 @@ merge(Compressor.prototype, { var init; if (fixed instanceof AST_This) { if (!(d.orig[0] instanceof AST_SymbolFunarg) - && all(d.references, function(ref) { + && all(d.references, d.scope.is_block_scope() ? function(ref) { return d.scope === ref.scope; + } : function(ref) { + return d.scope === ref.scope.get_defun_scope(); })) { init = fixed; } diff --git a/lib/scope.js b/lib/scope.js index 40ab8445..01f7ee4f 100644 --- a/lib/scope.js +++ b/lib/scope.js @@ -183,11 +183,7 @@ AST_Toplevel.DEFMETHOD("figure_out_scope", function(options){ // scope when we encounter the AST_Defun node (which is // instanceof AST_Scope) but we get to the symbol a bit // later. - var parent_lambda = defun.parent_scope; - while (parent_lambda.is_block_scope()) { - parent_lambda = parent_lambda.parent_scope; - } - mark_export((node.scope = parent_lambda).def_function(node), 1); + mark_export((node.scope = defun.parent_scope.get_defun_scope()).def_function(node), 1); } else if (node instanceof AST_SymbolClass) { mark_export(defun.def_variable(node), 1); diff --git a/test/compress/reduce_vars.js b/test/compress/reduce_vars.js index a246709b..55b4485c 100644 --- a/test/compress/reduce_vars.js +++ b/test/compress/reduce_vars.js @@ -4887,3 +4887,21 @@ issue_2416: { expect_stdout: "Foo" node_version: ">=6" } + +issue_2455: { + options = { + reduce_vars: true, + unused: true, + } + input: { + function foo() { + var that = this; + for (;;) that.bar(); + } + } + expect: { + function foo() { + for (;;) this.bar(); + } + } +}