Mark vars with /** @const */ pragma as consts so they can be eliminated.
authorSamuel Reed <samuel.trace.reed@gmail.com>
Tue, 19 Jan 2016 19:12:32 +0000 (13:12 -0600)
committerSamuel Reed <samuel.trace.reed@gmail.com>
Tue, 19 Jan 2016 19:23:02 +0000 (13:23 -0600)
Fixes older browser support for consts and allows more flexibility
in dead code removal.

lib/scope.js
test/compress/dead-code.js

index 5e93020..22fb150 100644 (file)
@@ -154,7 +154,7 @@ AST_Toplevel.DEFMETHOD("figure_out_scope", function(options){
         else if (node instanceof AST_SymbolVar
                  || node instanceof AST_SymbolConst) {
             var def = defun.def_variable(node);
-            def.constant = node instanceof AST_SymbolConst;
+            def.constant = node instanceof AST_SymbolConst || node.has_const_pragma();
             def.init = tw.parent().value;
         }
         else if (node instanceof AST_SymbolCatch) {
@@ -357,6 +357,16 @@ AST_Symbol.DEFMETHOD("global", function(){
     return this.definition().global;
 });
 
+AST_Symbol.DEFMETHOD("has_const_pragma", function() {
+    var token = this.scope.body[0] && this.scope.body[0].start;
+    var comments = token && token.comments_before;
+    if (comments && comments.length > 0) {
+        var last = comments[comments.length - 1];
+        return /@const/.test(last.value);
+    }
+    return false;
+})
+
 AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options){
     return defaults(options, {
         except      : [],
index 5009ae1..f79b04d 100644 (file)
@@ -87,3 +87,49 @@ dead_code_constant_boolean_should_warn_more: {
         var moo;\r
     }\r
 }\r
+\r
+dead_code_const_declaration: {\r
+    options = {\r
+        dead_code    : true,\r
+        loops        : true,\r
+        booleans     : true,\r
+        conditionals : true,\r
+        evaluate     : true\r
+    };\r
+    input: {\r
+        const CONST_FOO = false;\r
+        if (CONST_FOO) {\r
+            console.log("unreachable");\r
+            var moo;\r
+            function bar() {}\r
+        }\r
+    }\r
+    expect: {\r
+        const CONST_FOO = !1;\r
+        var moo;\r
+        function bar() {}\r
+    }\r
+}\r
+\r
+dead_code_const_annotation: {\r
+    options = {\r
+        dead_code    : true,\r
+        loops        : true,\r
+        booleans     : true,\r
+        conditionals : true,\r
+        evaluate     : true\r
+    };\r
+    input: {\r
+        /** @const*/ var CONST_FOO_ANN = false;\r
+        if (CONST_FOO_ANN) {\r
+            console.log("unreachable");\r
+            var moo;\r
+            function bar() {}\r
+        }\r
+    }\r
+    expect: {\r
+        var CONST_FOO_ANN = !1;\r
+        var moo;\r
+        function bar() {}\r
+    }\r
+}\r