process.js 91 KB

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