xonecas.io
818
Du

dustymarkdown / files

dustymarkdown / node_modules / uglify-js / lib / process.js

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