improve AST_ConciseMethod compression (#2202)

p(){return x;} ---> p:()=>x

Optimization subject to the `compress` option `arrows`.
This commit is contained in:
Alex Lam S.L
2017-07-06 01:21:04 +08:00
committed by GitHub
parent fdbb1d09ef
commit f5c46db738
4 changed files with 177 additions and 20 deletions

View File

@@ -4596,7 +4596,7 @@ merge(Compressor.prototype, {
var has_special_symbol = false;
self.walk(new TreeWalker(function(node) {
if (has_special_symbol) return true;
if (node instanceof AST_Symbol && !node.definition()) {
if (node instanceof AST_Super || node instanceof AST_This) {
has_special_symbol = true;
return true;
}
@@ -4656,6 +4656,36 @@ merge(Compressor.prototype, {
return self;
});
AST_Lambda.DEFMETHOD("contains_this", function() {
var result;
var self = this;
self.walk(new TreeWalker(function(node) {
if (result) return true;
if (node instanceof AST_This) return result = true;
if (node !== self && node instanceof AST_Scope && !(node instanceof AST_Arrow)) return true;
}));
return result;
});
OPT(AST_ConciseMethod, function(self, compressor){
// p(){return x;} ---> p:()=>x
if (compressor.option("arrows")
&& compressor.parent() instanceof AST_Object
&& self.value.body.length == 1
&& self.value.body[0] instanceof AST_Return
&& self.value.body[0].value
&& !self.value.contains_this()) {
var arrow = make_node(AST_Arrow, self.value, self.value);
arrow.async = self.async;
arrow.is_generator = self.is_generator;
return make_node(AST_ObjectKeyVal, self, {
key: self.key instanceof AST_SymbolMethod ? self.key.name : self.key,
value: arrow
});
}
return self;
});
OPT(AST_ObjectKeyVal, function(self, compressor){
// p:function(){} ---> p(){}
// p:function*(){} ---> *p(){}
@@ -4667,7 +4697,7 @@ merge(Compressor.prototype, {
var value = self.value;
var is_arrow_with_block = value instanceof AST_Arrow
&& Array.isArray(value.body)
&& !contains_this(value);
&& !value.contains_this();
if ((is_arrow_with_block || value instanceof AST_Function) && !value.name) {
return make_node(AST_ConciseMethod, self, {
async: value.async,
@@ -4680,16 +4710,5 @@ merge(Compressor.prototype, {
}
}
return self;
function contains_this(node) {
var result;
var tw = new TreeWalker(function(node) {
if (node instanceof AST_This) {
return result = true;
}
});
node.walk(tw);
return result;
}
});
})();