uglifier 0.5.1 → 0.5.2

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of uglifier might be problematic. Click here for more details.

@@ -0,0 +1,1616 @@
1
+ /***********************************************************************
2
+
3
+ A JavaScript tokenizer / parser / beautifier / compressor.
4
+
5
+ This version is suitable for Node.js. With minimal changes (the
6
+ exports stuff) it should work on any JS platform.
7
+
8
+ This file implements some AST processors. They work on data built
9
+ by parse-js.
10
+
11
+ Exported functions:
12
+
13
+ - ast_mangle(ast, options) -- mangles the variable/function names
14
+ in the AST. Returns an AST.
15
+
16
+ - ast_squeeze(ast) -- employs various optimizations to make the
17
+ final generated code even smaller. Returns an AST.
18
+
19
+ - gen_code(ast, options) -- generates JS code from the AST. Pass
20
+ true (or an object, see the code for some options) as second
21
+ argument to get "pretty" (indented) code.
22
+
23
+ -------------------------------- (C) ---------------------------------
24
+
25
+ Author: Mihai Bazon
26
+ <mihai.bazon@gmail.com>
27
+ http://mihai.bazon.net/blog
28
+
29
+ Distributed under the BSD license:
30
+
31
+ Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
32
+
33
+ Redistribution and use in source and binary forms, with or without
34
+ modification, are permitted provided that the following conditions
35
+ are met:
36
+
37
+ * Redistributions of source code must retain the above
38
+ copyright notice, this list of conditions and the following
39
+ disclaimer.
40
+
41
+ * Redistributions in binary form must reproduce the above
42
+ copyright notice, this list of conditions and the following
43
+ disclaimer in the documentation and/or other materials
44
+ provided with the distribution.
45
+
46
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
47
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
49
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
50
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
51
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
52
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
53
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
54
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
55
+ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
56
+ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
57
+ SUCH DAMAGE.
58
+
59
+ ***********************************************************************/
60
+
61
+ var jsp = require("./parse-js"),
62
+ slice = jsp.slice,
63
+ member = jsp.member,
64
+ PRECEDENCE = jsp.PRECEDENCE,
65
+ OPERATORS = jsp.OPERATORS;
66
+
67
+ /* -----[ helper for AST traversal ]----- */
68
+
69
+ function ast_walker(ast) {
70
+ function _vardefs(defs) {
71
+ return [ this[0], MAP(defs, function(def){
72
+ var a = [ def[0] ];
73
+ if (def.length > 1)
74
+ a[1] = walk(def[1]);
75
+ return a;
76
+ }) ];
77
+ };
78
+ var walkers = {
79
+ "string": function(str) {
80
+ return [ this[0], str ];
81
+ },
82
+ "num": function(num) {
83
+ return [ this[0], num ];
84
+ },
85
+ "name": function(name) {
86
+ return [ this[0], name ];
87
+ },
88
+ "toplevel": function(statements) {
89
+ return [ this[0], MAP(statements, walk) ];
90
+ },
91
+ "block": function(statements) {
92
+ var out = [ this[0] ];
93
+ if (statements != null)
94
+ out.push(MAP(statements, walk));
95
+ return out;
96
+ },
97
+ "var": _vardefs,
98
+ "const": _vardefs,
99
+ "try": function(t, c, f) {
100
+ return [
101
+ this[0],
102
+ MAP(t, walk),
103
+ c != null ? [ c[0], MAP(c[1], walk) ] : null,
104
+ f != null ? MAP(f, walk) : null
105
+ ];
106
+ },
107
+ "throw": function(expr) {
108
+ return [ this[0], walk(expr) ];
109
+ },
110
+ "new": function(ctor, args) {
111
+ return [ this[0], walk(ctor), MAP(args, walk) ];
112
+ },
113
+ "switch": function(expr, body) {
114
+ return [ this[0], walk(expr), MAP(body, function(branch){
115
+ return [ branch[0] ? walk(branch[0]) : null,
116
+ MAP(branch[1], walk) ];
117
+ }) ];
118
+ },
119
+ "break": function(label) {
120
+ return [ this[0], label ];
121
+ },
122
+ "continue": function(label) {
123
+ return [ this[0], label ];
124
+ },
125
+ "conditional": function(cond, t, e) {
126
+ return [ this[0], walk(cond), walk(t), walk(e) ];
127
+ },
128
+ "assign": function(op, lvalue, rvalue) {
129
+ return [ this[0], op, walk(lvalue), walk(rvalue) ];
130
+ },
131
+ "dot": function(expr) {
132
+ return [ this[0], walk(expr) ].concat(slice(arguments, 1));
133
+ },
134
+ "call": function(expr, args) {
135
+ return [ this[0], walk(expr), MAP(args, walk) ];
136
+ },
137
+ "function": function(name, args, body) {
138
+ return [ this[0], name, args.slice(), MAP(body, walk) ];
139
+ },
140
+ "defun": function(name, args, body) {
141
+ return [ this[0], name, args.slice(), MAP(body, walk) ];
142
+ },
143
+ "if": function(conditional, t, e) {
144
+ return [ this[0], walk(conditional), walk(t), walk(e) ];
145
+ },
146
+ "for": function(init, cond, step, block) {
147
+ return [ this[0], walk(init), walk(cond), walk(step), walk(block) ];
148
+ },
149
+ "for-in": function(vvar, key, hash, block) {
150
+ return [ this[0], walk(vvar), walk(key), walk(hash), walk(block) ];
151
+ },
152
+ "while": function(cond, block) {
153
+ return [ this[0], walk(cond), walk(block) ];
154
+ },
155
+ "do": function(cond, block) {
156
+ return [ this[0], walk(cond), walk(block) ];
157
+ },
158
+ "return": function(expr) {
159
+ return [ this[0], walk(expr) ];
160
+ },
161
+ "binary": function(op, left, right) {
162
+ return [ this[0], op, walk(left), walk(right) ];
163
+ },
164
+ "unary-prefix": function(op, expr) {
165
+ return [ this[0], op, walk(expr) ];
166
+ },
167
+ "unary-postfix": function(op, expr) {
168
+ return [ this[0], op, walk(expr) ];
169
+ },
170
+ "sub": function(expr, subscript) {
171
+ return [ this[0], walk(expr), walk(subscript) ];
172
+ },
173
+ "object": function(props) {
174
+ return [ this[0], MAP(props, function(p){
175
+ return p.length == 2
176
+ ? [ p[0], walk(p[1]) ]
177
+ : [ p[0], walk(p[1]), p[2] ]; // get/set-ter
178
+ }) ];
179
+ },
180
+ "regexp": function(rx, mods) {
181
+ return [ this[0], rx, mods ];
182
+ },
183
+ "array": function(elements) {
184
+ return [ this[0], MAP(elements, walk) ];
185
+ },
186
+ "stat": function(stat) {
187
+ return [ this[0], walk(stat) ];
188
+ },
189
+ "seq": function() {
190
+ return [ this[0] ].concat(MAP(slice(arguments), walk));
191
+ },
192
+ "label": function(name, block) {
193
+ return [ this[0], name, walk(block) ];
194
+ },
195
+ "with": function(expr, block) {
196
+ return [ this[0], walk(expr), walk(block) ];
197
+ },
198
+ "atom": function(name) {
199
+ return [ this[0], name ];
200
+ }
201
+ };
202
+
203
+ var user = {};
204
+ var stack = [];
205
+ function walk(ast) {
206
+ if (ast == null)
207
+ return null;
208
+ try {
209
+ stack.push(ast);
210
+ var type = ast[0];
211
+ var gen = user[type];
212
+ if (gen) {
213
+ var ret = gen.apply(ast, ast.slice(1));
214
+ if (ret != null)
215
+ return ret;
216
+ }
217
+ gen = walkers[type];
218
+ return gen.apply(ast, ast.slice(1));
219
+ } finally {
220
+ stack.pop();
221
+ }
222
+ };
223
+
224
+ function with_walkers(walkers, cont){
225
+ var save = {}, i;
226
+ for (i in walkers) if (HOP(walkers, i)) {
227
+ save[i] = user[i];
228
+ user[i] = walkers[i];
229
+ }
230
+ var ret = cont();
231
+ for (i in save) if (HOP(save, i)) {
232
+ if (!save[i]) delete user[i];
233
+ else user[i] = save[i];
234
+ }
235
+ return ret;
236
+ };
237
+
238
+ return {
239
+ walk: walk,
240
+ with_walkers: with_walkers,
241
+ parent: function() {
242
+ return stack[stack.length - 2]; // last one is current node
243
+ },
244
+ stack: function() {
245
+ return stack;
246
+ }
247
+ };
248
+ };
249
+
250
+ /* -----[ Scope and mangling ]----- */
251
+
252
+ function Scope(parent) {
253
+ this.names = {}; // names defined in this scope
254
+ this.mangled = {}; // mangled names (orig.name => mangled)
255
+ this.rev_mangled = {}; // reverse lookup (mangled => orig.name)
256
+ this.cname = -1; // current mangled name
257
+ this.refs = {}; // names referenced from this scope
258
+ this.uses_with = false; // will become TRUE if with() is detected in this or any subscopes
259
+ this.uses_eval = false; // will become TRUE if eval() is detected in this or any subscopes
260
+ this.parent = parent; // parent scope
261
+ this.children = []; // sub-scopes
262
+ if (parent) {
263
+ this.level = parent.level + 1;
264
+ parent.children.push(this);
265
+ } else {
266
+ this.level = 0;
267
+ }
268
+ };
269
+
270
+ var base54 = (function(){
271
+ var DIGITS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_";
272
+ return function(num) {
273
+ var ret = "";
274
+ do {
275
+ ret = DIGITS.charAt(num % 54) + ret;
276
+ num = Math.floor(num / 54);
277
+ } while (num > 0);
278
+ return ret;
279
+ };
280
+ })();
281
+
282
+ Scope.prototype = {
283
+ has: function(name) {
284
+ for (var s = this; s; s = s.parent)
285
+ if (HOP(s.names, name))
286
+ return s;
287
+ },
288
+ has_mangled: function(mname) {
289
+ for (var s = this; s; s = s.parent)
290
+ if (HOP(s.rev_mangled, mname))
291
+ return s;
292
+ },
293
+ toJSON: function() {
294
+ return {
295
+ names: this.names,
296
+ uses_eval: this.uses_eval,
297
+ uses_with: this.uses_with
298
+ };
299
+ },
300
+
301
+ next_mangled: function() {
302
+ // we must be careful that the new mangled name:
303
+ //
304
+ // 1. doesn't shadow a mangled name from a parent
305
+ // scope, unless we don't reference the original
306
+ // name from this scope OR from any sub-scopes!
307
+ // This will get slow.
308
+ //
309
+ // 2. doesn't shadow an original name from a parent
310
+ // scope, in the event that the name is not mangled
311
+ // in the parent scope and we reference that name
312
+ // here OR IN ANY SUBSCOPES!
313
+ //
314
+ // 3. doesn't shadow a name that is referenced but not
315
+ // defined (possibly global defined elsewhere).
316
+ for (;;) {
317
+ var m = base54(++this.cname), prior;
318
+
319
+ // case 1.
320
+ prior = this.has_mangled(m);
321
+ if (prior && this.refs[prior.rev_mangled[m]] === prior)
322
+ continue;
323
+
324
+ // case 2.
325
+ prior = this.has(m);
326
+ if (prior && prior !== this && this.refs[m] === prior && !prior.has_mangled(m))
327
+ continue;
328
+
329
+ // case 3.
330
+ if (HOP(this.refs, m) && this.refs[m] == null)
331
+ continue;
332
+
333
+ // I got "do" once. :-/
334
+ if (!is_identifier(m))
335
+ continue;
336
+
337
+ return m;
338
+ }
339
+ },
340
+ get_mangled: function(name, newMangle) {
341
+ if (this.uses_eval || this.uses_with) return name; // no mangle if eval or with is in use
342
+ var s = this.has(name);
343
+ if (!s) return name; // not in visible scope, no mangle
344
+ if (HOP(s.mangled, name)) return s.mangled[name]; // already mangled in this scope
345
+ if (!newMangle) return name; // not found and no mangling requested
346
+
347
+ var m = s.next_mangled();
348
+ s.rev_mangled[m] = name;
349
+ return s.mangled[name] = m;
350
+ },
351
+ define: function(name) {
352
+ if (name != null)
353
+ return this.names[name] = name;
354
+ }
355
+ };
356
+
357
+ function ast_add_scope(ast) {
358
+
359
+ var current_scope = null;
360
+ var w = ast_walker(), walk = w.walk;
361
+ var having_eval = [];
362
+
363
+ function with_new_scope(cont) {
364
+ current_scope = new Scope(current_scope);
365
+ var ret = current_scope.body = cont();
366
+ ret.scope = current_scope;
367
+ current_scope = current_scope.parent;
368
+ return ret;
369
+ };
370
+
371
+ function define(name) {
372
+ return current_scope.define(name);
373
+ };
374
+
375
+ function reference(name) {
376
+ current_scope.refs[name] = true;
377
+ };
378
+
379
+ function _lambda(name, args, body) {
380
+ return [ this[0], define(name), args, with_new_scope(function(){
381
+ MAP(args, define);
382
+ return MAP(body, walk);
383
+ })];
384
+ };
385
+
386
+ return with_new_scope(function(){
387
+ // process AST
388
+ var ret = w.with_walkers({
389
+ "function": _lambda,
390
+ "defun": _lambda,
391
+ "with": function(expr, block) {
392
+ for (var s = current_scope; s; s = s.parent)
393
+ s.uses_with = true;
394
+ },
395
+ "var": function(defs) {
396
+ MAP(defs, function(d){ define(d[0]) });
397
+ },
398
+ "const": function(defs) {
399
+ MAP(defs, function(d){ define(d[0]) });
400
+ },
401
+ "try": function(t, c, f) {
402
+ if (c != null) return [
403
+ this[0],
404
+ MAP(t, walk),
405
+ [ define(c[0]), MAP(c[1], walk) ],
406
+ f != null ? MAP(f, walk) : null
407
+ ];
408
+ },
409
+ "name": function(name) {
410
+ if (name == "eval")
411
+ having_eval.push(current_scope);
412
+ reference(name);
413
+ }
414
+ }, function(){
415
+ return walk(ast);
416
+ });
417
+
418
+ // the reason why we need an additional pass here is
419
+ // that names can be used prior to their definition.
420
+
421
+ // scopes where eval was detected and their parents
422
+ // are marked with uses_eval, unless they define the
423
+ // "eval" name.
424
+ MAP(having_eval, function(scope){
425
+ if (!scope.has("eval")) while (scope) {
426
+ scope.uses_eval = true;
427
+ scope = scope.parent;
428
+ }
429
+ });
430
+
431
+ // for referenced names it might be useful to know
432
+ // their origin scope. current_scope here is the
433
+ // toplevel one.
434
+ function fixrefs(scope, i) {
435
+ // do children first; order shouldn't matter
436
+ for (i = scope.children.length; --i >= 0;)
437
+ fixrefs(scope.children[i]);
438
+ for (i in scope.refs) if (HOP(scope.refs, i)) {
439
+ // find origin scope and propagate the reference to origin
440
+ for (var origin = scope.has(i), s = scope; s; s = s.parent) {
441
+ s.refs[i] = origin;
442
+ if (s === origin) break;
443
+ }
444
+ }
445
+ };
446
+ fixrefs(current_scope);
447
+
448
+ return ret;
449
+ });
450
+
451
+ };
452
+
453
+ /* -----[ mangle names ]----- */
454
+
455
+ function ast_mangle(ast, options) {
456
+ var w = ast_walker(), walk = w.walk, scope;
457
+ options = options || {};
458
+
459
+ function get_mangled(name, newMangle) {
460
+ if (!options.toplevel && !scope.parent) return name; // don't mangle toplevel
461
+ if (options.except && member(name, options.except))
462
+ return name;
463
+ return scope.get_mangled(name, newMangle);
464
+ };
465
+
466
+ function _lambda(name, args, body) {
467
+ if (name) name = get_mangled(name);
468
+ body = with_scope(body.scope, function(){
469
+ args = MAP(args, function(name){ return get_mangled(name) });
470
+ return MAP(body, walk);
471
+ });
472
+ return [ this[0], name, args, body ];
473
+ };
474
+
475
+ function with_scope(s, cont) {
476
+ var _scope = scope;
477
+ scope = s;
478
+ for (var i in s.names) if (HOP(s.names, i)) {
479
+ get_mangled(i, true);
480
+ }
481
+ var ret = cont();
482
+ ret.scope = s;
483
+ scope = _scope;
484
+ return ret;
485
+ };
486
+
487
+ function _vardefs(defs) {
488
+ return [ this[0], MAP(defs, function(d){
489
+ return [ get_mangled(d[0]), walk(d[1]) ];
490
+ }) ];
491
+ };
492
+
493
+ return w.with_walkers({
494
+ "function": _lambda,
495
+ "defun": function() {
496
+ // move function declarations to the top when
497
+ // they are not in some block.
498
+ var ast = _lambda.apply(this, arguments);
499
+ switch (w.parent()[0]) {
500
+ case "toplevel":
501
+ case "function":
502
+ case "defun":
503
+ return MAP.at_top(ast);
504
+ }
505
+ return ast;
506
+ },
507
+ "var": _vardefs,
508
+ "const": _vardefs,
509
+ "name": function(name) {
510
+ return [ this[0], get_mangled(name) ];
511
+ },
512
+ "try": function(t, c, f) {
513
+ return [ this[0],
514
+ MAP(t, walk),
515
+ c != null ? [ get_mangled(c[0]), MAP(c[1], walk) ] : null,
516
+ f != null ? MAP(f, walk) : null ];
517
+ },
518
+ "toplevel": function(body) {
519
+ var self = this;
520
+ return with_scope(self.scope, function(){
521
+ return [ self[0], MAP(body, walk) ];
522
+ });
523
+ }
524
+ }, function() {
525
+ return walk(ast_add_scope(ast));
526
+ });
527
+ };
528
+
529
+ /* -----[
530
+ - compress foo["bar"] into foo.bar,
531
+ - remove block brackets {} where possible
532
+ - join consecutive var declarations
533
+ - various optimizations for IFs:
534
+ - if (cond) foo(); else bar(); ==> cond?foo():bar();
535
+ - if (cond) foo(); ==> cond&&foo();
536
+ - if (foo) return bar(); else return baz(); ==> return foo?bar():baz(); // also for throw
537
+ - if (foo) return bar(); else something(); ==> {if(foo)return bar();something()}
538
+ ]----- */
539
+
540
+ var warn = function(){};
541
+
542
+ function best_of(ast1, ast2) {
543
+ return gen_code(ast1).length > gen_code(ast2[0] == "stat" ? ast2[1] : ast2).length ? ast2 : ast1;
544
+ };
545
+
546
+ function last_stat(b) {
547
+ if (b[0] == "block" && b[1] && b[1].length > 0)
548
+ return b[1][b[1].length - 1];
549
+ return b;
550
+ }
551
+
552
+ function aborts(t) {
553
+ if (t) {
554
+ t = last_stat(t);
555
+ if (t[0] == "return" || t[0] == "break" || t[0] == "continue" || t[0] == "throw")
556
+ return true;
557
+ }
558
+ };
559
+
560
+ function boolean_expr(expr) {
561
+ return ( (expr[0] == "unary-prefix"
562
+ && member(expr[1], [ "!", "delete" ])) ||
563
+
564
+ (expr[0] == "binary"
565
+ && member(expr[1], [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ])) ||
566
+
567
+ (expr[0] == "binary"
568
+ && member(expr[1], [ "&&", "||" ])
569
+ && boolean_expr(expr[2])
570
+ && boolean_expr(expr[3])) ||
571
+
572
+ (expr[0] == "conditional"
573
+ && boolean_expr(expr[2])
574
+ && boolean_expr(expr[3])) ||
575
+
576
+ (expr[0] == "assign"
577
+ && expr[1] === true
578
+ && boolean_expr(expr[3])) ||
579
+
580
+ (expr[0] == "seq"
581
+ && boolean_expr(expr[expr.length - 1]))
582
+ );
583
+ };
584
+
585
+ function make_conditional(c, t, e) {
586
+ if (c[0] == "unary-prefix" && c[1] == "!") {
587
+ return e ? [ "conditional", c[2], e, t ] : [ "binary", "||", c[2], t ];
588
+ } else {
589
+ return e ? [ "conditional", c, t, e ] : [ "binary", "&&", c, t ];
590
+ }
591
+ };
592
+
593
+ function empty(b) {
594
+ return !b || (b[0] == "block" && (!b[1] || b[1].length == 0));
595
+ };
596
+
597
+ function is_string(node) {
598
+ return (node[0] == "string" ||
599
+ node[0] == "unary-prefix" && node[1] == "typeof" ||
600
+ node[0] == "binary" && node[1] == "+" &&
601
+ (is_string(node[2]) || is_string(node[3])));
602
+ };
603
+
604
+ var when_constant = (function(){
605
+
606
+ var $NOT_CONSTANT = {};
607
+
608
+ // this can only evaluate constant expressions. If it finds anything
609
+ // not constant, it throws $NOT_CONSTANT.
610
+ function evaluate(expr) {
611
+ switch (expr[0]) {
612
+ case "string":
613
+ case "num":
614
+ return expr[1];
615
+ case "name":
616
+ case "atom":
617
+ switch (expr[1]) {
618
+ case "true": return true;
619
+ case "false": return false;
620
+ }
621
+ break;
622
+ case "unary-prefix":
623
+ switch (expr[1]) {
624
+ case "!": return !evaluate(expr[2]);
625
+ case "typeof": return typeof evaluate(expr[2]);
626
+ case "~": return ~evaluate(expr[2]);
627
+ case "-": return -evaluate(expr[2]);
628
+ case "+": return +evaluate(expr[2]);
629
+ }
630
+ break;
631
+ case "binary":
632
+ var left = expr[2], right = expr[3];
633
+ switch (expr[1]) {
634
+ case "&&" : return evaluate(left) && evaluate(right);
635
+ case "||" : return evaluate(left) || evaluate(right);
636
+ case "|" : return evaluate(left) | evaluate(right);
637
+ case "&" : return evaluate(left) & evaluate(right);
638
+ case "^" : return evaluate(left) ^ evaluate(right);
639
+ case "+" : return evaluate(left) + evaluate(right);
640
+ case "*" : return evaluate(left) * evaluate(right);
641
+ case "/" : return evaluate(left) / evaluate(right);
642
+ case "-" : return evaluate(left) - evaluate(right);
643
+ case "<<" : return evaluate(left) << evaluate(right);
644
+ case ">>" : return evaluate(left) >> evaluate(right);
645
+ case ">>>" : return evaluate(left) >>> evaluate(right);
646
+ case "==" : return evaluate(left) == evaluate(right);
647
+ case "===" : return evaluate(left) === evaluate(right);
648
+ case "!=" : return evaluate(left) != evaluate(right);
649
+ case "!==" : return evaluate(left) !== evaluate(right);
650
+ case "<" : return evaluate(left) < evaluate(right);
651
+ case "<=" : return evaluate(left) <= evaluate(right);
652
+ case ">" : return evaluate(left) > evaluate(right);
653
+ case ">=" : return evaluate(left) >= evaluate(right);
654
+ case "in" : return evaluate(left) in evaluate(right);
655
+ case "instanceof" : return evaluate(left) instanceof evaluate(right);
656
+ }
657
+ }
658
+ throw $NOT_CONSTANT;
659
+ };
660
+
661
+ return function(expr, yes, no) {
662
+ try {
663
+ var val = evaluate(expr), ast;
664
+ switch (typeof val) {
665
+ case "string": ast = [ "string", val ]; break;
666
+ case "number": ast = [ "num", val ]; break;
667
+ case "boolean": ast = [ "name", String(val) ]; break;
668
+ default: throw new Error("Can't handle constant of type: " + (typeof val));
669
+ }
670
+ return yes.call(expr, ast, val);
671
+ } catch(ex) {
672
+ if (ex === $NOT_CONSTANT) {
673
+ if (expr[0] == "binary"
674
+ && (expr[1] == "===" || expr[1] == "!==")
675
+ && ((is_string(expr[2]) && is_string(expr[3]))
676
+ || (boolean_expr(expr[2]) && boolean_expr(expr[3])))) {
677
+ expr[1] = expr[1].substr(0, 2);
678
+ }
679
+ return no ? no.call(expr, expr) : null;
680
+ }
681
+ else throw ex;
682
+ }
683
+ };
684
+
685
+ })();
686
+
687
+ function warn_unreachable(ast) {
688
+ if (!empty(ast))
689
+ warn("Dropping unreachable code: " + gen_code(ast, true));
690
+ };
691
+
692
+ function ast_squeeze(ast, options) {
693
+ options = defaults(options, {
694
+ make_seqs : true,
695
+ dead_code : true,
696
+ keep_comps : true,
697
+ no_warnings : false
698
+ });
699
+
700
+ var w = ast_walker(), walk = w.walk, scope;
701
+
702
+ function negate(c) {
703
+ var not_c = [ "unary-prefix", "!", c ];
704
+ switch (c[0]) {
705
+ case "unary-prefix":
706
+ return c[1] == "!" && boolean_expr(c[2]) ? c[2] : not_c;
707
+ case "seq":
708
+ c = slice(c);
709
+ c[c.length - 1] = negate(c[c.length - 1]);
710
+ return c;
711
+ case "conditional":
712
+ return best_of(not_c, [ "conditional", c[1], negate(c[2]), negate(c[3]) ]);
713
+ case "binary":
714
+ var op = c[1], left = c[2], right = c[3];
715
+ if (!options.keep_comps) switch (op) {
716
+ case "<=" : return [ "binary", ">", left, right ];
717
+ case "<" : return [ "binary", ">=", left, right ];
718
+ case ">=" : return [ "binary", "<", left, right ];
719
+ case ">" : return [ "binary", "<=", left, right ];
720
+ }
721
+ switch (op) {
722
+ case "==" : return [ "binary", "!=", left, right ];
723
+ case "!=" : return [ "binary", "==", left, right ];
724
+ case "===" : return [ "binary", "!==", left, right ];
725
+ case "!==" : return [ "binary", "===", left, right ];
726
+ case "&&" : return best_of(not_c, [ "binary", "||", negate(left), negate(right) ]);
727
+ case "||" : return best_of(not_c, [ "binary", "&&", negate(left), negate(right) ]);
728
+ }
729
+ break;
730
+ }
731
+ return not_c;
732
+ };
733
+
734
+ function with_scope(s, cont) {
735
+ var _scope = scope;
736
+ scope = s;
737
+ var ret = cont();
738
+ ret.scope = s;
739
+ scope = _scope;
740
+ return ret;
741
+ };
742
+
743
+ function rmblock(block) {
744
+ if (block != null && block[0] == "block" && block[1]) {
745
+ if (block[1].length == 1)
746
+ block = block[1][0];
747
+ else if (block[1].length == 0)
748
+ block = [ "block" ];
749
+ }
750
+ return block;
751
+ };
752
+
753
+ function _lambda(name, args, body) {
754
+ return [ this[0], name, args, with_scope(body.scope, function(){
755
+ return tighten(MAP(body, walk), "lambda");
756
+ }) ];
757
+ };
758
+
759
+ // we get here for blocks that have been already transformed.
760
+ // this function does a few things:
761
+ // 1. discard useless blocks
762
+ // 2. join consecutive var declarations
763
+ // 3. remove obviously dead code
764
+ // 4. transform consecutive statements using the comma operator
765
+ // 5. if block_type == "lambda" and it detects constructs like if(foo) return ... - rewrite like if (!foo) { ... }
766
+ function tighten(statements, block_type) {
767
+ statements = statements.reduce(function(a, stat){
768
+ if (stat[0] == "block") {
769
+ if (stat[1]) {
770
+ a.push.apply(a, stat[1]);
771
+ }
772
+ } else {
773
+ a.push(stat);
774
+ }
775
+ return a;
776
+ }, []);
777
+
778
+ statements = (function(a, prev){
779
+ statements.forEach(function(cur){
780
+ if (prev && ((cur[0] == "var" && prev[0] == "var") ||
781
+ (cur[0] == "const" && prev[0] == "const"))) {
782
+ prev[1] = prev[1].concat(cur[1]);
783
+ } else {
784
+ a.push(cur);
785
+ prev = cur;
786
+ }
787
+ });
788
+ return a;
789
+ })([]);
790
+
791
+ if (options.dead_code) statements = (function(a, has_quit){
792
+ statements.forEach(function(st){
793
+ if (has_quit) {
794
+ if (member(st[0], [ "function", "defun" , "var", "const" ])) {
795
+ a.push(st);
796
+ }
797
+ else if (!options.no_warnings)
798
+ warn_unreachable(st);
799
+ }
800
+ else {
801
+ a.push(st);
802
+ if (member(st[0], [ "return", "throw", "break", "continue" ]))
803
+ has_quit = true;
804
+ }
805
+ });
806
+ return a;
807
+ })([]);
808
+
809
+ if (options.make_seqs) statements = (function(a, prev) {
810
+ statements.forEach(function(cur){
811
+ if (prev && prev[0] == "stat" && cur[0] == "stat") {
812
+ prev[1] = [ "seq", prev[1], cur[1] ];
813
+ } else {
814
+ a.push(cur);
815
+ prev = cur;
816
+ }
817
+ });
818
+ return a;
819
+ })([]);
820
+
821
+ if (block_type == "lambda") statements = (function(i, a, stat){
822
+ while (i < statements.length) {
823
+ stat = statements[i++];
824
+ if (stat[0] == "if" && !stat[3]) {
825
+ if (stat[2][0] == "return" && stat[2][1] == null) {
826
+ a.push(make_if(negate(stat[1]), [ "block", statements.slice(i) ]));
827
+ break;
828
+ }
829
+ var last = last_stat(stat[2]);
830
+ if (last[0] == "return" && last[1] == null) {
831
+ a.push(make_if(stat[1], [ "block", stat[2][1].slice(0, -1) ], [ "block", statements.slice(i) ]));
832
+ break;
833
+ }
834
+ }
835
+ a.push(stat);
836
+ }
837
+ return a;
838
+ })(0, []);
839
+
840
+ return statements;
841
+ };
842
+
843
+ function make_if(c, t, e) {
844
+ return when_constant(c, function(ast, val){
845
+ if (val) {
846
+ warn_unreachable(e);
847
+ return t;
848
+ } else {
849
+ warn_unreachable(t);
850
+ return e;
851
+ }
852
+ }, function() {
853
+ return make_real_if(c, t, e);
854
+ });
855
+ };
856
+
857
+ function make_real_if(c, t, e) {
858
+ c = walk(c);
859
+ t = walk(t);
860
+ e = walk(e);
861
+
862
+ if (empty(t)) {
863
+ c = negate(c);
864
+ t = e;
865
+ e = null;
866
+ } else if (empty(e)) {
867
+ e = null;
868
+ } else {
869
+ // if we have both else and then, maybe it makes sense to switch them?
870
+ (function(){
871
+ var a = gen_code(c);
872
+ var n = negate(c);
873
+ var b = gen_code(n);
874
+ if (b.length < a.length) {
875
+ var tmp = t;
876
+ t = e;
877
+ e = tmp;
878
+ c = n;
879
+ }
880
+ })();
881
+ }
882
+ if (empty(e) && empty(t))
883
+ return [ "stat", c ];
884
+ var ret = [ "if", c, t, e ];
885
+ if (t[0] == "if" && empty(t[3]) && empty(e)) {
886
+ ret = best_of(ret, walk([ "if", [ "binary", "&&", c, t[1] ], t[2] ]));
887
+ }
888
+ else if (t[0] == "stat") {
889
+ if (e) {
890
+ if (e[0] == "stat") {
891
+ ret = best_of(ret, [ "stat", make_conditional(c, t[1], e[1]) ]);
892
+ }
893
+ }
894
+ else {
895
+ ret = best_of(ret, [ "stat", make_conditional(c, t[1]) ]);
896
+ }
897
+ }
898
+ else if (e && t[0] == e[0] && (t[0] == "return" || t[0] == "throw") && t[1] && e[1]) {
899
+ ret = best_of(ret, [ t[0], make_conditional(c, t[1], e[1] ) ]);
900
+ }
901
+ else if (e && aborts(t)) {
902
+ ret = [ [ "if", c, t ] ];
903
+ if (e[0] == "block") {
904
+ if (e[1]) ret = ret.concat(e[1]);
905
+ }
906
+ else {
907
+ ret.push(e);
908
+ }
909
+ ret = walk([ "block", ret ]);
910
+ }
911
+ else if (t && aborts(e)) {
912
+ ret = [ [ "if", negate(c), e ] ];
913
+ if (t[0] == "block") {
914
+ if (t[1]) ret = ret.concat(t[1]);
915
+ } else {
916
+ ret.push(t);
917
+ }
918
+ ret = walk([ "block", ret ]);
919
+ }
920
+ return ret;
921
+ };
922
+
923
+ function _do_while(cond, body) {
924
+ return when_constant(cond, function(cond, val){
925
+ if (!val) {
926
+ warn_unreachable(body);
927
+ return [ "block" ];
928
+ } else {
929
+ return [ "for", null, null, null, walk(body) ];
930
+ }
931
+ });
932
+ };
933
+
934
+ return w.with_walkers({
935
+ "sub": function(expr, subscript) {
936
+ if (subscript[0] == "string") {
937
+ var name = subscript[1];
938
+ if (is_identifier(name))
939
+ return [ "dot", walk(expr), name ];
940
+ else if (/^[1-9][0-9]*$/.test(name) || name === "0")
941
+ return [ "sub", walk(expr), [ "num", parseInt(name, 10) ] ];
942
+ }
943
+ },
944
+ "if": make_if,
945
+ "toplevel": function(body) {
946
+ return [ "toplevel", with_scope(this.scope, function(){
947
+ return tighten(MAP(body, walk));
948
+ }) ];
949
+ },
950
+ "switch": function(expr, body) {
951
+ var last = body.length - 1;
952
+ return [ "switch", walk(expr), MAP(body, function(branch, i){
953
+ var block = tighten(MAP(branch[1], walk));
954
+ if (i == last && block.length > 0) {
955
+ var node = block[block.length - 1];
956
+ if (node[0] == "break" && !node[1])
957
+ block.pop();
958
+ }
959
+ return [ branch[0] ? walk(branch[0]) : null, block ];
960
+ }) ];
961
+ },
962
+ "function": function() {
963
+ var ret = _lambda.apply(this, arguments);
964
+ if (ret[1] && !HOP(scope.refs, ret[1])) {
965
+ ret[1] = null;
966
+ }
967
+ return ret;
968
+ },
969
+ "defun": _lambda,
970
+ "block": function(body) {
971
+ if (body) return rmblock([ "block", tighten(MAP(body, walk)) ]);
972
+ },
973
+ "binary": function(op, left, right) {
974
+ return when_constant([ "binary", op, walk(left), walk(right) ], function yes(c){
975
+ return best_of(walk(c), this);
976
+ }, function no() {
977
+ return this;
978
+ });
979
+ },
980
+ "conditional": function(c, t, e) {
981
+ return make_conditional(walk(c), walk(t), walk(e));
982
+ },
983
+ "try": function(t, c, f) {
984
+ return [
985
+ "try",
986
+ tighten(MAP(t, walk)),
987
+ c != null ? [ c[0], tighten(MAP(c[1], walk)) ] : null,
988
+ f != null ? tighten(MAP(f, walk)) : null
989
+ ];
990
+ },
991
+ "unary-prefix": function(op, expr) {
992
+ expr = walk(expr);
993
+ var ret = [ "unary-prefix", op, expr ];
994
+ if (op == "!")
995
+ ret = best_of(ret, negate(expr));
996
+ return when_constant(ret, function(ast, val){
997
+ return walk(ast); // it's either true or false, so minifies to !0 or !1
998
+ }, function() { return ret });
999
+ },
1000
+ "name": function(name) {
1001
+ switch (name) {
1002
+ case "true": return [ "unary-prefix", "!", [ "num", 0 ]];
1003
+ case "false": return [ "unary-prefix", "!", [ "num", 1 ]];
1004
+ }
1005
+ },
1006
+ "new": function(ctor, args) {
1007
+ if (ctor[0] == "name" && ctor[1] == "Array" && !scope.has("Array")) {
1008
+ if (args.length != 1) {
1009
+ return [ "array", args ];
1010
+ } else {
1011
+ return [ "call", [ "name", "Array" ], args ];
1012
+ }
1013
+ }
1014
+ },
1015
+ "call": function(expr, args) {
1016
+ if (expr[0] == "name" && expr[1] == "Array" && args.length != 1 && !scope.has("Array")) {
1017
+ return [ "array", args ];
1018
+ }
1019
+ },
1020
+ "while": _do_while,
1021
+ "do": _do_while
1022
+ }, function() {
1023
+ return walk(ast_add_scope(ast));
1024
+ });
1025
+ };
1026
+
1027
+ /* -----[ re-generate code from the AST ]----- */
1028
+
1029
+ var DOT_CALL_NO_PARENS = jsp.array_to_hash([
1030
+ "name",
1031
+ "array",
1032
+ "object",
1033
+ "string",
1034
+ "dot",
1035
+ "sub",
1036
+ "call",
1037
+ "regexp"
1038
+ ]);
1039
+
1040
+ function make_string(str, ascii_only) {
1041
+ var dq = 0, sq = 0;
1042
+ str = str.replace(/[\\\b\f\n\r\t\x22\x27\u2028\u2029]/g, function(s){
1043
+ switch (s) {
1044
+ case "\\": return "\\\\";
1045
+ case "\b": return "\\b";
1046
+ case "\f": return "\\f";
1047
+ case "\n": return "\\n";
1048
+ case "\r": return "\\r";
1049
+ case "\t": return "\\t";
1050
+ case "\u2028": return "\\u2028";
1051
+ case "\u2029": return "\\u2029";
1052
+ case '"': ++dq; return '"';
1053
+ case "'": ++sq; return "'";
1054
+ }
1055
+ return s;
1056
+ });
1057
+ if (ascii_only) str = to_ascii(str);
1058
+ if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'";
1059
+ else return '"' + str.replace(/\x22/g, '\\"') + '"';
1060
+ };
1061
+
1062
+ function to_ascii(str) {
1063
+ return str.replace(/[\u0080-\uffff]/g, function(ch) {
1064
+ var code = ch.charCodeAt(0).toString(16);
1065
+ while (code.length < 4) code = "0" + code;
1066
+ return "\\u" + code;
1067
+ });
1068
+ };
1069
+
1070
+ function gen_code(ast, options) {
1071
+ options = defaults(options, {
1072
+ indent_start : 0,
1073
+ indent_level : 4,
1074
+ quote_keys : false,
1075
+ space_colon : false,
1076
+ beautify : false,
1077
+ ascii_only : false
1078
+ });
1079
+ var beautify = !!options.beautify;
1080
+ var indentation = 0,
1081
+ newline = beautify ? "\n" : "",
1082
+ space = beautify ? " " : "";
1083
+
1084
+ function encode_string(str) {
1085
+ return make_string(str, options.ascii_only);
1086
+ };
1087
+
1088
+ function make_name(name) {
1089
+ name = name.toString();
1090
+ if (options.ascii_only)
1091
+ name = to_ascii(name);
1092
+ return name;
1093
+ };
1094
+
1095
+ function indent(line) {
1096
+ if (line == null)
1097
+ line = "";
1098
+ if (beautify)
1099
+ line = repeat_string(" ", options.indent_start + indentation * options.indent_level) + line;
1100
+ return line;
1101
+ };
1102
+
1103
+ function with_indent(cont, incr) {
1104
+ if (incr == null) incr = 1;
1105
+ indentation += incr;
1106
+ try { return cont.apply(null, slice(arguments, 1)); }
1107
+ finally { indentation -= incr; }
1108
+ };
1109
+
1110
+ function add_spaces(a) {
1111
+ if (beautify)
1112
+ return a.join(" ");
1113
+ var b = [];
1114
+ for (var i = 0; i < a.length; ++i) {
1115
+ var next = a[i + 1];
1116
+ b.push(a[i]);
1117
+ if (next &&
1118
+ ((/[a-z0-9_\x24]$/i.test(a[i].toString()) && /^[a-z0-9_\x24]/i.test(next.toString())) ||
1119
+ (/[\+\-]$/.test(a[i].toString()) && /^[\+\-]/.test(next.toString())))) {
1120
+ b.push(" ");
1121
+ }
1122
+ }
1123
+ return b.join("");
1124
+ };
1125
+
1126
+ function add_commas(a) {
1127
+ return a.join("," + space);
1128
+ };
1129
+
1130
+ function parenthesize(expr) {
1131
+ var gen = make(expr);
1132
+ for (var i = 1; i < arguments.length; ++i) {
1133
+ var el = arguments[i];
1134
+ if ((el instanceof Function && el(expr)) || expr[0] == el)
1135
+ return "(" + gen + ")";
1136
+ }
1137
+ return gen;
1138
+ };
1139
+
1140
+ function best_of(a) {
1141
+ if (a.length == 1) {
1142
+ return a[0];
1143
+ }
1144
+ if (a.length == 2) {
1145
+ var b = a[1];
1146
+ a = a[0];
1147
+ return a.length <= b.length ? a : b;
1148
+ }
1149
+ return best_of([ a[0], best_of(a.slice(1)) ]);
1150
+ };
1151
+
1152
+ function needs_parens(expr) {
1153
+ if (expr[0] == "function" || expr[0] == "object") {
1154
+ // dot/call on a literal function requires the
1155
+ // function literal itself to be parenthesized
1156
+ // only if it's the first "thing" in a
1157
+ // statement. This means that the parent is
1158
+ // "stat", but it could also be a "seq" and
1159
+ // we're the first in this "seq" and the
1160
+ // parent is "stat", and so on. Messy stuff,
1161
+ // but it worths the trouble.
1162
+ var a = slice($stack), self = a.pop(), p = a.pop();
1163
+ while (p) {
1164
+ if (p[0] == "stat") return true;
1165
+ if (((p[0] == "seq" || p[0] == "call" || p[0] == "dot" || p[0] == "sub" || p[0] == "conditional") && p[1] === self) ||
1166
+ ((p[0] == "binary" || p[0] == "assign" || p[0] == "unary-postfix") && p[2] === self)) {
1167
+ self = p;
1168
+ p = a.pop();
1169
+ } else {
1170
+ return false;
1171
+ }
1172
+ }
1173
+ }
1174
+ return !HOP(DOT_CALL_NO_PARENS, expr[0]);
1175
+ };
1176
+
1177
+ function make_num(num) {
1178
+ var str = num.toString(10), a = [ str.replace(/^0\./, ".") ], m;
1179
+ if (Math.floor(num) === num) {
1180
+ a.push("0x" + num.toString(16).toLowerCase(), // probably pointless
1181
+ "0" + num.toString(8)); // same.
1182
+ if ((m = /^(.*?)(0+)$/.exec(num))) {
1183
+ a.push(m[1] + "e" + m[2].length);
1184
+ }
1185
+ } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) {
1186
+ a.push(m[2] + "e-" + (m[1].length + m[2].length),
1187
+ str.substr(str.indexOf(".")));
1188
+ }
1189
+ return best_of(a);
1190
+ };
1191
+
1192
+ var generators = {
1193
+ "string": encode_string,
1194
+ "num": make_num,
1195
+ "name": make_name,
1196
+ "toplevel": function(statements) {
1197
+ return make_block_statements(statements)
1198
+ .join(newline + newline);
1199
+ },
1200
+ "block": make_block,
1201
+ "var": function(defs) {
1202
+ return "var " + add_commas(MAP(defs, make_1vardef)) + ";";
1203
+ },
1204
+ "const": function(defs) {
1205
+ return "const " + add_commas(MAP(defs, make_1vardef)) + ";";
1206
+ },
1207
+ "try": function(tr, ca, fi) {
1208
+ var out = [ "try", make_block(tr) ];
1209
+ if (ca) out.push("catch", "(" + ca[0] + ")", make_block(ca[1]));
1210
+ if (fi) out.push("finally", make_block(fi));
1211
+ return add_spaces(out);
1212
+ },
1213
+ "throw": function(expr) {
1214
+ return add_spaces([ "throw", make(expr) ]) + ";";
1215
+ },
1216
+ "new": function(ctor, args) {
1217
+ args = args.length > 0 ? "(" + add_commas(MAP(args, make)) + ")" : "";
1218
+ return add_spaces([ "new", parenthesize(ctor, "seq", "binary", "conditional", "assign", function(expr){
1219
+ var w = ast_walker(), has_call = {};
1220
+ try {
1221
+ w.with_walkers({
1222
+ "call": function() { throw has_call },
1223
+ "function": function() { return this }
1224
+ }, function(){
1225
+ w.walk(expr);
1226
+ });
1227
+ } catch(ex) {
1228
+ if (ex === has_call)
1229
+ return true;
1230
+ throw ex;
1231
+ }
1232
+ }) + args ]);
1233
+ },
1234
+ "switch": function(expr, body) {
1235
+ return add_spaces([ "switch", "(" + make(expr) + ")", make_switch_block(body) ]);
1236
+ },
1237
+ "break": function(label) {
1238
+ var out = "break";
1239
+ if (label != null)
1240
+ out += " " + make_name(label);
1241
+ return out + ";";
1242
+ },
1243
+ "continue": function(label) {
1244
+ var out = "continue";
1245
+ if (label != null)
1246
+ out += " " + make_name(label);
1247
+ return out + ";";
1248
+ },
1249
+ "conditional": function(co, th, el) {
1250
+ return add_spaces([ parenthesize(co, "assign", "seq", "conditional"), "?",
1251
+ parenthesize(th, "seq"), ":",
1252
+ parenthesize(el, "seq") ]);
1253
+ },
1254
+ "assign": function(op, lvalue, rvalue) {
1255
+ if (op && op !== true) op += "=";
1256
+ else op = "=";
1257
+ return add_spaces([ make(lvalue), op, parenthesize(rvalue, "seq") ]);
1258
+ },
1259
+ "dot": function(expr) {
1260
+ var out = make(expr), i = 1;
1261
+ if (expr[0] == "num") {
1262
+ if (!/\./.test(expr[1]))
1263
+ out += ".";
1264
+ } else if (needs_parens(expr))
1265
+ out = "(" + out + ")";
1266
+ while (i < arguments.length)
1267
+ out += "." + make_name(arguments[i++]);
1268
+ return out;
1269
+ },
1270
+ "call": function(func, args) {
1271
+ var f = make(func);
1272
+ if (needs_parens(func))
1273
+ f = "(" + f + ")";
1274
+ return f + "(" + add_commas(MAP(args, function(expr){
1275
+ return parenthesize(expr, "seq");
1276
+ })) + ")";
1277
+ },
1278
+ "function": make_function,
1279
+ "defun": make_function,
1280
+ "if": function(co, th, el) {
1281
+ var out = [ "if", "(" + make(co) + ")", el ? make_then(th) : make(th) ];
1282
+ if (el) {
1283
+ out.push("else", make(el));
1284
+ }
1285
+ return add_spaces(out);
1286
+ },
1287
+ "for": function(init, cond, step, block) {
1288
+ var out = [ "for" ];
1289
+ init = (init != null ? make(init) : "").replace(/;*\s*$/, ";" + space);
1290
+ cond = (cond != null ? make(cond) : "").replace(/;*\s*$/, ";" + space);
1291
+ step = (step != null ? make(step) : "").replace(/;*\s*$/, "");
1292
+ var args = init + cond + step;
1293
+ if (args == "; ; ") args = ";;";
1294
+ out.push("(" + args + ")", make(block));
1295
+ return add_spaces(out);
1296
+ },
1297
+ "for-in": function(vvar, key, hash, block) {
1298
+ return add_spaces([ "for", "(" +
1299
+ (vvar ? make(vvar).replace(/;+$/, "") : make(key)),
1300
+ "in",
1301
+ make(hash) + ")", make(block) ]);
1302
+ },
1303
+ "while": function(condition, block) {
1304
+ return add_spaces([ "while", "(" + make(condition) + ")", make(block) ]);
1305
+ },
1306
+ "do": function(condition, block) {
1307
+ return add_spaces([ "do", make(block), "while", "(" + make(condition) + ")" ]) + ";";
1308
+ },
1309
+ "return": function(expr) {
1310
+ var out = [ "return" ];
1311
+ if (expr != null) out.push(make(expr));
1312
+ return add_spaces(out) + ";";
1313
+ },
1314
+ "binary": function(operator, lvalue, rvalue) {
1315
+ var left = make(lvalue), right = make(rvalue);
1316
+ // XXX: I'm pretty sure other cases will bite here.
1317
+ // we need to be smarter.
1318
+ // adding parens all the time is the safest bet.
1319
+ if (member(lvalue[0], [ "assign", "conditional", "seq" ]) ||
1320
+ lvalue[0] == "binary" && PRECEDENCE[operator] > PRECEDENCE[lvalue[1]]) {
1321
+ left = "(" + left + ")";
1322
+ }
1323
+ if (member(rvalue[0], [ "assign", "conditional", "seq" ]) ||
1324
+ rvalue[0] == "binary" && PRECEDENCE[operator] >= PRECEDENCE[rvalue[1]] &&
1325
+ !(rvalue[1] == operator && member(operator, [ "&&", "||", "*" ]))) {
1326
+ right = "(" + right + ")";
1327
+ }
1328
+ return add_spaces([ left, operator, right ]);
1329
+ },
1330
+ "unary-prefix": function(operator, expr) {
1331
+ var val = make(expr);
1332
+ if (!(expr[0] == "num" || (expr[0] == "unary-prefix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
1333
+ val = "(" + val + ")";
1334
+ return operator + (jsp.is_alphanumeric_char(operator.charAt(0)) ? " " : "") + val;
1335
+ },
1336
+ "unary-postfix": function(operator, expr) {
1337
+ var val = make(expr);
1338
+ if (!(expr[0] == "num" || (expr[0] == "unary-postfix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
1339
+ val = "(" + val + ")";
1340
+ return val + operator;
1341
+ },
1342
+ "sub": function(expr, subscript) {
1343
+ var hash = make(expr);
1344
+ if (needs_parens(expr))
1345
+ hash = "(" + hash + ")";
1346
+ return hash + "[" + make(subscript) + "]";
1347
+ },
1348
+ "object": function(props) {
1349
+ if (props.length == 0)
1350
+ return "{}";
1351
+ return "{" + newline + with_indent(function(){
1352
+ return MAP(props, function(p){
1353
+ if (p.length == 3) {
1354
+ // getter/setter. The name is in p[0], the arg.list in p[1][2], the
1355
+ // body in p[1][3] and type ("get" / "set") in p[2].
1356
+ return indent(make_function(p[0], p[1][2], p[1][3], p[2]));
1357
+ }
1358
+ var key = p[0], val = make(p[1]);
1359
+ if (options.quote_keys) {
1360
+ key = encode_string(key);
1361
+ } else if ((typeof key == "number" || !beautify && +key + "" == key)
1362
+ && parseFloat(key) >= 0) {
1363
+ key = make_num(+key);
1364
+ } else if (!is_identifier(key)) {
1365
+ key = encode_string(key);
1366
+ }
1367
+ return indent(add_spaces(beautify && options.space_colon
1368
+ ? [ key, ":", val ]
1369
+ : [ key + ":", val ]));
1370
+ }).join("," + newline);
1371
+ }) + newline + indent("}");
1372
+ },
1373
+ "regexp": function(rx, mods) {
1374
+ return "/" + rx + "/" + mods;
1375
+ },
1376
+ "array": function(elements) {
1377
+ if (elements.length == 0) return "[]";
1378
+ return add_spaces([ "[", add_commas(MAP(elements, function(el){
1379
+ if (!beautify && el[0] == "atom" && el[1] == "undefined") return "";
1380
+ return parenthesize(el, "seq");
1381
+ })), "]" ]);
1382
+ },
1383
+ "stat": function(stmt) {
1384
+ return make(stmt).replace(/;*\s*$/, ";");
1385
+ },
1386
+ "seq": function() {
1387
+ return add_commas(MAP(slice(arguments), make));
1388
+ },
1389
+ "label": function(name, block) {
1390
+ return add_spaces([ make_name(name), ":", make(block) ]);
1391
+ },
1392
+ "with": function(expr, block) {
1393
+ return add_spaces([ "with", "(" + make(expr) + ")", make(block) ]);
1394
+ },
1395
+ "atom": function(name) {
1396
+ return make_name(name);
1397
+ }
1398
+ };
1399
+
1400
+ // The squeezer replaces "block"-s that contain only a single
1401
+ // statement with the statement itself; technically, the AST
1402
+ // is correct, but this can create problems when we output an
1403
+ // IF having an ELSE clause where the THEN clause ends in an
1404
+ // IF *without* an ELSE block (then the outer ELSE would refer
1405
+ // to the inner IF). This function checks for this case and
1406
+ // adds the block brackets if needed.
1407
+ function make_then(th) {
1408
+ if (th[0] == "do") {
1409
+ // https://github.com/mishoo/UglifyJS/issues/#issue/57
1410
+ // IE croaks with "syntax error" on code like this:
1411
+ // if (foo) do ... while(cond); else ...
1412
+ // we need block brackets around do/while
1413
+ return make([ "block", [ th ]]);
1414
+ }
1415
+ var b = th;
1416
+ while (true) {
1417
+ var type = b[0];
1418
+ if (type == "if") {
1419
+ if (!b[3])
1420
+ // no else, we must add the block
1421
+ return make([ "block", [ th ]]);
1422
+ b = b[3];
1423
+ }
1424
+ else if (type == "while" || type == "do") b = b[2];
1425
+ else if (type == "for" || type == "for-in") b = b[4];
1426
+ else break;
1427
+ }
1428
+ return make(th);
1429
+ };
1430
+
1431
+ function make_function(name, args, body, keyword) {
1432
+ var out = keyword || "function";
1433
+ if (name) {
1434
+ out += " " + make_name(name);
1435
+ }
1436
+ out += "(" + add_commas(MAP(args, make_name)) + ")";
1437
+ return add_spaces([ out, make_block(body) ]);
1438
+ };
1439
+
1440
+ function make_block_statements(statements) {
1441
+ for (var a = [], last = statements.length - 1, i = 0; i <= last; ++i) {
1442
+ var stat = statements[i];
1443
+ var code = make(stat);
1444
+ if (code != ";") {
1445
+ if (!beautify && i == last) {
1446
+ if ((stat[0] == "while" && empty(stat[2])) ||
1447
+ (member(stat[0], [ "for", "for-in"] ) && empty(stat[4])) ||
1448
+ (stat[0] == "if" && empty(stat[2]) && !stat[3]) ||
1449
+ (stat[0] == "if" && stat[3] && empty(stat[3]))) {
1450
+ code = code.replace(/;*\s*$/, ";");
1451
+ } else {
1452
+ code = code.replace(/;+\s*$/, "");
1453
+ }
1454
+ }
1455
+ a.push(code);
1456
+ }
1457
+ }
1458
+ return MAP(a, indent);
1459
+ };
1460
+
1461
+ function make_switch_block(body) {
1462
+ var n = body.length;
1463
+ if (n == 0) return "{}";
1464
+ return "{" + newline + MAP(body, function(branch, i){
1465
+ var has_body = branch[1].length > 0, code = with_indent(function(){
1466
+ return indent(branch[0]
1467
+ ? add_spaces([ "case", make(branch[0]) + ":" ])
1468
+ : "default:");
1469
+ }, 0.5) + (has_body ? newline + with_indent(function(){
1470
+ return make_block_statements(branch[1]).join(newline);
1471
+ }) : "");
1472
+ if (!beautify && has_body && i < n - 1)
1473
+ code += ";";
1474
+ return code;
1475
+ }).join(newline) + newline + indent("}");
1476
+ };
1477
+
1478
+ function make_block(statements) {
1479
+ if (!statements) return ";";
1480
+ if (statements.length == 0) return "{}";
1481
+ return "{" + newline + with_indent(function(){
1482
+ return make_block_statements(statements).join(newline);
1483
+ }) + newline + indent("}");
1484
+ };
1485
+
1486
+ function make_1vardef(def) {
1487
+ var name = def[0], val = def[1];
1488
+ if (val != null)
1489
+ name = add_spaces([ make_name(name), "=", make(val) ]);
1490
+ return name;
1491
+ };
1492
+
1493
+ var $stack = [];
1494
+
1495
+ function make(node) {
1496
+ var type = node[0];
1497
+ var gen = generators[type];
1498
+ if (!gen)
1499
+ throw new Error("Can't find generator for \"" + type + "\"");
1500
+ $stack.push(node);
1501
+ var ret = gen.apply(type, node.slice(1));
1502
+ $stack.pop();
1503
+ return ret;
1504
+ };
1505
+
1506
+ return make(ast);
1507
+ };
1508
+
1509
+ function split_lines(code, max_line_length) {
1510
+ var splits = [ 0 ];
1511
+ jsp.parse(function(){
1512
+ var next_token = jsp.tokenizer(code);
1513
+ var last_split = 0;
1514
+ var prev_token;
1515
+ function current_length(tok) {
1516
+ return tok.pos - last_split;
1517
+ };
1518
+ function split_here(tok) {
1519
+ last_split = tok.pos;
1520
+ splits.push(last_split);
1521
+ };
1522
+ function custom(){
1523
+ var tok = next_token.apply(this, arguments);
1524
+ out: {
1525
+ if (prev_token) {
1526
+ if (prev_token.type == "keyword") break out;
1527
+ }
1528
+ if (current_length(tok) > max_line_length) {
1529
+ switch (tok.type) {
1530
+ case "keyword":
1531
+ case "atom":
1532
+ case "name":
1533
+ case "punc":
1534
+ split_here(tok);
1535
+ break out;
1536
+ }
1537
+ }
1538
+ }
1539
+ prev_token = tok;
1540
+ return tok;
1541
+ };
1542
+ custom.context = function() {
1543
+ return next_token.context.apply(this, arguments);
1544
+ };
1545
+ return custom;
1546
+ }());
1547
+ return splits.map(function(pos, i){
1548
+ return code.substring(pos, splits[i + 1] || code.length);
1549
+ }).join("\n");
1550
+ };
1551
+
1552
+ /* -----[ Utilities ]----- */
1553
+
1554
+ function repeat_string(str, i) {
1555
+ if (i <= 0) return "";
1556
+ if (i == 1) return str;
1557
+ var d = repeat_string(str, i >> 1);
1558
+ d += d;
1559
+ if (i & 1) d += str;
1560
+ return d;
1561
+ };
1562
+
1563
+ function defaults(args, defs) {
1564
+ var ret = {};
1565
+ if (args === true)
1566
+ args = {};
1567
+ for (var i in defs) if (HOP(defs, i)) {
1568
+ ret[i] = (args && HOP(args, i)) ? args[i] : defs[i];
1569
+ }
1570
+ return ret;
1571
+ };
1572
+
1573
+ function is_identifier(name) {
1574
+ return /^[a-z_$][a-z0-9_$]*$/i.test(name)
1575
+ && name != "this"
1576
+ && !HOP(jsp.KEYWORDS_ATOM, name)
1577
+ && !HOP(jsp.RESERVED_WORDS, name)
1578
+ && !HOP(jsp.KEYWORDS, name);
1579
+ };
1580
+
1581
+ function HOP(obj, prop) {
1582
+ return Object.prototype.hasOwnProperty.call(obj, prop);
1583
+ };
1584
+
1585
+ // some utilities
1586
+
1587
+ var MAP;
1588
+
1589
+ (function(){
1590
+ MAP = function(a, f, o) {
1591
+ var ret = [];
1592
+ for (var i = 0; i < a.length; ++i) {
1593
+ var val = f.call(o, a[i], i);
1594
+ if (val instanceof AtTop) ret.unshift(val.v);
1595
+ else ret.push(val);
1596
+ }
1597
+ return ret;
1598
+ };
1599
+ MAP.at_top = function(val) { return new AtTop(val) };
1600
+ function AtTop(val) { this.v = val };
1601
+ })();
1602
+
1603
+ /* -----[ Exports ]----- */
1604
+
1605
+ exports.ast_walker = ast_walker;
1606
+ exports.ast_mangle = ast_mangle;
1607
+ exports.ast_squeeze = ast_squeeze;
1608
+ exports.gen_code = gen_code;
1609
+ exports.ast_add_scope = ast_add_scope;
1610
+ exports.set_logger = function(logger) { warn = logger };
1611
+ exports.make_string = make_string;
1612
+ exports.split_lines = split_lines;
1613
+ exports.MAP = MAP;
1614
+
1615
+ // keep this last!
1616
+ exports.ast_squeeze_more = require("./squeeze-more").ast_squeeze_more;