terser 4.8.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/scope.js ADDED
@@ -0,0 +1,965 @@
1
+ /***********************************************************************
2
+
3
+ A JavaScript tokenizer / parser / beautifier / compressor.
4
+ https://github.com/mishoo/UglifyJS2
5
+
6
+ -------------------------------- (C) ---------------------------------
7
+
8
+ Author: Mihai Bazon
9
+ <mihai.bazon@gmail.com>
10
+ http://mihai.bazon.net/blog
11
+
12
+ Distributed under the BSD license:
13
+
14
+ Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
15
+
16
+ Redistribution and use in source and binary forms, with or without
17
+ modification, are permitted provided that the following conditions
18
+ are met:
19
+
20
+ * Redistributions of source code must retain the above
21
+ copyright notice, this list of conditions and the following
22
+ disclaimer.
23
+
24
+ * Redistributions in binary form must reproduce the above
25
+ copyright notice, this list of conditions and the following
26
+ disclaimer in the documentation and/or other materials
27
+ provided with the distribution.
28
+
29
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
30
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
32
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
33
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
34
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
35
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
36
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
38
+ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
39
+ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40
+ SUCH DAMAGE.
41
+
42
+ ***********************************************************************/
43
+
44
+ "use strict";
45
+
46
+ import {
47
+ defaults,
48
+ keep_name,
49
+ mergeSort,
50
+ push_uniq,
51
+ make_node,
52
+ return_false,
53
+ return_this,
54
+ return_true,
55
+ string_template,
56
+ } from "./utils/index.js";
57
+ import {
58
+ AST_Arrow,
59
+ AST_Block,
60
+ AST_Call,
61
+ AST_Catch,
62
+ AST_Class,
63
+ AST_Conditional,
64
+ AST_DefClass,
65
+ AST_Defun,
66
+ AST_Destructuring,
67
+ AST_Dot,
68
+ AST_Export,
69
+ AST_For,
70
+ AST_ForIn,
71
+ AST_Function,
72
+ AST_Import,
73
+ AST_IterationStatement,
74
+ AST_Label,
75
+ AST_LabeledStatement,
76
+ AST_LabelRef,
77
+ AST_Lambda,
78
+ AST_LoopControl,
79
+ AST_NameMapping,
80
+ AST_Node,
81
+ AST_Scope,
82
+ AST_Sequence,
83
+ AST_String,
84
+ AST_Sub,
85
+ AST_Switch,
86
+ AST_SwitchBranch,
87
+ AST_Symbol,
88
+ AST_SymbolBlockDeclaration,
89
+ AST_SymbolCatch,
90
+ AST_SymbolClass,
91
+ AST_SymbolConst,
92
+ AST_SymbolDefClass,
93
+ AST_SymbolDefun,
94
+ AST_SymbolExport,
95
+ AST_SymbolFunarg,
96
+ AST_SymbolImport,
97
+ AST_SymbolLambda,
98
+ AST_SymbolLet,
99
+ AST_SymbolMethod,
100
+ AST_SymbolRef,
101
+ AST_SymbolVar,
102
+ AST_Toplevel,
103
+ AST_VarDef,
104
+ AST_With,
105
+ TreeWalker,
106
+ walk
107
+ } from "./ast.js";
108
+ import {
109
+ RESERVED_WORDS,
110
+ js_error,
111
+ } from "./parse.js";
112
+
113
+ const MASK_EXPORT_DONT_MANGLE = 1 << 0;
114
+ const MASK_EXPORT_WANT_MANGLE = 1 << 1;
115
+
116
+ let function_defs = null;
117
+ let unmangleable_names = null;
118
+
119
+ class SymbolDef {
120
+ constructor(scope, orig, init) {
121
+ this.name = orig.name;
122
+ this.orig = [ orig ];
123
+ this.init = init;
124
+ this.eliminated = 0;
125
+ this.assignments = 0;
126
+ this.scope = scope;
127
+ this.replaced = 0;
128
+ this.global = false;
129
+ this.export = 0;
130
+ this.mangled_name = null;
131
+ this.undeclared = false;
132
+ this.id = SymbolDef.next_id++;
133
+ this.chained = false;
134
+ this.direct_access = false;
135
+ this.escaped = 0;
136
+ this.recursive_refs = 0;
137
+ this.references = [];
138
+ this.should_replace = undefined;
139
+ this.single_use = false;
140
+ this.fixed = false;
141
+ Object.seal(this);
142
+ }
143
+ fixed_value() {
144
+ if (!this.fixed || this.fixed instanceof AST_Node) return this.fixed;
145
+ return this.fixed();
146
+ }
147
+ unmangleable(options) {
148
+ if (!options) options = {};
149
+
150
+ if (
151
+ function_defs &&
152
+ function_defs.has(this.id) &&
153
+ keep_name(options.keep_fnames, this.orig[0].name)
154
+ ) return true;
155
+
156
+ return this.global && !options.toplevel
157
+ || (this.export & MASK_EXPORT_DONT_MANGLE)
158
+ || this.undeclared
159
+ || !options.eval && this.scope.pinned()
160
+ || (this.orig[0] instanceof AST_SymbolLambda
161
+ || this.orig[0] instanceof AST_SymbolDefun) && keep_name(options.keep_fnames, this.orig[0].name)
162
+ || this.orig[0] instanceof AST_SymbolMethod
163
+ || (this.orig[0] instanceof AST_SymbolClass
164
+ || this.orig[0] instanceof AST_SymbolDefClass) && keep_name(options.keep_classnames, this.orig[0].name);
165
+ }
166
+ mangle(options) {
167
+ const cache = options.cache && options.cache.props;
168
+ if (this.global && cache && cache.has(this.name)) {
169
+ this.mangled_name = cache.get(this.name);
170
+ } else if (!this.mangled_name && !this.unmangleable(options)) {
171
+ var s = this.scope;
172
+ var sym = this.orig[0];
173
+ if (options.ie8 && sym instanceof AST_SymbolLambda)
174
+ s = s.parent_scope;
175
+ const redefinition = redefined_catch_def(this);
176
+ this.mangled_name = redefinition
177
+ ? redefinition.mangled_name || redefinition.name
178
+ : s.next_mangled(options, this);
179
+ if (this.global && cache) {
180
+ cache.set(this.name, this.mangled_name);
181
+ }
182
+ }
183
+ }
184
+ }
185
+
186
+ SymbolDef.next_id = 1;
187
+
188
+ function redefined_catch_def(def) {
189
+ if (def.orig[0] instanceof AST_SymbolCatch
190
+ && def.scope.is_block_scope()
191
+ ) {
192
+ return def.scope.get_defun_scope().variables.get(def.name);
193
+ }
194
+ }
195
+
196
+ AST_Scope.DEFMETHOD("figure_out_scope", function(options, { parent_scope = null, toplevel = this } = {}) {
197
+ options = defaults(options, {
198
+ cache: null,
199
+ ie8: false,
200
+ safari10: false,
201
+ });
202
+
203
+ if (!(toplevel instanceof AST_Toplevel)) {
204
+ throw new Error("Invalid toplevel scope");
205
+ }
206
+
207
+ // pass 1: setup scope chaining and handle definitions
208
+ var scope = this.parent_scope = parent_scope;
209
+ var labels = new Map();
210
+ var defun = null;
211
+ var in_destructuring = null;
212
+ var for_scopes = [];
213
+ var tw = new TreeWalker((node, descend) => {
214
+ if (node.is_block_scope()) {
215
+ const save_scope = scope;
216
+ node.block_scope = scope = new AST_Scope(node);
217
+ scope._block_scope = true;
218
+ // AST_Try in the AST sadly *is* (not has) a body itself,
219
+ // and its catch and finally branches are children of the AST_Try itself
220
+ const parent_scope = node instanceof AST_Catch
221
+ ? save_scope.parent_scope
222
+ : save_scope;
223
+ scope.init_scope_vars(parent_scope);
224
+ scope.uses_with = save_scope.uses_with;
225
+ scope.uses_eval = save_scope.uses_eval;
226
+ if (options.safari10) {
227
+ if (node instanceof AST_For || node instanceof AST_ForIn) {
228
+ for_scopes.push(scope);
229
+ }
230
+ }
231
+
232
+ if (node instanceof AST_Switch) {
233
+ // XXX: HACK! Ensure the switch expression gets the correct scope (the parent scope) and the body gets the contained scope
234
+ // AST_Switch has a scope within the body, but it itself "is a block scope"
235
+ // This means the switched expression has to belong to the outer scope
236
+ // while the body inside belongs to the switch itself.
237
+ // This is pretty nasty and warrants an AST change similar to AST_Try (read above)
238
+ const the_block_scope = scope;
239
+ scope = save_scope;
240
+ node.expression.walk(tw);
241
+ scope = the_block_scope;
242
+ for (let i = 0; i < node.body.length; i++) {
243
+ node.body[i].walk(tw);
244
+ }
245
+ } else {
246
+ descend();
247
+ }
248
+ scope = save_scope;
249
+ return true;
250
+ }
251
+ if (node instanceof AST_Destructuring) {
252
+ const save_destructuring = in_destructuring;
253
+ in_destructuring = node;
254
+ descend();
255
+ in_destructuring = save_destructuring;
256
+ return true;
257
+ }
258
+ if (node instanceof AST_Scope) {
259
+ node.init_scope_vars(scope);
260
+ var save_scope = scope;
261
+ var save_defun = defun;
262
+ var save_labels = labels;
263
+ defun = scope = node;
264
+ labels = new Map();
265
+ descend();
266
+ scope = save_scope;
267
+ defun = save_defun;
268
+ labels = save_labels;
269
+ return true; // don't descend again in TreeWalker
270
+ }
271
+ if (node instanceof AST_LabeledStatement) {
272
+ var l = node.label;
273
+ if (labels.has(l.name)) {
274
+ throw new Error(string_template("Label {name} defined twice", l));
275
+ }
276
+ labels.set(l.name, l);
277
+ descend();
278
+ labels.delete(l.name);
279
+ return true; // no descend again
280
+ }
281
+ if (node instanceof AST_With) {
282
+ for (var s = scope; s; s = s.parent_scope)
283
+ s.uses_with = true;
284
+ return;
285
+ }
286
+ if (node instanceof AST_Symbol) {
287
+ node.scope = scope;
288
+ }
289
+ if (node instanceof AST_Label) {
290
+ node.thedef = node;
291
+ node.references = [];
292
+ }
293
+ if (node instanceof AST_SymbolLambda) {
294
+ defun.def_function(node, node.name == "arguments" ? undefined : defun);
295
+ } else if (node instanceof AST_SymbolDefun) {
296
+ // Careful here, the scope where this should be defined is
297
+ // the parent scope. The reason is that we enter a new
298
+ // scope when we encounter the AST_Defun node (which is
299
+ // instanceof AST_Scope) but we get to the symbol a bit
300
+ // later.
301
+ mark_export((node.scope = defun.parent_scope.get_defun_scope()).def_function(node, defun), 1);
302
+ } else if (node instanceof AST_SymbolClass) {
303
+ mark_export(defun.def_variable(node, defun), 1);
304
+ } else if (node instanceof AST_SymbolImport) {
305
+ scope.def_variable(node);
306
+ } else if (node instanceof AST_SymbolDefClass) {
307
+ // This deals with the name of the class being available
308
+ // inside the class.
309
+ mark_export((node.scope = defun.parent_scope).def_function(node, defun), 1);
310
+ } else if (
311
+ node instanceof AST_SymbolVar
312
+ || node instanceof AST_SymbolLet
313
+ || node instanceof AST_SymbolConst
314
+ || node instanceof AST_SymbolCatch
315
+ ) {
316
+ var def;
317
+ if (node instanceof AST_SymbolBlockDeclaration) {
318
+ def = scope.def_variable(node, null);
319
+ } else {
320
+ def = defun.def_variable(node, node.TYPE == "SymbolVar" ? null : undefined);
321
+ }
322
+ if (!def.orig.every((sym) => {
323
+ if (sym === node) return true;
324
+ if (node instanceof AST_SymbolBlockDeclaration) {
325
+ return sym instanceof AST_SymbolLambda;
326
+ }
327
+ return !(sym instanceof AST_SymbolLet || sym instanceof AST_SymbolConst);
328
+ })) {
329
+ js_error(
330
+ `"${node.name}" is redeclared`,
331
+ node.start.file,
332
+ node.start.line,
333
+ node.start.col,
334
+ node.start.pos
335
+ );
336
+ }
337
+ if (!(node instanceof AST_SymbolFunarg)) mark_export(def, 2);
338
+ if (defun !== scope) {
339
+ node.mark_enclosed();
340
+ var def = scope.find_variable(node);
341
+ if (node.thedef !== def) {
342
+ node.thedef = def;
343
+ node.reference();
344
+ }
345
+ }
346
+ } else if (node instanceof AST_LabelRef) {
347
+ var sym = labels.get(node.name);
348
+ if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", {
349
+ name: node.name,
350
+ line: node.start.line,
351
+ col: node.start.col
352
+ }));
353
+ node.thedef = sym;
354
+ }
355
+ if (!(scope instanceof AST_Toplevel) && (node instanceof AST_Export || node instanceof AST_Import)) {
356
+ js_error(
357
+ `"${node.TYPE}" statement may only appear at the top level`,
358
+ node.start.file,
359
+ node.start.line,
360
+ node.start.col,
361
+ node.start.pos
362
+ );
363
+ }
364
+ });
365
+ this.walk(tw);
366
+
367
+ function mark_export(def, level) {
368
+ if (in_destructuring) {
369
+ var i = 0;
370
+ do {
371
+ level++;
372
+ } while (tw.parent(i++) !== in_destructuring);
373
+ }
374
+ var node = tw.parent(level);
375
+ if (def.export = node instanceof AST_Export ? MASK_EXPORT_DONT_MANGLE : 0) {
376
+ var exported = node.exported_definition;
377
+ if ((exported instanceof AST_Defun || exported instanceof AST_DefClass) && node.is_default) {
378
+ def.export = MASK_EXPORT_WANT_MANGLE;
379
+ }
380
+ }
381
+ }
382
+
383
+ // pass 2: find back references and eval
384
+ const is_toplevel = this instanceof AST_Toplevel;
385
+ if (is_toplevel) {
386
+ this.globals = new Map();
387
+ }
388
+
389
+ var tw = new TreeWalker(node => {
390
+ if (node instanceof AST_LoopControl && node.label) {
391
+ node.label.thedef.references.push(node);
392
+ return true;
393
+ }
394
+ if (node instanceof AST_SymbolRef) {
395
+ var name = node.name;
396
+ if (name == "eval" && tw.parent() instanceof AST_Call) {
397
+ for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) {
398
+ s.uses_eval = true;
399
+ }
400
+ }
401
+ var sym;
402
+ if (tw.parent() instanceof AST_NameMapping && tw.parent(1).module_name
403
+ || !(sym = node.scope.find_variable(name))) {
404
+
405
+ sym = toplevel.def_global(node);
406
+ if (node instanceof AST_SymbolExport) sym.export = MASK_EXPORT_DONT_MANGLE;
407
+ } else if (sym.scope instanceof AST_Lambda && name == "arguments") {
408
+ sym.scope.uses_arguments = true;
409
+ }
410
+ node.thedef = sym;
411
+ node.reference();
412
+ if (node.scope.is_block_scope()
413
+ && !(sym.orig[0] instanceof AST_SymbolBlockDeclaration)) {
414
+ node.scope = node.scope.get_defun_scope();
415
+ }
416
+ return true;
417
+ }
418
+ // ensure mangling works if catch reuses a scope variable
419
+ var def;
420
+ if (node instanceof AST_SymbolCatch && (def = redefined_catch_def(node.definition()))) {
421
+ var s = node.scope;
422
+ while (s) {
423
+ push_uniq(s.enclosed, def);
424
+ if (s === def.scope) break;
425
+ s = s.parent_scope;
426
+ }
427
+ }
428
+ });
429
+ this.walk(tw);
430
+
431
+ // pass 3: work around IE8 and Safari catch scope bugs
432
+ if (options.ie8 || options.safari10) {
433
+ walk(this, node => {
434
+ if (node instanceof AST_SymbolCatch) {
435
+ var name = node.name;
436
+ var refs = node.thedef.references;
437
+ var scope = node.scope.get_defun_scope();
438
+ var def = scope.find_variable(name)
439
+ || toplevel.globals.get(name)
440
+ || scope.def_variable(node);
441
+ refs.forEach(function(ref) {
442
+ ref.thedef = def;
443
+ ref.reference();
444
+ });
445
+ node.thedef = def;
446
+ node.reference();
447
+ return true;
448
+ }
449
+ });
450
+ }
451
+
452
+ // pass 4: add symbol definitions to loop scopes
453
+ // Safari/Webkit bug workaround - loop init let variable shadowing argument.
454
+ // https://github.com/mishoo/UglifyJS2/issues/1753
455
+ // https://bugs.webkit.org/show_bug.cgi?id=171041
456
+ if (options.safari10) {
457
+ for (const scope of for_scopes) {
458
+ scope.parent_scope.variables.forEach(function(def) {
459
+ push_uniq(scope.enclosed, def);
460
+ });
461
+ }
462
+ }
463
+ });
464
+
465
+ AST_Toplevel.DEFMETHOD("def_global", function(node) {
466
+ var globals = this.globals, name = node.name;
467
+ if (globals.has(name)) {
468
+ return globals.get(name);
469
+ } else {
470
+ var g = new SymbolDef(this, node);
471
+ g.undeclared = true;
472
+ g.global = true;
473
+ globals.set(name, g);
474
+ return g;
475
+ }
476
+ });
477
+
478
+ AST_Scope.DEFMETHOD("init_scope_vars", function(parent_scope) {
479
+ this.variables = new Map(); // map name to AST_SymbolVar (variables defined in this scope; includes functions)
480
+ this.functions = new Map(); // map name to AST_SymbolDefun (functions defined in this scope)
481
+ this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement
482
+ this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval`
483
+ this.parent_scope = parent_scope; // the parent scope
484
+ this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes
485
+ this.cname = -1; // the current index for mangling functions/variables
486
+ });
487
+
488
+ AST_Scope.DEFMETHOD("conflicting_def", function (name) {
489
+ return (
490
+ this.enclosed.find(def => def.name === name)
491
+ || this.variables.has(name)
492
+ || (this.parent_scope && this.parent_scope.conflicting_def(name))
493
+ );
494
+ });
495
+
496
+ AST_Scope.DEFMETHOD("add_child_scope", function (scope) {
497
+ // `scope` is going to be moved into `this` right now.
498
+ // Update the required scopes' information
499
+
500
+ if (scope.parent_scope === this) return;
501
+
502
+ scope.parent_scope = this;
503
+
504
+ // TODO uses_with, uses_eval, etc
505
+
506
+ const scope_ancestry = (() => {
507
+ const ancestry = [];
508
+ let cur = this;
509
+ do {
510
+ ancestry.push(cur);
511
+ } while ((cur = cur.parent_scope));
512
+ ancestry.reverse();
513
+ return ancestry;
514
+ })();
515
+
516
+ const new_scope_enclosed_set = new Set(scope.enclosed);
517
+ const to_enclose = [];
518
+ for (const scope_topdown of scope_ancestry) {
519
+ to_enclose.forEach(e => push_uniq(scope_topdown.enclosed, e));
520
+ for (const def of scope_topdown.variables.values()) {
521
+ if (new_scope_enclosed_set.has(def)) {
522
+ push_uniq(to_enclose, def);
523
+ push_uniq(scope_topdown.enclosed, def);
524
+ }
525
+ }
526
+ }
527
+ });
528
+
529
+ // Creates a symbol during compression
530
+ AST_Scope.DEFMETHOD("create_symbol", function(SymClass, {
531
+ source,
532
+ tentative_name,
533
+ scope,
534
+ init = null
535
+ } = {}) {
536
+ let symbol_name;
537
+
538
+ if (tentative_name) {
539
+ // Implement hygiene (no new names are conflicting with existing names)
540
+ tentative_name =
541
+ symbol_name =
542
+ tentative_name.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/ig, "_");
543
+
544
+ let i = 0;
545
+ while (this.conflicting_def(symbol_name)) {
546
+ symbol_name = tentative_name + "$" + i++;
547
+ }
548
+ }
549
+
550
+ if (!symbol_name) {
551
+ throw new Error("No symbol name could be generated in create_symbol()");
552
+ }
553
+
554
+ const symbol = make_node(SymClass, source, {
555
+ name: symbol_name,
556
+ scope
557
+ });
558
+
559
+ this.def_variable(symbol, init || null);
560
+
561
+ symbol.mark_enclosed();
562
+
563
+ return symbol;
564
+ });
565
+
566
+
567
+ AST_Node.DEFMETHOD("is_block_scope", return_false);
568
+ AST_Class.DEFMETHOD("is_block_scope", return_false);
569
+ AST_Lambda.DEFMETHOD("is_block_scope", return_false);
570
+ AST_Toplevel.DEFMETHOD("is_block_scope", return_false);
571
+ AST_SwitchBranch.DEFMETHOD("is_block_scope", return_false);
572
+ AST_Block.DEFMETHOD("is_block_scope", return_true);
573
+ AST_Scope.DEFMETHOD("is_block_scope", function () {
574
+ return this._block_scope || false;
575
+ });
576
+ AST_IterationStatement.DEFMETHOD("is_block_scope", return_true);
577
+
578
+ AST_Lambda.DEFMETHOD("init_scope_vars", function() {
579
+ AST_Scope.prototype.init_scope_vars.apply(this, arguments);
580
+ this.uses_arguments = false;
581
+ this.def_variable(new AST_SymbolFunarg({
582
+ name: "arguments",
583
+ start: this.start,
584
+ end: this.end
585
+ }));
586
+ });
587
+
588
+ AST_Arrow.DEFMETHOD("init_scope_vars", function() {
589
+ AST_Scope.prototype.init_scope_vars.apply(this, arguments);
590
+ this.uses_arguments = false;
591
+ });
592
+
593
+ AST_Symbol.DEFMETHOD("mark_enclosed", function() {
594
+ var def = this.definition();
595
+ var s = this.scope;
596
+ while (s) {
597
+ push_uniq(s.enclosed, def);
598
+ if (s === def.scope) break;
599
+ s = s.parent_scope;
600
+ }
601
+ });
602
+
603
+ AST_Symbol.DEFMETHOD("reference", function() {
604
+ this.definition().references.push(this);
605
+ this.mark_enclosed();
606
+ });
607
+
608
+ AST_Scope.DEFMETHOD("find_variable", function(name) {
609
+ if (name instanceof AST_Symbol) name = name.name;
610
+ return this.variables.get(name)
611
+ || (this.parent_scope && this.parent_scope.find_variable(name));
612
+ });
613
+
614
+ AST_Scope.DEFMETHOD("def_function", function(symbol, init) {
615
+ var def = this.def_variable(symbol, init);
616
+ if (!def.init || def.init instanceof AST_Defun) def.init = init;
617
+ this.functions.set(symbol.name, def);
618
+ return def;
619
+ });
620
+
621
+ AST_Scope.DEFMETHOD("def_variable", function(symbol, init) {
622
+ var def = this.variables.get(symbol.name);
623
+ if (def) {
624
+ def.orig.push(symbol);
625
+ if (def.init && (def.scope !== symbol.scope || def.init instanceof AST_Function)) {
626
+ def.init = init;
627
+ }
628
+ } else {
629
+ def = new SymbolDef(this, symbol, init);
630
+ this.variables.set(symbol.name, def);
631
+ def.global = !this.parent_scope;
632
+ }
633
+ return symbol.thedef = def;
634
+ });
635
+
636
+ function next_mangled(scope, options) {
637
+ var ext = scope.enclosed;
638
+ out: while (true) {
639
+ var m = base54(++scope.cname);
640
+ if (RESERVED_WORDS.has(m)) continue; // skip over "do"
641
+
642
+ // https://github.com/mishoo/UglifyJS2/issues/242 -- do not
643
+ // shadow a name reserved from mangling.
644
+ if (options.reserved.has(m)) continue;
645
+
646
+ // Functions with short names might collide with base54 output
647
+ // and therefore cause collisions when keep_fnames is true.
648
+ if (unmangleable_names && unmangleable_names.has(m)) continue out;
649
+
650
+ // we must ensure that the mangled name does not shadow a name
651
+ // from some parent scope that is referenced in this or in
652
+ // inner scopes.
653
+ for (let i = ext.length; --i >= 0;) {
654
+ const def = ext[i];
655
+ const name = def.mangled_name || (def.unmangleable(options) && def.name);
656
+ if (m == name) continue out;
657
+ }
658
+ return m;
659
+ }
660
+ }
661
+
662
+ AST_Scope.DEFMETHOD("next_mangled", function(options) {
663
+ return next_mangled(this, options);
664
+ });
665
+
666
+ AST_Toplevel.DEFMETHOD("next_mangled", function(options) {
667
+ let name;
668
+ const mangled_names = this.mangled_names;
669
+ do {
670
+ name = next_mangled(this, options);
671
+ } while (mangled_names.has(name));
672
+ return name;
673
+ });
674
+
675
+ AST_Function.DEFMETHOD("next_mangled", function(options, def) {
676
+ // #179, #326
677
+ // in Safari strict mode, something like (function x(x){...}) is a syntax error;
678
+ // a function expression's argument cannot shadow the function expression's name
679
+
680
+ var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition();
681
+
682
+ // the function's mangled_name is null when keep_fnames is true
683
+ var tricky_name = tricky_def ? tricky_def.mangled_name || tricky_def.name : null;
684
+
685
+ while (true) {
686
+ var name = next_mangled(this, options);
687
+ if (!tricky_name || tricky_name != name)
688
+ return name;
689
+ }
690
+ });
691
+
692
+ AST_Symbol.DEFMETHOD("unmangleable", function(options) {
693
+ var def = this.definition();
694
+ return !def || def.unmangleable(options);
695
+ });
696
+
697
+ // labels are always mangleable
698
+ AST_Label.DEFMETHOD("unmangleable", return_false);
699
+
700
+ AST_Symbol.DEFMETHOD("unreferenced", function() {
701
+ return !this.definition().references.length && !this.scope.pinned();
702
+ });
703
+
704
+ AST_Symbol.DEFMETHOD("definition", function() {
705
+ return this.thedef;
706
+ });
707
+
708
+ AST_Symbol.DEFMETHOD("global", function() {
709
+ return this.thedef.global;
710
+ });
711
+
712
+ AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options) {
713
+ options = defaults(options, {
714
+ eval : false,
715
+ ie8 : false,
716
+ keep_classnames: false,
717
+ keep_fnames : false,
718
+ module : false,
719
+ reserved : [],
720
+ toplevel : false,
721
+ });
722
+ if (options.module) options.toplevel = true;
723
+ if (!Array.isArray(options.reserved)
724
+ && !(options.reserved instanceof Set)
725
+ ) {
726
+ options.reserved = [];
727
+ }
728
+ options.reserved = new Set(options.reserved);
729
+ // Never mangle arguments
730
+ options.reserved.add("arguments");
731
+ return options;
732
+ });
733
+
734
+ AST_Toplevel.DEFMETHOD("mangle_names", function(options) {
735
+ options = this._default_mangler_options(options);
736
+
737
+ // We only need to mangle declaration nodes. Special logic wired
738
+ // into the code generator will display the mangled name if it's
739
+ // present (and for AST_SymbolRef-s it'll use the mangled name of
740
+ // the AST_SymbolDeclaration that it points to).
741
+ var lname = -1;
742
+ var to_mangle = [];
743
+
744
+ if (options.keep_fnames) {
745
+ function_defs = new Set();
746
+ }
747
+
748
+ const mangled_names = this.mangled_names = new Set();
749
+ if (options.cache) {
750
+ this.globals.forEach(collect);
751
+ if (options.cache.props) {
752
+ options.cache.props.forEach(function(mangled_name) {
753
+ mangled_names.add(mangled_name);
754
+ });
755
+ }
756
+ }
757
+
758
+ var tw = new TreeWalker(function(node, descend) {
759
+ if (node instanceof AST_LabeledStatement) {
760
+ // lname is incremented when we get to the AST_Label
761
+ var save_nesting = lname;
762
+ descend();
763
+ lname = save_nesting;
764
+ return true; // don't descend again in TreeWalker
765
+ }
766
+ if (node instanceof AST_Scope) {
767
+ node.variables.forEach(collect);
768
+ return;
769
+ }
770
+ if (node.is_block_scope()) {
771
+ node.block_scope.variables.forEach(collect);
772
+ return;
773
+ }
774
+ if (
775
+ function_defs
776
+ && node instanceof AST_VarDef
777
+ && node.value instanceof AST_Lambda
778
+ && !node.value.name
779
+ && keep_name(options.keep_fnames, node.name.name)
780
+ ) {
781
+ function_defs.add(node.name.definition().id);
782
+ return;
783
+ }
784
+ if (node instanceof AST_Label) {
785
+ let name;
786
+ do {
787
+ name = base54(++lname);
788
+ } while (RESERVED_WORDS.has(name));
789
+ node.mangled_name = name;
790
+ return true;
791
+ }
792
+ if (!(options.ie8 || options.safari10) && node instanceof AST_SymbolCatch) {
793
+ to_mangle.push(node.definition());
794
+ return;
795
+ }
796
+ });
797
+
798
+ this.walk(tw);
799
+
800
+ if (options.keep_fnames || options.keep_classnames) {
801
+ unmangleable_names = new Set();
802
+ // Collect a set of short names which are unmangleable,
803
+ // for use in avoiding collisions in next_mangled.
804
+ to_mangle.forEach(def => {
805
+ if (def.name.length < 6 && def.unmangleable(options)) {
806
+ unmangleable_names.add(def.name);
807
+ }
808
+ });
809
+ }
810
+
811
+ to_mangle.forEach(def => { def.mangle(options); });
812
+
813
+ function_defs = null;
814
+ unmangleable_names = null;
815
+
816
+ function collect(symbol) {
817
+ const should_mangle = !options.reserved.has(symbol.name)
818
+ && !(symbol.export & MASK_EXPORT_DONT_MANGLE);
819
+ if (should_mangle) {
820
+ to_mangle.push(symbol);
821
+ }
822
+ }
823
+ });
824
+
825
+ AST_Toplevel.DEFMETHOD("find_colliding_names", function(options) {
826
+ const cache = options.cache && options.cache.props;
827
+ const avoid = new Set();
828
+ options.reserved.forEach(to_avoid);
829
+ this.globals.forEach(add_def);
830
+ this.walk(new TreeWalker(function(node) {
831
+ if (node instanceof AST_Scope) node.variables.forEach(add_def);
832
+ if (node instanceof AST_SymbolCatch) add_def(node.definition());
833
+ }));
834
+ return avoid;
835
+
836
+ function to_avoid(name) {
837
+ avoid.add(name);
838
+ }
839
+
840
+ function add_def(def) {
841
+ var name = def.name;
842
+ if (def.global && cache && cache.has(name)) name = cache.get(name);
843
+ else if (!def.unmangleable(options)) return;
844
+ to_avoid(name);
845
+ }
846
+ });
847
+
848
+ AST_Toplevel.DEFMETHOD("expand_names", function(options) {
849
+ base54.reset();
850
+ base54.sort();
851
+ options = this._default_mangler_options(options);
852
+ var avoid = this.find_colliding_names(options);
853
+ var cname = 0;
854
+ this.globals.forEach(rename);
855
+ this.walk(new TreeWalker(function(node) {
856
+ if (node instanceof AST_Scope) node.variables.forEach(rename);
857
+ if (node instanceof AST_SymbolCatch) rename(node.definition());
858
+ }));
859
+
860
+ function next_name() {
861
+ var name;
862
+ do {
863
+ name = base54(cname++);
864
+ } while (avoid.has(name) || RESERVED_WORDS.has(name));
865
+ return name;
866
+ }
867
+
868
+ function rename(def) {
869
+ if (def.global && options.cache) return;
870
+ if (def.unmangleable(options)) return;
871
+ if (options.reserved.has(def.name)) return;
872
+ const redefinition = redefined_catch_def(def);
873
+ const name = def.name = redefinition ? redefinition.name : next_name();
874
+ def.orig.forEach(function(sym) {
875
+ sym.name = name;
876
+ });
877
+ def.references.forEach(function(sym) {
878
+ sym.name = name;
879
+ });
880
+ }
881
+ });
882
+
883
+ AST_Node.DEFMETHOD("tail_node", return_this);
884
+ AST_Sequence.DEFMETHOD("tail_node", function() {
885
+ return this.expressions[this.expressions.length - 1];
886
+ });
887
+
888
+ AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options) {
889
+ options = this._default_mangler_options(options);
890
+ try {
891
+ AST_Node.prototype.print = function(stream, force_parens) {
892
+ this._print(stream, force_parens);
893
+ if (this instanceof AST_Symbol && !this.unmangleable(options)) {
894
+ base54.consider(this.name, -1);
895
+ } else if (options.properties) {
896
+ if (this instanceof AST_Dot) {
897
+ base54.consider(this.property, -1);
898
+ } else if (this instanceof AST_Sub) {
899
+ skip_string(this.property);
900
+ }
901
+ }
902
+ };
903
+ base54.consider(this.print_to_string(), 1);
904
+ } finally {
905
+ AST_Node.prototype.print = AST_Node.prototype._print;
906
+ }
907
+ base54.sort();
908
+
909
+ function skip_string(node) {
910
+ if (node instanceof AST_String) {
911
+ base54.consider(node.value, -1);
912
+ } else if (node instanceof AST_Conditional) {
913
+ skip_string(node.consequent);
914
+ skip_string(node.alternative);
915
+ } else if (node instanceof AST_Sequence) {
916
+ skip_string(node.tail_node());
917
+ }
918
+ }
919
+ });
920
+
921
+ const base54 = (() => {
922
+ const leading = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_".split("");
923
+ const digits = "0123456789".split("");
924
+ let chars;
925
+ let frequency;
926
+ function reset() {
927
+ frequency = new Map();
928
+ leading.forEach(function(ch) {
929
+ frequency.set(ch, 0);
930
+ });
931
+ digits.forEach(function(ch) {
932
+ frequency.set(ch, 0);
933
+ });
934
+ }
935
+ base54.consider = function(str, delta) {
936
+ for (var i = str.length; --i >= 0;) {
937
+ frequency.set(str[i], frequency.get(str[i]) + delta);
938
+ }
939
+ };
940
+ function compare(a, b) {
941
+ return frequency.get(b) - frequency.get(a);
942
+ }
943
+ base54.sort = function() {
944
+ chars = mergeSort(leading, compare).concat(mergeSort(digits, compare));
945
+ };
946
+ base54.reset = reset;
947
+ reset();
948
+ function base54(num) {
949
+ var ret = "", base = 54;
950
+ num++;
951
+ do {
952
+ num--;
953
+ ret += chars[num % base];
954
+ num = Math.floor(num / base);
955
+ base = 64;
956
+ } while (num > 0);
957
+ return ret;
958
+ }
959
+ return base54;
960
+ })();
961
+
962
+ export {
963
+ base54,
964
+ SymbolDef,
965
+ };