You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Instead of implementing custom recursive functions, use recursiveWalk
from a shared helper. It will automatically invoke one callback for
nested expressions (e.g. computed properties or defaults) and another
callback for any bound names.
Copy file name to clipboardExpand all lines: tools/acorn-optimizer.mjs
+26-37Lines changed: 26 additions & 37 deletions
Original file line number
Diff line number
Diff line change
@@ -100,6 +100,25 @@ function dump(node) {
100
100
console.log(JSON.stringify(node,null,' '));
101
101
}
102
102
103
+
// Traverse a pattern node (identifier, object/array pattern, etc) invoking onExpr on any nested expressions and onBoundIdent on any bound identifiers.
104
+
functionwalkPattern(node,onExpr,onBoundIdent){
105
+
recursiveWalk(node,{
106
+
AssignmentPattern(node,c){
107
+
c(node.left);
108
+
onExpr(node.right);
109
+
},
110
+
Property(node,c){
111
+
if(node.computed){
112
+
onExpr(node.key);
113
+
}
114
+
c(node.value);
115
+
},
116
+
Identifier({name}){
117
+
onBoundIdent(name);
118
+
},
119
+
});
120
+
}
121
+
103
122
functionhasSideEffects(node){
104
123
// Conservative analysis.
105
124
lethas=false;
@@ -270,29 +289,12 @@ function JSDCE(ast, aggressive) {
270
289
}
271
290
constscope={};
272
291
scopes.push(scope);
273
-
node.params.forEach(functiontraverse(param){
274
-
if(param.type==='RestElement'){
275
-
param=param.argument;
276
-
}
277
-
if(param.type==='AssignmentPattern'){
278
-
c(param.right);
279
-
param=param.left;
280
-
}
281
-
if(param.type==='ArrayPattern'){
282
-
for(varelemofparam.elements){
283
-
if(elem)traverse(elem);
284
-
}
285
-
}elseif(param.type==='ObjectPattern'){
286
-
for(varpropofparam.properties){
287
-
traverse(prop.key);
288
-
}
289
-
}else{
290
-
assert(param.type==='Identifier',param.type);
291
-
constname=param.name;
292
+
for(constparamofnode.params){
293
+
walkPattern(param,c,(name)=>{
292
294
ensureData(scope,name).def=1;
293
295
scope[name].param=1;
294
-
}
295
-
});
296
+
});
297
+
}
296
298
c(node.body);
297
299
// we can ignore self-references, i.e., references to ourselves inside
298
300
// ourselves, for named defined (defun) functions
@@ -316,22 +318,9 @@ function JSDCE(ast, aggressive) {
316
318
317
319
recursiveWalk(ast,{
318
320
VariableDeclarator(node,c){
319
-
functiontraverse(id){
320
-
if(id.type==='ObjectPattern'){
321
-
for(constpropofid.properties){
322
-
traverse(prop.value);
323
-
}
324
-
}elseif(id.type==='ArrayPattern'){
325
-
for(constelemofid.elements){
326
-
if(elem)traverse(elem);
327
-
}
328
-
}else{
329
-
assertAt(id.type==='Identifier',id,`expected Identifier but found ${id.type}`);
0 commit comments