uglifier 0.1.0

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,1299 @@
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, include_toplevel) -- mangles the
14
+ variable/function names in the AST. Returns an AST. Pass true
15
+ as second argument to mangle toplevel names too.
16
+
17
+ - ast_squeeze(ast) -- employs various optimizations to make the
18
+ final generated code even smaller. Returns an AST.
19
+
20
+ - gen_code(ast, beautify) -- generates JS code from the AST. Pass
21
+ true (or an object, see the code for some options) as second
22
+ argument to get "pretty" (indented) code.
23
+
24
+ -------------------------------- (C) ---------------------------------
25
+
26
+ Author: Mihai Bazon
27
+ <mihai.bazon@gmail.com>
28
+ http://mihai.bazon.net/blog
29
+
30
+ Distributed under a ZLIB license:
31
+
32
+ Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
33
+
34
+ This software is provided 'as-is', without any express or implied
35
+ warranty. In no event will the authors be held liable for any
36
+ damages arising from the use of this software.
37
+
38
+ Permission is granted to anyone to use this software for any
39
+ purpose, including commercial applications, and to alter it and
40
+ redistribute it freely, subject to the following restrictions:
41
+
42
+ 1. The origin of this software must not be misrepresented; you must
43
+ not claim that you wrote the original software. If you use this
44
+ software in a product, an acknowledgment in the product
45
+ documentation would be appreciated but is not required.
46
+
47
+ 2. Altered source versions must be plainly marked as such, and must
48
+ not be misrepresented as being the original software.
49
+
50
+ 3. This notice may not be removed or altered from any source
51
+ distribution.
52
+
53
+ ***********************************************************************/
54
+
55
+ var jsp = require("./parse-js"),
56
+ slice = jsp.slice,
57
+ member = jsp.member,
58
+ PRECEDENCE = jsp.PRECEDENCE,
59
+ OPERATORS = jsp.OPERATORS;
60
+
61
+ var sys = require(/^v0\.[012]/.test(process.version) ? "sys" : "util");
62
+
63
+ /* -----[ helper for AST traversal ]----- */
64
+
65
+ function ast_walker(ast) {
66
+ function _vardefs(defs) {
67
+ return defs.map(function(def){
68
+ var a = [ def[0] ];
69
+ if (def.length > 1)
70
+ a[1] = walk(def[1]);
71
+ return a;
72
+ });
73
+ };
74
+ var walkers = {
75
+ "string": function(str) {
76
+ return [ "string", str ];
77
+ },
78
+ "num": function(num) {
79
+ return [ "num", num ];
80
+ },
81
+ "name": function(name) {
82
+ return [ "name", name ];
83
+ },
84
+ "toplevel": function(statements) {
85
+ return [ "toplevel", statements.map(walk) ];
86
+ },
87
+ "block": function(statements) {
88
+ var out = [ "block" ];
89
+ if (statements != null)
90
+ out.push(statements.map(walk));
91
+ return out;
92
+ },
93
+ "var": function(defs) {
94
+ return [ "var", _vardefs(defs) ];
95
+ },
96
+ "const": function(defs) {
97
+ return [ "const", _vardefs(defs) ];
98
+ },
99
+ "try": function(t, c, f) {
100
+ return [
101
+ "try",
102
+ t.map(walk),
103
+ c != null ? [ c[0], c[1].map(walk) ] : null,
104
+ f != null ? f.map(walk) : null
105
+ ];
106
+ },
107
+ "throw": function(expr) {
108
+ return [ "throw", walk(expr) ];
109
+ },
110
+ "new": function(ctor, args) {
111
+ return [ "new", walk(ctor), args.map(walk) ];
112
+ },
113
+ "switch": function(expr, body) {
114
+ return [ "switch", walk(expr), body.map(function(branch){
115
+ return [ branch[0] ? walk(branch[0]) : null,
116
+ branch[1].map(walk) ];
117
+ }) ];
118
+ },
119
+ "break": function(label) {
120
+ return [ "break", label ];
121
+ },
122
+ "continue": function(label) {
123
+ return [ "continue", label ];
124
+ },
125
+ "conditional": function(cond, t, e) {
126
+ return [ "conditional", walk(cond), walk(t), walk(e) ];
127
+ },
128
+ "assign": function(op, lvalue, rvalue) {
129
+ return [ "assign", op, walk(lvalue), walk(rvalue) ];
130
+ },
131
+ "dot": function(expr) {
132
+ return [ "dot", walk(expr) ].concat(slice(arguments, 1));
133
+ },
134
+ "call": function(expr, args) {
135
+ return [ "call", walk(expr), args.map(walk) ];
136
+ },
137
+ "function": function(name, args, body) {
138
+ return [ "function", name, args.slice(), body.map(walk) ];
139
+ },
140
+ "defun": function(name, args, body) {
141
+ return [ "defun", name, args.slice(), body.map(walk) ];
142
+ },
143
+ "if": function(conditional, t, e) {
144
+ return [ "if", walk(conditional), walk(t), walk(e) ];
145
+ },
146
+ "for": function(init, cond, step, block) {
147
+ return [ "for", walk(init), walk(cond), walk(step), walk(block) ];
148
+ },
149
+ "for-in": function(has_var, key, hash, block) {
150
+ return [ "for-in", has_var, key, walk(hash), walk(block) ];
151
+ },
152
+ "while": function(cond, block) {
153
+ return [ "while", walk(cond), walk(block) ];
154
+ },
155
+ "do": function(cond, block) {
156
+ return [ "do", walk(cond), walk(block) ];
157
+ },
158
+ "return": function(expr) {
159
+ return [ "return", walk(expr) ];
160
+ },
161
+ "binary": function(op, left, right) {
162
+ return [ "binary", op, walk(left), walk(right) ];
163
+ },
164
+ "unary-prefix": function(op, expr) {
165
+ return [ "unary-prefix", op, walk(expr) ];
166
+ },
167
+ "unary-postfix": function(op, expr) {
168
+ return [ "unary-postfix", op, walk(expr) ];
169
+ },
170
+ "sub": function(expr, subscript) {
171
+ return [ "sub", walk(expr), walk(subscript) ];
172
+ },
173
+ "object": function(props) {
174
+ return [ "object", props.map(function(p){
175
+ return [ p[0], walk(p[1]) ];
176
+ }) ];
177
+ },
178
+ "regexp": function(rx, mods) {
179
+ return [ "regexp", rx, mods ];
180
+ },
181
+ "array": function(elements) {
182
+ return [ "array", elements.map(walk) ];
183
+ },
184
+ "stat": function(stat) {
185
+ return [ "stat", walk(stat) ];
186
+ },
187
+ "seq": function() {
188
+ return [ "seq" ].concat(slice(arguments).map(walk));
189
+ },
190
+ "label": function(name, block) {
191
+ return [ "label", name, walk(block) ];
192
+ },
193
+ "with": function(expr, block) {
194
+ return [ "with", walk(expr), walk(block) ];
195
+ },
196
+ "atom": function(name) {
197
+ return [ "atom", name ];
198
+ }
199
+ };
200
+
201
+ var user = {};
202
+ var stack = [];
203
+ function walk(ast) {
204
+ if (ast == null)
205
+ return null;
206
+ try {
207
+ stack.push(ast);
208
+ var type = ast[0];
209
+ var gen = user[type];
210
+ if (gen) {
211
+ var ret = gen.apply(ast, ast.slice(1));
212
+ if (ret != null)
213
+ return ret;
214
+ }
215
+ gen = walkers[type];
216
+ return gen.apply(ast, ast.slice(1));
217
+ } finally {
218
+ stack.pop();
219
+ }
220
+ };
221
+
222
+ function with_walkers(walkers, cont){
223
+ var save = {}, i;
224
+ for (i in walkers) if (HOP(walkers, i)) {
225
+ save[i] = user[i];
226
+ user[i] = walkers[i];
227
+ }
228
+ try { return cont(); }
229
+ finally {
230
+ for (i in save) if (HOP(save, i)) {
231
+ if (!save[i]) delete user[i];
232
+ else user[i] = save[i];
233
+ }
234
+ }
235
+ };
236
+
237
+ return {
238
+ walk: walk,
239
+ with_walkers: with_walkers,
240
+ parent: function() {
241
+ return stack[stack.length - 2]; // last one is current node
242
+ },
243
+ stack: function() {
244
+ return stack;
245
+ }
246
+ };
247
+ };
248
+
249
+ /* -----[ Scope and mangling ]----- */
250
+
251
+ function Scope(parent) {
252
+ this.names = {}; // names defined in this scope
253
+ this.mangled = {}; // mangled names (orig.name => mangled)
254
+ this.rev_mangled = {}; // reverse lookup (mangled => orig.name)
255
+ this.cname = -1; // current mangled name
256
+ this.refs = {}; // names referenced from this scope
257
+ this.uses_with = false; // will become TRUE if eval() is detected in this or any subscopes
258
+ this.uses_eval = false; // will become TRUE if with() is detected in this or any subscopes
259
+ this.parent = parent; // parent scope
260
+ this.children = []; // sub-scopes
261
+ if (parent) {
262
+ this.level = parent.level + 1;
263
+ parent.children.push(this);
264
+ } else {
265
+ this.level = 0;
266
+ }
267
+ };
268
+
269
+ var base54 = (function(){
270
+ var DIGITS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_";
271
+ return function(num) {
272
+ var ret = "";
273
+ do {
274
+ ret = DIGITS.charAt(num % 54) + ret;
275
+ num = Math.floor(num / 54);
276
+ } while (num > 0);
277
+ return ret;
278
+ };
279
+ })();
280
+
281
+ Scope.prototype = {
282
+ has: function(name) {
283
+ for (var s = this; s; s = s.parent)
284
+ if (HOP(s.names, name))
285
+ return s;
286
+ },
287
+ has_mangled: function(mname) {
288
+ for (var s = this; s; s = s.parent)
289
+ if (HOP(s.rev_mangled, mname))
290
+ return s;
291
+ },
292
+ toJSON: function() {
293
+ return {
294
+ names: this.names,
295
+ uses_eval: this.uses_eval,
296
+ uses_with: this.uses_with
297
+ };
298
+ },
299
+
300
+ next_mangled: function() {
301
+ // we must be careful that the new mangled name:
302
+ //
303
+ // 1. doesn't shadow a mangled name from a parent
304
+ // scope, unless we don't reference the original
305
+ // name from this scope OR from any sub-scopes!
306
+ // This will get slow.
307
+ //
308
+ // 2. doesn't shadow an original name from a parent
309
+ // scope, in the event that the name is not mangled
310
+ // in the parent scope and we reference that name
311
+ // here OR IN ANY SUBSCOPES!
312
+ //
313
+ // 3. doesn't shadow a name that is referenced but not
314
+ // defined (possibly global defined elsewhere).
315
+ for (;;) {
316
+ var m = base54(++this.cname), prior;
317
+
318
+ // case 1.
319
+ prior = this.has_mangled(m);
320
+ if (prior && this.refs[prior.rev_mangled[m]] === prior)
321
+ continue;
322
+
323
+ // case 2.
324
+ prior = this.has(m);
325
+ if (prior && prior !== this && this.refs[m] === prior && !prior.has_mangled(m))
326
+ continue;
327
+
328
+ // case 3.
329
+ if (HOP(this.refs, m) && this.refs[m] == null)
330
+ continue;
331
+
332
+ // I got "do" once. :-/
333
+ if (!is_identifier(m))
334
+ continue;
335
+
336
+ return m;
337
+ }
338
+ },
339
+ get_mangled: function(name, newMangle) {
340
+ if (this.uses_eval || this.uses_with) return name; // no mangle if eval or with is in use
341
+ var s = this.has(name);
342
+ if (!s) return name; // not in visible scope, no mangle
343
+ if (HOP(s.mangled, name)) return s.mangled[name]; // already mangled in this scope
344
+ if (!newMangle) return name; // not found and no mangling requested
345
+
346
+ var m = s.next_mangled();
347
+ s.rev_mangled[m] = name;
348
+ return s.mangled[name] = m;
349
+ },
350
+ define: function(name) {
351
+ if (name != null)
352
+ return this.names[name] = name;
353
+ }
354
+ };
355
+
356
+ function ast_add_scope(ast) {
357
+
358
+ var current_scope = null;
359
+ var w = ast_walker(), walk = w.walk;
360
+ var having_eval = [];
361
+
362
+ function with_new_scope(cont) {
363
+ current_scope = new Scope(current_scope);
364
+ try {
365
+ var ret = current_scope.body = cont();
366
+ ret.scope = current_scope;
367
+ return ret;
368
+ }
369
+ finally {
370
+ current_scope = current_scope.parent;
371
+ }
372
+ };
373
+
374
+ function define(name) {
375
+ return current_scope.define(name);
376
+ };
377
+
378
+ function reference(name) {
379
+ current_scope.refs[name] = true;
380
+ };
381
+
382
+ function _lambda(name, args, body) {
383
+ return [ this[0], define(name), args, with_new_scope(function(){
384
+ args.map(define);
385
+ return body.map(walk);
386
+ })];
387
+ };
388
+
389
+ return with_new_scope(function(){
390
+ // process AST
391
+ var ret = w.with_walkers({
392
+ "function": _lambda,
393
+ "defun": _lambda,
394
+ "with": function(expr, block) {
395
+ for (var s = current_scope; s; s = s.parent)
396
+ s.uses_with = true;
397
+ },
398
+ "var": function(defs) {
399
+ defs.map(function(d){ define(d[0]) });
400
+ },
401
+ "const": function(defs) {
402
+ defs.map(function(d){ define(d[0]) });
403
+ },
404
+ "try": function(t, c, f) {
405
+ if (c != null) return [
406
+ "try",
407
+ t.map(walk),
408
+ with_new_scope(function(){
409
+ return [ define(c[0]), c[1].map(walk) ];
410
+ }),
411
+ f != null ? f.map(walk) : null
412
+ ];
413
+ },
414
+ "name": function(name) {
415
+ if (name == "eval")
416
+ having_eval.push(current_scope);
417
+ reference(name);
418
+ },
419
+ "for-in": function(has_var, name) {
420
+ if (has_var) define(name);
421
+ else reference(name);
422
+ }
423
+ }, function(){
424
+ return walk(ast);
425
+ });
426
+
427
+ // the reason why we need an additional pass here is
428
+ // that names can be used prior to their definition.
429
+
430
+ // scopes where eval was detected and their parents
431
+ // are marked with uses_eval, unless they define the
432
+ // "eval" name.
433
+ having_eval.map(function(scope){
434
+ if (!scope.has("eval")) while (scope) {
435
+ scope.uses_eval = true;
436
+ scope = scope.parent;
437
+ }
438
+ });
439
+
440
+ // for referenced names it might be useful to know
441
+ // their origin scope. current_scope here is the
442
+ // toplevel one.
443
+ function fixrefs(scope, i) {
444
+ // do children first; order shouldn't matter
445
+ for (i = scope.children.length; --i >= 0;)
446
+ fixrefs(scope.children[i]);
447
+ for (i in scope.refs) if (HOP(scope.refs, i)) {
448
+ // find origin scope and propagate the reference to origin
449
+ for (var origin = scope.has(i), s = scope; s; s = s.parent) {
450
+ s.refs[i] = origin;
451
+ if (s === origin) break;
452
+ }
453
+ }
454
+ };
455
+ fixrefs(current_scope);
456
+
457
+ return ret;
458
+ });
459
+
460
+ };
461
+
462
+ /* -----[ mangle names ]----- */
463
+
464
+ function ast_mangle(ast, do_toplevel) {
465
+ var w = ast_walker(), walk = w.walk, scope;
466
+
467
+ function get_mangled(name, newMangle) {
468
+ if (!do_toplevel && !scope.parent) return name; // don't mangle toplevel
469
+ return scope.get_mangled(name, newMangle);
470
+ };
471
+
472
+ function _lambda(name, args, body) {
473
+ if (name) name = get_mangled(name);
474
+ body = with_scope(body.scope, function(){
475
+ args = args.map(function(name){ return get_mangled(name) });
476
+ return body.map(walk);
477
+ });
478
+ return [ this[0], name, args, body ];
479
+ };
480
+
481
+ function with_scope(s, cont) {
482
+ var _scope = scope;
483
+ scope = s;
484
+ for (var i in s.names) if (HOP(s.names, i)) {
485
+ get_mangled(i, true);
486
+ }
487
+ try { var ret = cont(); ret.scope = s; return ret; }
488
+ finally { scope = _scope; };
489
+ };
490
+
491
+ function _vardefs(defs) {
492
+ return defs.map(function(d){
493
+ return [ get_mangled(d[0]), walk(d[1]) ];
494
+ });
495
+ };
496
+
497
+ return w.with_walkers({
498
+ "function": _lambda,
499
+ "defun": _lambda,
500
+ "var": function(defs) {
501
+ return [ "var", _vardefs(defs) ];
502
+ },
503
+ "const": function(defs) {
504
+ return [ "const", _vardefs(defs) ];
505
+ },
506
+ "name": function(name) {
507
+ return [ "name", get_mangled(name) ];
508
+ },
509
+ "try": function(t, c, f) {
510
+ return [ "try",
511
+ t.map(walk),
512
+ c ? with_scope(c.scope, function(){
513
+ return [ get_mangled(c[0]), c[1].map(walk) ];
514
+ }) : null,
515
+ f != null ? f.map(walk) : null ];
516
+ },
517
+ "toplevel": function(body) {
518
+ return with_scope(this.scope, function(){
519
+ return [ "toplevel", body.map(walk) ];
520
+ });
521
+ },
522
+ "for-in": function(has_var, name, obj, stat) {
523
+ return [ "for-in", has_var, get_mangled(name), walk(obj), walk(stat) ];
524
+ }
525
+ }, function() {
526
+ return walk(ast_add_scope(ast));
527
+ });
528
+ };
529
+
530
+ // function ast_has_side_effects(ast) {
531
+ // var w = ast_walker();
532
+ // var FOUND_SIDE_EFFECTS = {};
533
+ // function _found() { throw FOUND_SIDE_EFFECTS };
534
+ // try {
535
+ // w.with_walkers({
536
+ // "new": _found,
537
+ // "call": _found,
538
+ // "assign": _found,
539
+ // "defun": _found,
540
+ // "var": _found,
541
+ // "const": _found,
542
+ // "throw": _found,
543
+ // "return": _found,
544
+ // "break": _found,
545
+ // "continue": _found,
546
+ // "label": _found,
547
+ // "function": function(name) {
548
+ // if (name) _found();
549
+ // }
550
+ // }, function(){
551
+ // w.walk(ast);
552
+ // });
553
+ // } catch(ex) {
554
+ // if (ex === FOUND_SIDE_EFFECTS)
555
+ // return true;
556
+ // throw ex;
557
+ // }
558
+ // };
559
+
560
+ /* -----[
561
+ - compress foo["bar"] into foo.bar,
562
+ - remove block brackets {} where possible
563
+ - join consecutive var declarations
564
+ - various optimizations for IFs:
565
+ - if (cond) foo(); else bar(); ==> cond?foo():bar();
566
+ - if (cond) foo(); ==> cond&&foo();
567
+ - if (foo) return bar(); else return baz(); ==> return foo?bar():baz(); // also for throw
568
+ - if (foo) return bar(); else something(); ==> {if(foo)return bar();something()}
569
+ ]----- */
570
+
571
+ function warn(msg) {
572
+ sys.debug(msg);
573
+ };
574
+
575
+ function ast_squeeze(ast, options) {
576
+ options = defaults(options, {
577
+ make_seqs: true,
578
+ dead_code: true,
579
+ no_warnings: false
580
+ });
581
+
582
+ var w = ast_walker(), walk = w.walk;
583
+
584
+ function is_constant(node) {
585
+ return node[0] == "string" || node[0] == "num";
586
+ };
587
+
588
+ function rmblock(block) {
589
+ if (block != null && block[0] == "block" && block[1] && block[1].length == 1)
590
+ block = block[1][0];
591
+ return block;
592
+ };
593
+
594
+ function _lambda(name, args, body) {
595
+ return [ this[0], name, args, tighten(body.map(walk), "lambda") ];
596
+ };
597
+
598
+ // we get here for blocks that have been already transformed.
599
+ // this function does two things:
600
+ // 1. discard useless blocks
601
+ // 2. join consecutive var declarations
602
+ // 3. remove obviously dead code
603
+ // 4. transform consecutive statements using the comma operator
604
+ function tighten(statements, block_type) {
605
+ statements = statements.reduce(function(a, stat){
606
+ if (stat[0] == "block") {
607
+ if (stat[1]) {
608
+ a.push.apply(a, stat[1]);
609
+ }
610
+ } else {
611
+ a.push(stat);
612
+ }
613
+ return a;
614
+ }, []);
615
+
616
+ statements = (function(a, prev){
617
+ statements.forEach(function(cur){
618
+ if (prev && ((cur[0] == "var" && prev[0] == "var") ||
619
+ (cur[0] == "const" && prev[0] == "const"))) {
620
+ prev[1] = prev[1].concat(cur[1]);
621
+ } else {
622
+ a.push(cur);
623
+ prev = cur;
624
+ }
625
+ });
626
+ return a;
627
+ })([]);
628
+
629
+ if (options.dead_code) statements = (function(a, has_quit){
630
+ statements.forEach(function(st){
631
+ if (has_quit) {
632
+ if (member(st[0], [ "function", "defun" , "var", "const" ])) {
633
+ a.push(st);
634
+ }
635
+ else if (!options.no_warnings)
636
+ warn("Removing unreachable code: " + gen_code(st, true));
637
+ }
638
+ else {
639
+ a.push(st);
640
+ if (member(st[0], [ "return", "throw", "break", "continue" ]))
641
+ has_quit = true;
642
+ }
643
+ });
644
+ return a;
645
+ })([]);
646
+
647
+ if (options.make_seqs) statements = (function(a, prev) {
648
+ statements.forEach(function(cur){
649
+ if (!prev) {
650
+ a.push(cur);
651
+ if (cur[0] == "stat") prev = cur;
652
+ } else if (cur[0] == "stat" && prev[0] == "stat") {
653
+ prev[1] = [ "seq", prev[1], cur[1] ];
654
+ } else {
655
+ a.push(cur);
656
+ prev = null;
657
+ }
658
+ });
659
+ return a;
660
+ })([]);
661
+
662
+ if (block_type == "lambda") statements = (function(i, a, stat){
663
+ while (i < statements.length) {
664
+ stat = statements[i++];
665
+ if (stat[0] == "if" && stat[2][0] == "return" && stat[2][1] == null && !stat[3]) {
666
+ a.push(make_if(negate(stat[1]), [ "block", statements.slice(i) ]));
667
+ break;
668
+ } else {
669
+ a.push(stat);
670
+ }
671
+ }
672
+ return a;
673
+ })(0, []);
674
+
675
+ return statements;
676
+ };
677
+
678
+ function best_of(ast1, ast2) {
679
+ return gen_code(ast1).length > gen_code(ast2[0] == "stat" ? ast2[1] : ast2).length ? ast2 : ast1;
680
+ };
681
+
682
+ function aborts(t) {
683
+ if (t[0] == "block" && t[1] && t[1].length > 0)
684
+ t = t[1][t[1].length - 1]; // interested in last statement
685
+ if (t[0] == "return" || t[0] == "break" || t[0] == "continue" || t[0] == "throw")
686
+ return true;
687
+ };
688
+
689
+ function negate(c) {
690
+ if (c[0] == "unary-prefix" && c[1] == "!") return c[2];
691
+ else return [ "unary-prefix", "!", c ];
692
+ };
693
+
694
+ function make_conditional(c, t, e) {
695
+ if (c[0] == "unary-prefix" && c[1] == "!") {
696
+ return e ? [ "conditional", c[2], e, t ] : [ "binary", "||", c[2], t ];
697
+ } else {
698
+ return e ? [ "conditional", c, t, e ] : [ "binary", "&&", c, t ];
699
+ }
700
+ };
701
+
702
+ function empty(b) {
703
+ return !b || (b[0] == "block" && (!b[1] || b[1].length == 0));
704
+ };
705
+
706
+ function make_if(c, t, e) {
707
+ c = walk(c);
708
+ t = walk(t);
709
+ e = walk(e);
710
+ var negated = c[0] == "unary-prefix" && c[1] == "!";
711
+ if (empty(t)) {
712
+ if (negated) c = c[2];
713
+ else c = [ "unary-prefix", "!", c ];
714
+ t = e;
715
+ e = null;
716
+ }
717
+ if (empty(e)) {
718
+ e = null;
719
+ } else {
720
+ if (negated) {
721
+ c = c[2];
722
+ var tmp = t; t = e; e = tmp;
723
+ }
724
+ }
725
+ if (empty(e) && empty(t))
726
+ return [ "stat", c ];
727
+ var ret = [ "if", c, t, e ];
728
+ if (t[0] == "stat") {
729
+ if (e) {
730
+ if (e[0] == "stat") {
731
+ ret = best_of(ret, [ "stat", make_conditional(c, t[1], e[1]) ]);
732
+ }
733
+ }
734
+ else {
735
+ ret = best_of(ret, [ "stat", make_conditional(c, t[1]) ]);
736
+ }
737
+ }
738
+ else if (e && t[0] == e[0] && (t[0] == "return" || t[0] == "throw")) {
739
+ ret = best_of(ret, [ t[0], make_conditional(c, t[1], e[1] ) ]);
740
+ }
741
+ else if (e && aborts(t)) {
742
+ ret = [ [ "if", c, t ] ];
743
+ if (e[0] == "block") {
744
+ if (e[1]) ret = ret.concat(e[1]);
745
+ }
746
+ else {
747
+ ret.push(e);
748
+ }
749
+ ret = walk([ "block", ret ]);
750
+ }
751
+ return ret;
752
+ };
753
+
754
+ return w.with_walkers({
755
+ "sub": function(expr, subscript) {
756
+ if (subscript[0] == "string") {
757
+ var name = subscript[1];
758
+ if (is_identifier(name)) {
759
+ return [ "dot", walk(expr), name ];
760
+ }
761
+ }
762
+ },
763
+ "if": make_if,
764
+ "toplevel": function(body) {
765
+ return [ "toplevel", tighten(body.map(walk)) ];
766
+ },
767
+ "switch": function(expr, body) {
768
+ var last = body.length - 1;
769
+ return [ "switch", walk(expr), body.map(function(branch, i){
770
+ var block = tighten(branch[1].map(walk));
771
+ if (i == last && block.length > 0) {
772
+ var node = block[block.length - 1];
773
+ if (node[0] == "break" && !node[1])
774
+ block.pop();
775
+ }
776
+ return [ branch[0] ? walk(branch[0]) : null, block ];
777
+ }) ];
778
+ },
779
+ "function": _lambda,
780
+ "defun": _lambda,
781
+ "block": function(body) {
782
+ if (body) return rmblock([ "block", tighten(body.map(walk)) ]);
783
+ },
784
+ "binary": function(op, left, right) {
785
+ left = walk(left);
786
+ right = walk(right);
787
+ var best = [ "binary", op, left, right ];
788
+ if (is_constant(left) && is_constant(right)) {
789
+ var val = null;
790
+ switch (op) {
791
+ case "+": val = left[1] + right[1]; break;
792
+ case "*": val = left[1] * right[1]; break;
793
+ case "/": val = left[1] / right[1]; break;
794
+ case "-": val = left[1] - right[1]; break;
795
+ case "<<": val = left[1] << right[1]; break;
796
+ case ">>": val = left[1] >> right[1]; break;
797
+ case ">>>": val = left[1] >>> right[1]; break;
798
+ }
799
+ if (val != null) {
800
+ best = best_of(best, [ typeof val == "string" ? "string" : "num", val ]);
801
+ }
802
+ }
803
+ return best;
804
+ },
805
+ "conditional": function(c, t, e) {
806
+ return make_conditional(walk(c), walk(t), walk(e));
807
+ },
808
+ "try": function(t, c, f) {
809
+ return [
810
+ "try",
811
+ tighten(t.map(walk)),
812
+ c != null ? [ c[0], tighten(c[1].map(walk)) ] : null,
813
+ f != null ? tighten(f.map(walk)) : null
814
+ ];
815
+ }
816
+ }, function() {
817
+ return walk(ast);
818
+ });
819
+
820
+ };
821
+
822
+ /* -----[ re-generate code from the AST ]----- */
823
+
824
+ var DOT_CALL_NO_PARENS = jsp.array_to_hash([
825
+ "name",
826
+ "array",
827
+ "string",
828
+ "dot",
829
+ "sub",
830
+ "call",
831
+ "regexp"
832
+ ]);
833
+
834
+ function gen_code(ast, beautify) {
835
+ if (beautify) beautify = defaults(beautify, {
836
+ indent_start : 0,
837
+ indent_level : 4,
838
+ quote_keys : false,
839
+ space_colon : false
840
+ });
841
+ var indentation = 0,
842
+ newline = beautify ? "\n" : "",
843
+ space = beautify ? " " : "";
844
+
845
+ function indent(line) {
846
+ if (line == null)
847
+ line = "";
848
+ if (beautify)
849
+ line = repeat_string(" ", beautify.indent_start + indentation * beautify.indent_level) + line;
850
+ return line;
851
+ };
852
+
853
+ function with_indent(cont, incr) {
854
+ if (incr == null) incr = 1;
855
+ indentation += incr;
856
+ try { return cont.apply(null, slice(arguments, 1)); }
857
+ finally { indentation -= incr; }
858
+ };
859
+
860
+ function add_spaces(a) {
861
+ if (beautify)
862
+ return a.join(" ");
863
+ var b = [];
864
+ for (var i = 0; i < a.length; ++i) {
865
+ var next = a[i + 1];
866
+ b.push(a[i]);
867
+ if (next &&
868
+ ((/[a-z0-9_\x24]$/i.test(a[i].toString()) && /^[a-z0-9_\x24]/i.test(next.toString())) ||
869
+ (/[\+\-]$/.test(a[i].toString()) && /^[\+\-]/.test(next.toString())))) {
870
+ b.push(" ");
871
+ }
872
+ }
873
+ return b.join("");
874
+ };
875
+
876
+ function add_commas(a) {
877
+ return a.join("," + space);
878
+ };
879
+
880
+ function parenthesize(expr) {
881
+ var gen = make(expr);
882
+ for (var i = 1; i < arguments.length; ++i) {
883
+ var el = arguments[i];
884
+ if ((el instanceof Function && el(expr)) || expr[0] == el)
885
+ return "(" + gen + ")";
886
+ }
887
+ return gen;
888
+ };
889
+
890
+ function best_of(a) {
891
+ if (a.length == 1) {
892
+ return a[0];
893
+ }
894
+ if (a.length == 2) {
895
+ var b = a[1];
896
+ a = a[0];
897
+ return a.length <= b.length ? a : b;
898
+ }
899
+ return best_of([ a[0], best_of(a.slice(1)) ]);
900
+ };
901
+
902
+ function needs_parens(expr) {
903
+ if (expr[0] == "function") {
904
+ // dot/call on a literal function requires the
905
+ // function literal itself to be parenthesized
906
+ // only if it's the first "thing" in a
907
+ // statement. This means that the parent is
908
+ // "stat", but it could also be a "seq" and
909
+ // we're the first in this "seq" and the
910
+ // parent is "stat", and so on. Messy stuff,
911
+ // but it worths the trouble.
912
+ var a = slice($stack), self = a.pop(), p = a.pop();
913
+ while (true) {
914
+ if (p[0] == "stat") return true;
915
+ if ((p[0] == "seq" && p[1] === self) ||
916
+ (p[0] == "call" && p[1] === self) ||
917
+ (p[0] == "binary" && p[2] === self)) {
918
+ self = p;
919
+ p = a.pop();
920
+ } else {
921
+ return false;
922
+ }
923
+ }
924
+ }
925
+ return !HOP(DOT_CALL_NO_PARENS, expr[0]);
926
+ };
927
+
928
+ function make_num(num) {
929
+ var str = num.toString(10), a = [ str.replace(/^0\./, ".") ], m;
930
+ if (Math.floor(num) === num) {
931
+ a.push("0x" + num.toString(16).toLowerCase(), // probably pointless
932
+ "0" + num.toString(8)); // same.
933
+ if ((m = /^(.*?)(0+)$/.exec(num))) {
934
+ a.push(m[1] + "e" + m[2].length);
935
+ }
936
+ } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) {
937
+ a.push(m[2] + "e-" + (m[1].length + 1),
938
+ str.substr(str.indexOf(".")));
939
+ }
940
+ return best_of(a);
941
+ };
942
+
943
+ var generators = {
944
+ "string": make_string,
945
+ "num": make_num,
946
+ "name": make_name,
947
+ "toplevel": function(statements) {
948
+ return make_block_statements(statements)
949
+ .join(newline + newline);
950
+ },
951
+ "block": make_block,
952
+ "var": function(defs) {
953
+ return "var " + add_commas(defs.map(make_1vardef)) + ";";
954
+ },
955
+ "const": function(defs) {
956
+ return "const " + add_commas(defs.map(make_1vardef)) + ";";
957
+ },
958
+ "try": function(tr, ca, fi) {
959
+ var out = [ "try", make_block(tr) ];
960
+ if (ca) out.push("catch", "(" + ca[0] + ")", make_block(ca[1]));
961
+ if (fi) out.push("finally", make_block(fi));
962
+ return add_spaces(out);
963
+ },
964
+ "throw": function(expr) {
965
+ return add_spaces([ "throw", make(expr) ]) + ";";
966
+ },
967
+ "new": function(ctor, args) {
968
+ args = args.length > 0 ? "(" + add_commas(args.map(make)) + ")" : "";
969
+ return add_spaces([ "new", parenthesize(ctor, "seq", "binary", "conditional", "assign", function(expr){
970
+ var w = ast_walker(), has_call = {};
971
+ try {
972
+ w.with_walkers({
973
+ "call": function() { throw has_call },
974
+ "function": function() { return this }
975
+ }, function(){
976
+ w.walk(expr);
977
+ });
978
+ } catch(ex) {
979
+ if (ex === has_call)
980
+ return true;
981
+ throw ex;
982
+ }
983
+ }) + args ]);
984
+ },
985
+ "switch": function(expr, body) {
986
+ return add_spaces([ "switch", "(" + make(expr) + ")", make_switch_block(body) ]);
987
+ },
988
+ "break": function(label) {
989
+ var out = "break";
990
+ if (label != null)
991
+ out += " " + make_name(label);
992
+ return out + ";";
993
+ },
994
+ "continue": function(label) {
995
+ var out = "continue";
996
+ if (label != null)
997
+ out += " " + make_name(label);
998
+ return out + ";";
999
+ },
1000
+ "conditional": function(co, th, el) {
1001
+ return add_spaces([ parenthesize(co, "assign", "seq", "conditional"), "?",
1002
+ parenthesize(th, "seq"), ":",
1003
+ parenthesize(el, "seq") ]);
1004
+ },
1005
+ "assign": function(op, lvalue, rvalue) {
1006
+ if (op && op !== true) op += "=";
1007
+ else op = "=";
1008
+ return add_spaces([ make(lvalue), op, make(rvalue) ]);
1009
+ },
1010
+ "dot": function(expr) {
1011
+ var out = make(expr), i = 1;
1012
+ if (needs_parens(expr))
1013
+ out = "(" + out + ")";
1014
+ while (i < arguments.length)
1015
+ out += "." + make_name(arguments[i++]);
1016
+ return out;
1017
+ },
1018
+ "call": function(func, args) {
1019
+ var f = make(func);
1020
+ if (needs_parens(func))
1021
+ f = "(" + f + ")";
1022
+ return f + "(" + add_commas(args.map(make)) + ")";
1023
+ },
1024
+ "function": make_function,
1025
+ "defun": make_function,
1026
+ "if": function(co, th, el) {
1027
+ var out = [ "if", "(" + make(co) + ")", el ? make_then(th) : make(th) ];
1028
+ if (el) {
1029
+ out.push("else", make(el));
1030
+ }
1031
+ return add_spaces(out);
1032
+ },
1033
+ "for": function(init, cond, step, block) {
1034
+ var out = [ "for" ];
1035
+ init = (init != null ? make(init) : "").replace(/;*\s*$/, ";" + space);
1036
+ cond = (cond != null ? make(cond) : "").replace(/;*\s*$/, ";" + space);
1037
+ step = (step != null ? make(step) : "").replace(/;*\s*$/, "");
1038
+ var args = init + cond + step;
1039
+ if (args == "; ; ") args = ";;";
1040
+ out.push("(" + args + ")", make(block));
1041
+ return add_spaces(out);
1042
+ },
1043
+ "for-in": function(has_var, key, hash, block) {
1044
+ var out = add_spaces([ "for", "(" ]);
1045
+ if (has_var)
1046
+ out += "var ";
1047
+ out += add_spaces([ make_name(key) + " in " + make(hash) + ")", make(block) ]);
1048
+ return out;
1049
+ },
1050
+ "while": function(condition, block) {
1051
+ return add_spaces([ "while", "(" + make(condition) + ")", make(block) ]);
1052
+ },
1053
+ "do": function(condition, block) {
1054
+ return add_spaces([ "do", make(block), "while", "(" + make(condition) + ")" ]) + ";";
1055
+ },
1056
+ "return": function(expr) {
1057
+ var out = [ "return" ];
1058
+ if (expr != null) out.push(make(expr));
1059
+ return add_spaces(out) + ";";
1060
+ },
1061
+ "binary": function(operator, lvalue, rvalue) {
1062
+ var left = make(lvalue), right = make(rvalue);
1063
+ // XXX: I'm pretty sure other cases will bite here.
1064
+ // we need to be smarter.
1065
+ // adding parens all the time is the safest bet.
1066
+ if (member(lvalue[0], [ "assign", "conditional", "seq" ]) ||
1067
+ lvalue[0] == "binary" && PRECEDENCE[operator] > PRECEDENCE[lvalue[1]]) {
1068
+ left = "(" + left + ")";
1069
+ }
1070
+ if (member(rvalue[0], [ "assign", "conditional", "seq" ]) ||
1071
+ rvalue[0] == "binary" && PRECEDENCE[operator] >= PRECEDENCE[rvalue[1]]) {
1072
+ right = "(" + right + ")";
1073
+ }
1074
+ return add_spaces([ left, operator, right ]);
1075
+ },
1076
+ "unary-prefix": function(operator, expr) {
1077
+ var val = make(expr);
1078
+ if (!(expr[0] == "num" || (expr[0] == "unary-prefix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
1079
+ val = "(" + val + ")";
1080
+ return operator + (jsp.is_alphanumeric_char(operator.charAt(0)) ? " " : "") + val;
1081
+ },
1082
+ "unary-postfix": function(operator, expr) {
1083
+ var val = make(expr);
1084
+ if (!(expr[0] == "num" || (expr[0] == "unary-postfix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
1085
+ val = "(" + val + ")";
1086
+ return val + operator;
1087
+ },
1088
+ "sub": function(expr, subscript) {
1089
+ var hash = make(expr);
1090
+ if (needs_parens(expr))
1091
+ hash = "(" + hash + ")";
1092
+ return hash + "[" + make(subscript) + "]";
1093
+ },
1094
+ "object": function(props) {
1095
+ if (props.length == 0)
1096
+ return "{}";
1097
+ return "{" + newline + with_indent(function(){
1098
+ return props.map(function(p){
1099
+ var key = p[0], val = make(p[1]);
1100
+ if (beautify && beautify.quote_keys) {
1101
+ key = make_string(key);
1102
+ } else if (typeof key == "number" || !beautify && +key + "" == key) {
1103
+ key = make_num(+key);
1104
+ } else if (!is_identifier(key)) {
1105
+ key = make_string(key);
1106
+ }
1107
+ return indent(add_spaces(beautify && beautify.space_colon
1108
+ ? [ key, ":", val ]
1109
+ : [ key + ":", val ]));
1110
+ }).join("," + newline);
1111
+ }) + newline + indent("}");
1112
+ },
1113
+ "regexp": function(rx, mods) {
1114
+ return "/" + rx + "/" + mods;
1115
+ },
1116
+ "array": function(elements) {
1117
+ if (elements.length == 0) return "[]";
1118
+ return add_spaces([ "[", add_commas(elements.map(make)), "]" ]);
1119
+ },
1120
+ "stat": function(stmt) {
1121
+ return make(stmt).replace(/;*\s*$/, ";");
1122
+ },
1123
+ "seq": function() {
1124
+ return add_commas(slice(arguments).map(make));
1125
+ },
1126
+ "label": function(name, block) {
1127
+ return add_spaces([ make_name(name), ":", make(block) ]);
1128
+ },
1129
+ "with": function(expr, block) {
1130
+ return add_spaces([ "with", "(" + make(expr) + ")", make(block) ]);
1131
+ },
1132
+ "atom": function(name) {
1133
+ return make_name(name);
1134
+ },
1135
+ "comment1": function(text) {
1136
+ return "//" + text + "\n";
1137
+ },
1138
+ "comment2": function(text) {
1139
+ return "/*" + text + "*/";
1140
+ }
1141
+ };
1142
+
1143
+ // The squeezer replaces "block"-s that contain only a single
1144
+ // statement with the statement itself; technically, the AST
1145
+ // is correct, but this can create problems when we output an
1146
+ // IF having an ELSE clause where the THEN clause ends in an
1147
+ // IF *without* an ELSE block (then the outer ELSE would refer
1148
+ // to the inner IF). This function checks for this case and
1149
+ // adds the block brackets if needed.
1150
+ function make_then(th) {
1151
+ var b = th;
1152
+ while (true) {
1153
+ var type = b[0];
1154
+ if (type == "if") {
1155
+ if (!b[3])
1156
+ // no else, we must add the block
1157
+ return make([ "block", [ th ]]);
1158
+ b = b[3];
1159
+ }
1160
+ else if (type == "while" || type == "do") b = b[2];
1161
+ else if (type == "for" || type == "for-in") b = b[4];
1162
+ else break;
1163
+ }
1164
+ return make(th);
1165
+ };
1166
+
1167
+ function make_function(name, args, body) {
1168
+ var out = "function";
1169
+ if (name) {
1170
+ out += " " + make_name(name);
1171
+ }
1172
+ out += "(" + add_commas(args.map(make_name)) + ")";
1173
+ return add_spaces([ out, make_block(body) ]);
1174
+ };
1175
+
1176
+ function make_string(str) {
1177
+ // return '"' +
1178
+ // str.replace(/\x5c/g, "\\\\")
1179
+ // .replace(/\r?\n/g, "\\n")
1180
+ // .replace(/\t/g, "\\t")
1181
+ // .replace(/\r/g, "\\r")
1182
+ // .replace(/\f/g, "\\f")
1183
+ // .replace(/[\b]/g, "\\b")
1184
+ // .replace(/\x22/g, "\\\"")
1185
+ // .replace(/[\x00-\x1f]|[\x80-\xff]/g, function(c){
1186
+ // var hex = c.charCodeAt(0).toString(16);
1187
+ // if (hex.length < 2)
1188
+ // hex = "0" + hex;
1189
+ // return "\\x" + hex;
1190
+ // })
1191
+ // + '"';
1192
+ return JSON.stringify(str); // STILL cheating.
1193
+ };
1194
+
1195
+ function make_name(name) {
1196
+ return name.toString();
1197
+ };
1198
+
1199
+ function make_block_statements(statements) {
1200
+ for (var a = [], last = statements.length - 1, i = 0; i <= last; ++i) {
1201
+ var stat = statements[i];
1202
+ var code = make(stat);
1203
+ if (code != ";") {
1204
+ if (!beautify && i == last)
1205
+ code = code.replace(/;+\s*$/, "");
1206
+ a.push(code);
1207
+ }
1208
+ }
1209
+ return a.map(indent);
1210
+ };
1211
+
1212
+ function make_switch_block(body) {
1213
+ var n = body.length;
1214
+ if (n == 0) return "{}";
1215
+ return "{" + newline + body.map(function(branch, i){
1216
+ var has_body = branch[1].length > 0, code = with_indent(function(){
1217
+ return indent(branch[0]
1218
+ ? add_spaces([ "case", make(branch[0]) + ":" ])
1219
+ : "default:");
1220
+ }, 0.5) + (has_body ? newline + with_indent(function(){
1221
+ return make_block_statements(branch[1]).join(newline);
1222
+ }) : "");
1223
+ if (!beautify && has_body && i < n - 1)
1224
+ code += ";";
1225
+ return code;
1226
+ }).join(newline) + newline + indent("}");
1227
+ };
1228
+
1229
+ function make_block(statements) {
1230
+ if (!statements) return ";";
1231
+ if (statements.length == 0) return "{}";
1232
+ return "{" + newline + with_indent(function(){
1233
+ return make_block_statements(statements).join(newline);
1234
+ }) + newline + indent("}");
1235
+ };
1236
+
1237
+ function make_1vardef(def) {
1238
+ var name = def[0], val = def[1];
1239
+ if (val != null)
1240
+ name = add_spaces([ name, "=", make(val) ]);
1241
+ return name;
1242
+ };
1243
+
1244
+ var $stack = [];
1245
+
1246
+ function make(node) {
1247
+ var type = node[0];
1248
+ var gen = generators[type];
1249
+ if (!gen)
1250
+ throw new Error("Can't find generator for \"" + type + "\"");
1251
+ $stack.push(node);
1252
+ var ret = gen.apply(type, node.slice(1));
1253
+ $stack.pop();
1254
+ return ret;
1255
+ };
1256
+
1257
+ return make(ast);
1258
+ };
1259
+
1260
+ /* -----[ Utilities ]----- */
1261
+
1262
+ function repeat_string(str, i) {
1263
+ if (i <= 0) return "";
1264
+ if (i == 1) return str;
1265
+ var d = repeat_string(str, i >> 1);
1266
+ d += d;
1267
+ if (i & 1) d += str;
1268
+ return d;
1269
+ };
1270
+
1271
+ function defaults(args, defs) {
1272
+ var ret = {};
1273
+ if (args === true)
1274
+ args = {};
1275
+ for (var i in defs) if (HOP(defs, i)) {
1276
+ ret[i] = (args && HOP(args, i)) ? args[i] : defs[i];
1277
+ }
1278
+ return ret;
1279
+ };
1280
+
1281
+ function is_identifier(name) {
1282
+ return /^[a-z_$][a-z0-9_$]*$/i.test(name)
1283
+ && name != "this"
1284
+ && !HOP(jsp.KEYWORDS_ATOM, name)
1285
+ && !HOP(jsp.RESERVED_WORDS, name)
1286
+ && !HOP(jsp.KEYWORDS, name);
1287
+ };
1288
+
1289
+ function HOP(obj, prop) {
1290
+ return Object.prototype.hasOwnProperty.call(obj, prop);
1291
+ };
1292
+
1293
+ /* -----[ Exports ]----- */
1294
+
1295
+ exports.ast_walker = ast_walker;
1296
+ exports.ast_mangle = ast_mangle;
1297
+ exports.ast_squeeze = ast_squeeze;
1298
+ exports.gen_code = gen_code;
1299
+ exports.ast_add_scope = ast_add_scope;