coffeescript-router 0.0.1

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