mozilla-ast.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. /***********************************************************************
  2. A JavaScript tokenizer / parser / beautifier / compressor.
  3. https://github.com/mishoo/UglifyJS2
  4. -------------------------------- (C) ---------------------------------
  5. Author: Mihai Bazon
  6. <mihai.bazon@gmail.com>
  7. http://mihai.bazon.net/blog
  8. Distributed under the BSD license:
  9. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  10. Redistribution and use in source and binary forms, with or without
  11. modification, are permitted provided that the following conditions
  12. are met:
  13. * Redistributions of source code must retain the above
  14. copyright notice, this list of conditions and the following
  15. disclaimer.
  16. * Redistributions in binary form must reproduce the above
  17. copyright notice, this list of conditions and the following
  18. disclaimer in the documentation and/or other materials
  19. provided with the distribution.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  21. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  23. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  24. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  25. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  26. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  27. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  29. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  30. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31. SUCH DAMAGE.
  32. ***********************************************************************/
  33. "use strict";
  34. (function(){
  35. var normalize_directives = function(body) {
  36. var in_directive = true;
  37. for (var i = 0; i < body.length; i++) {
  38. if (in_directive && body[i] instanceof AST_Statement && body[i].body instanceof AST_String) {
  39. body[i] = new AST_Directive({
  40. start: body[i].start,
  41. end: body[i].end,
  42. value: body[i].body.value
  43. });
  44. } else if (in_directive && !(body[i] instanceof AST_Statement && body[i].body instanceof AST_String)) {
  45. in_directive = false;
  46. }
  47. }
  48. return body;
  49. };
  50. var MOZ_TO_ME = {
  51. Program: function(M) {
  52. return new AST_Toplevel({
  53. start: my_start_token(M),
  54. end: my_end_token(M),
  55. body: normalize_directives(M.body.map(from_moz))
  56. });
  57. },
  58. FunctionDeclaration: function(M) {
  59. return new AST_Defun({
  60. start: my_start_token(M),
  61. end: my_end_token(M),
  62. name: from_moz(M.id),
  63. argnames: M.params.map(from_moz),
  64. body: normalize_directives(from_moz(M.body).body)
  65. });
  66. },
  67. FunctionExpression: function(M) {
  68. return new AST_Function({
  69. start: my_start_token(M),
  70. end: my_end_token(M),
  71. name: from_moz(M.id),
  72. argnames: M.params.map(from_moz),
  73. body: normalize_directives(from_moz(M.body).body)
  74. });
  75. },
  76. ExpressionStatement: function(M) {
  77. return new AST_SimpleStatement({
  78. start: my_start_token(M),
  79. end: my_end_token(M),
  80. body: from_moz(M.expression)
  81. });
  82. },
  83. TryStatement: function(M) {
  84. var handlers = M.handlers || [M.handler];
  85. if (handlers.length > 1 || M.guardedHandlers && M.guardedHandlers.length) {
  86. throw new Error("Multiple catch clauses are not supported.");
  87. }
  88. return new AST_Try({
  89. start : my_start_token(M),
  90. end : my_end_token(M),
  91. body : from_moz(M.block).body,
  92. bcatch : from_moz(handlers[0]),
  93. bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null
  94. });
  95. },
  96. Property: function(M) {
  97. var key = M.key;
  98. var args = {
  99. start : my_start_token(key),
  100. end : my_end_token(M.value),
  101. key : key.type == "Identifier" ? key.name : key.value,
  102. value : from_moz(M.value)
  103. };
  104. if (M.kind == "init") return new AST_ObjectKeyVal(args);
  105. args.key = new AST_SymbolAccessor({
  106. name: args.key
  107. });
  108. args.value = new AST_Accessor(args.value);
  109. if (M.kind == "get") return new AST_ObjectGetter(args);
  110. if (M.kind == "set") return new AST_ObjectSetter(args);
  111. },
  112. ArrayExpression: function(M) {
  113. return new AST_Array({
  114. start : my_start_token(M),
  115. end : my_end_token(M),
  116. elements : M.elements.map(function(elem){
  117. return elem === null ? new AST_Hole() : from_moz(elem);
  118. })
  119. });
  120. },
  121. ObjectExpression: function(M) {
  122. return new AST_Object({
  123. start : my_start_token(M),
  124. end : my_end_token(M),
  125. properties : M.properties.map(function(prop){
  126. prop.type = "Property";
  127. return from_moz(prop)
  128. })
  129. });
  130. },
  131. SequenceExpression: function(M) {
  132. return AST_Seq.from_array(M.expressions.map(from_moz));
  133. },
  134. MemberExpression: function(M) {
  135. return new (M.computed ? AST_Sub : AST_Dot)({
  136. start : my_start_token(M),
  137. end : my_end_token(M),
  138. property : M.computed ? from_moz(M.property) : M.property.name,
  139. expression : from_moz(M.object)
  140. });
  141. },
  142. SwitchCase: function(M) {
  143. return new (M.test ? AST_Case : AST_Default)({
  144. start : my_start_token(M),
  145. end : my_end_token(M),
  146. expression : from_moz(M.test),
  147. body : M.consequent.map(from_moz)
  148. });
  149. },
  150. VariableDeclaration: function(M) {
  151. return new (M.kind === "const" ? AST_Const : AST_Var)({
  152. start : my_start_token(M),
  153. end : my_end_token(M),
  154. definitions : M.declarations.map(from_moz)
  155. });
  156. },
  157. Literal: function(M) {
  158. var val = M.value, args = {
  159. start : my_start_token(M),
  160. end : my_end_token(M)
  161. };
  162. if (val === null) return new AST_Null(args);
  163. switch (typeof val) {
  164. case "string":
  165. args.value = val;
  166. return new AST_String(args);
  167. case "number":
  168. args.value = val;
  169. return new AST_Number(args);
  170. case "boolean":
  171. return new (val ? AST_True : AST_False)(args);
  172. default:
  173. var rx = M.regex;
  174. if (rx && rx.pattern) {
  175. // RegExpLiteral as per ESTree AST spec
  176. args.value = new RegExp(rx.pattern, rx.flags).toString();
  177. } else {
  178. // support legacy RegExp
  179. args.value = M.regex && M.raw ? M.raw : val;
  180. }
  181. return new AST_RegExp(args);
  182. }
  183. },
  184. Identifier: function(M) {
  185. var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2];
  186. return new ( p.type == "LabeledStatement" ? AST_Label
  187. : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : AST_SymbolVar)
  188. : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg)
  189. : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg)
  190. : p.type == "CatchClause" ? AST_SymbolCatch
  191. : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef
  192. : AST_SymbolRef)({
  193. start : my_start_token(M),
  194. end : my_end_token(M),
  195. name : M.name
  196. });
  197. }
  198. };
  199. MOZ_TO_ME.UpdateExpression =
  200. MOZ_TO_ME.UnaryExpression = function To_Moz_Unary(M) {
  201. var prefix = "prefix" in M ? M.prefix
  202. : M.type == "UnaryExpression" ? true : false;
  203. return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({
  204. start : my_start_token(M),
  205. end : my_end_token(M),
  206. operator : M.operator,
  207. expression : from_moz(M.argument)
  208. });
  209. };
  210. map("EmptyStatement", AST_EmptyStatement);
  211. map("BlockStatement", AST_BlockStatement, "body@body");
  212. map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative");
  213. map("LabeledStatement", AST_LabeledStatement, "label>label, body>body");
  214. map("BreakStatement", AST_Break, "label>label");
  215. map("ContinueStatement", AST_Continue, "label>label");
  216. map("WithStatement", AST_With, "object>expression, body>body");
  217. map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body");
  218. map("ReturnStatement", AST_Return, "argument>value");
  219. map("ThrowStatement", AST_Throw, "argument>value");
  220. map("WhileStatement", AST_While, "test>condition, body>body");
  221. map("DoWhileStatement", AST_Do, "test>condition, body>body");
  222. map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body");
  223. map("ForInStatement", AST_ForIn, "left>init, right>object, body>body");
  224. map("DebuggerStatement", AST_Debugger);
  225. map("VariableDeclarator", AST_VarDef, "id>name, init>value");
  226. map("CatchClause", AST_Catch, "param>argname, body%body");
  227. map("ThisExpression", AST_This);
  228. map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right");
  229. map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right");
  230. map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right");
  231. map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative");
  232. map("NewExpression", AST_New, "callee>expression, arguments@args");
  233. map("CallExpression", AST_Call, "callee>expression, arguments@args");
  234. def_to_moz(AST_Toplevel, function To_Moz_Program(M) {
  235. return to_moz_scope("Program", M);
  236. });
  237. def_to_moz(AST_Defun, function To_Moz_FunctionDeclaration(M) {
  238. return {
  239. type: "FunctionDeclaration",
  240. id: to_moz(M.name),
  241. params: M.argnames.map(to_moz),
  242. body: to_moz_scope("BlockStatement", M)
  243. }
  244. });
  245. def_to_moz(AST_Function, function To_Moz_FunctionExpression(M) {
  246. return {
  247. type: "FunctionExpression",
  248. id: to_moz(M.name),
  249. params: M.argnames.map(to_moz),
  250. body: to_moz_scope("BlockStatement", M)
  251. }
  252. });
  253. def_to_moz(AST_Directive, function To_Moz_Directive(M) {
  254. return {
  255. type: "ExpressionStatement",
  256. expression: {
  257. type: "Literal",
  258. value: M.value
  259. }
  260. };
  261. });
  262. def_to_moz(AST_SimpleStatement, function To_Moz_ExpressionStatement(M) {
  263. return {
  264. type: "ExpressionStatement",
  265. expression: to_moz(M.body)
  266. };
  267. });
  268. def_to_moz(AST_SwitchBranch, function To_Moz_SwitchCase(M) {
  269. return {
  270. type: "SwitchCase",
  271. test: to_moz(M.expression),
  272. consequent: M.body.map(to_moz)
  273. };
  274. });
  275. def_to_moz(AST_Try, function To_Moz_TryStatement(M) {
  276. return {
  277. type: "TryStatement",
  278. block: to_moz_block(M),
  279. handler: to_moz(M.bcatch),
  280. guardedHandlers: [],
  281. finalizer: to_moz(M.bfinally)
  282. };
  283. });
  284. def_to_moz(AST_Catch, function To_Moz_CatchClause(M) {
  285. return {
  286. type: "CatchClause",
  287. param: to_moz(M.argname),
  288. guard: null,
  289. body: to_moz_block(M)
  290. };
  291. });
  292. def_to_moz(AST_Definitions, function To_Moz_VariableDeclaration(M) {
  293. return {
  294. type: "VariableDeclaration",
  295. kind: M instanceof AST_Const ? "const" : "var",
  296. declarations: M.definitions.map(to_moz)
  297. };
  298. });
  299. def_to_moz(AST_Seq, function To_Moz_SequenceExpression(M) {
  300. return {
  301. type: "SequenceExpression",
  302. expressions: M.to_array().map(to_moz)
  303. };
  304. });
  305. def_to_moz(AST_PropAccess, function To_Moz_MemberExpression(M) {
  306. var isComputed = M instanceof AST_Sub;
  307. return {
  308. type: "MemberExpression",
  309. object: to_moz(M.expression),
  310. computed: isComputed,
  311. property: isComputed ? to_moz(M.property) : {type: "Identifier", name: M.property}
  312. };
  313. });
  314. def_to_moz(AST_Unary, function To_Moz_Unary(M) {
  315. return {
  316. type: M.operator == "++" || M.operator == "--" ? "UpdateExpression" : "UnaryExpression",
  317. operator: M.operator,
  318. prefix: M instanceof AST_UnaryPrefix,
  319. argument: to_moz(M.expression)
  320. };
  321. });
  322. def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) {
  323. return {
  324. type: M.operator == "&&" || M.operator == "||" ? "LogicalExpression" : "BinaryExpression",
  325. left: to_moz(M.left),
  326. operator: M.operator,
  327. right: to_moz(M.right)
  328. };
  329. });
  330. def_to_moz(AST_Array, function To_Moz_ArrayExpression(M) {
  331. return {
  332. type: "ArrayExpression",
  333. elements: M.elements.map(to_moz)
  334. };
  335. });
  336. def_to_moz(AST_Object, function To_Moz_ObjectExpression(M) {
  337. return {
  338. type: "ObjectExpression",
  339. properties: M.properties.map(to_moz)
  340. };
  341. });
  342. def_to_moz(AST_ObjectProperty, function To_Moz_Property(M) {
  343. var key = {
  344. type: "Literal",
  345. value: M.key instanceof AST_SymbolAccessor ? M.key.name : M.key
  346. };
  347. var kind;
  348. if (M instanceof AST_ObjectKeyVal) {
  349. kind = "init";
  350. } else
  351. if (M instanceof AST_ObjectGetter) {
  352. kind = "get";
  353. } else
  354. if (M instanceof AST_ObjectSetter) {
  355. kind = "set";
  356. }
  357. return {
  358. type: "Property",
  359. kind: kind,
  360. key: key,
  361. value: to_moz(M.value)
  362. };
  363. });
  364. def_to_moz(AST_Symbol, function To_Moz_Identifier(M) {
  365. var def = M.definition();
  366. return {
  367. type: "Identifier",
  368. name: def ? def.mangled_name || def.name : M.name
  369. };
  370. });
  371. def_to_moz(AST_RegExp, function To_Moz_RegExpLiteral(M) {
  372. var value = M.value;
  373. return {
  374. type: "Literal",
  375. value: value,
  376. raw: value.toString(),
  377. regex: {
  378. pattern: value.source,
  379. flags: value.toString().match(/[gimuy]*$/)[0]
  380. }
  381. };
  382. });
  383. def_to_moz(AST_Constant, function To_Moz_Literal(M) {
  384. var value = M.value;
  385. if (typeof value === 'number' && (value < 0 || (value === 0 && 1 / value < 0))) {
  386. return {
  387. type: "UnaryExpression",
  388. operator: "-",
  389. prefix: true,
  390. argument: {
  391. type: "Literal",
  392. value: -value,
  393. raw: M.start.raw
  394. }
  395. };
  396. }
  397. return {
  398. type: "Literal",
  399. value: value,
  400. raw: M.start.raw
  401. };
  402. });
  403. def_to_moz(AST_Atom, function To_Moz_Atom(M) {
  404. return {
  405. type: "Identifier",
  406. name: String(M.value)
  407. };
  408. });
  409. AST_Boolean.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast);
  410. AST_Null.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast);
  411. AST_Hole.DEFMETHOD("to_mozilla_ast", function To_Moz_ArrayHole() { return null });
  412. AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast);
  413. AST_Lambda.DEFMETHOD("to_mozilla_ast", AST_Function.prototype.to_mozilla_ast);
  414. /* -----[ tools ]----- */
  415. function raw_token(moznode) {
  416. if (moznode.type == "Literal") {
  417. return moznode.raw != null ? moznode.raw : moznode.value + "";
  418. }
  419. }
  420. function my_start_token(moznode) {
  421. var loc = moznode.loc, start = loc && loc.start;
  422. var range = moznode.range;
  423. return new AST_Token({
  424. file : loc && loc.source,
  425. line : start && start.line,
  426. col : start && start.column,
  427. pos : range ? range[0] : moznode.start,
  428. endline : start && start.line,
  429. endcol : start && start.column,
  430. endpos : range ? range[0] : moznode.start,
  431. raw : raw_token(moznode),
  432. });
  433. };
  434. function my_end_token(moznode) {
  435. var loc = moznode.loc, end = loc && loc.end;
  436. var range = moznode.range;
  437. return new AST_Token({
  438. file : loc && loc.source,
  439. line : end && end.line,
  440. col : end && end.column,
  441. pos : range ? range[1] : moznode.end,
  442. endline : end && end.line,
  443. endcol : end && end.column,
  444. endpos : range ? range[1] : moznode.end,
  445. raw : raw_token(moznode),
  446. });
  447. };
  448. function map(moztype, mytype, propmap) {
  449. var moz_to_me = "function From_Moz_" + moztype + "(M){\n";
  450. moz_to_me += "return new U2." + mytype.name + "({\n" +
  451. "start: my_start_token(M),\n" +
  452. "end: my_end_token(M)";
  453. var me_to_moz = "function To_Moz_" + moztype + "(M){\n";
  454. me_to_moz += "return {\n" +
  455. "type: " + JSON.stringify(moztype);
  456. if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop){
  457. var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop);
  458. if (!m) throw new Error("Can't understand property map: " + prop);
  459. var moz = m[1], how = m[2], my = m[3];
  460. moz_to_me += ",\n" + my + ": ";
  461. me_to_moz += ",\n" + moz + ": ";
  462. switch (how) {
  463. case "@":
  464. moz_to_me += "M." + moz + ".map(from_moz)";
  465. me_to_moz += "M." + my + ".map(to_moz)";
  466. break;
  467. case ">":
  468. moz_to_me += "from_moz(M." + moz + ")";
  469. me_to_moz += "to_moz(M." + my + ")";
  470. break;
  471. case "=":
  472. moz_to_me += "M." + moz;
  473. me_to_moz += "M." + my;
  474. break;
  475. case "%":
  476. moz_to_me += "from_moz(M." + moz + ").body";
  477. me_to_moz += "to_moz_block(M)";
  478. break;
  479. default:
  480. throw new Error("Can't understand operator in propmap: " + prop);
  481. }
  482. });
  483. moz_to_me += "\n})\n}";
  484. me_to_moz += "\n}\n}";
  485. //moz_to_me = parse(moz_to_me).print_to_string({ beautify: true });
  486. //me_to_moz = parse(me_to_moz).print_to_string({ beautify: true });
  487. //console.log(moz_to_me);
  488. moz_to_me = new Function("U2", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")(
  489. exports, my_start_token, my_end_token, from_moz
  490. );
  491. me_to_moz = new Function("to_moz", "to_moz_block", "to_moz_scope", "return(" + me_to_moz + ")")(
  492. to_moz, to_moz_block, to_moz_scope
  493. );
  494. MOZ_TO_ME[moztype] = moz_to_me;
  495. def_to_moz(mytype, me_to_moz);
  496. };
  497. var FROM_MOZ_STACK = null;
  498. function from_moz(node) {
  499. FROM_MOZ_STACK.push(node);
  500. var ret = node != null ? MOZ_TO_ME[node.type](node) : null;
  501. FROM_MOZ_STACK.pop();
  502. return ret;
  503. };
  504. AST_Node.from_mozilla_ast = function(node){
  505. var save_stack = FROM_MOZ_STACK;
  506. FROM_MOZ_STACK = [];
  507. var ast = from_moz(node);
  508. FROM_MOZ_STACK = save_stack;
  509. return ast;
  510. };
  511. function set_moz_loc(mynode, moznode, myparent) {
  512. var start = mynode.start;
  513. var end = mynode.end;
  514. if (start.pos != null && end.endpos != null) {
  515. moznode.range = [start.pos, end.endpos];
  516. }
  517. if (start.line) {
  518. moznode.loc = {
  519. start: {line: start.line, column: start.col},
  520. end: end.endline ? {line: end.endline, column: end.endcol} : null
  521. };
  522. if (start.file) {
  523. moznode.loc.source = start.file;
  524. }
  525. }
  526. return moznode;
  527. };
  528. function def_to_moz(mytype, handler) {
  529. mytype.DEFMETHOD("to_mozilla_ast", function() {
  530. return set_moz_loc(this, handler(this));
  531. });
  532. };
  533. function to_moz(node) {
  534. return node != null ? node.to_mozilla_ast() : null;
  535. };
  536. function to_moz_block(node) {
  537. return {
  538. type: "BlockStatement",
  539. body: node.body.map(to_moz)
  540. };
  541. };
  542. function to_moz_scope(type, node) {
  543. var body = node.body.map(to_moz);
  544. if (node.body[0] instanceof AST_SimpleStatement && node.body[0].body instanceof AST_String) {
  545. body.unshift(to_moz(new AST_EmptyStatement(node.body[0])));
  546. }
  547. return {
  548. type: type,
  549. body: body
  550. };
  551. };
  552. })();