mozilla-ast.js 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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_SymbolMethod({
  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 new AST_Sequence({
  133. start : my_start_token(M),
  134. end : my_end_token(M),
  135. expressions: M.expressions.map(from_moz)
  136. });
  137. },
  138. MemberExpression: function(M) {
  139. return new (M.computed ? AST_Sub : AST_Dot)({
  140. start : my_start_token(M),
  141. end : my_end_token(M),
  142. property : M.computed ? from_moz(M.property) : M.property.name,
  143. expression : from_moz(M.object)
  144. });
  145. },
  146. SwitchCase: function(M) {
  147. return new (M.test ? AST_Case : AST_Default)({
  148. start : my_start_token(M),
  149. end : my_end_token(M),
  150. expression : from_moz(M.test),
  151. body : M.consequent.map(from_moz)
  152. });
  153. },
  154. VariableDeclaration: function(M) {
  155. return new (M.kind === "const" ? AST_Const : AST_Var)({
  156. start : my_start_token(M),
  157. end : my_end_token(M),
  158. definitions : M.declarations.map(from_moz)
  159. });
  160. },
  161. Literal: function(M) {
  162. var val = M.value, args = {
  163. start : my_start_token(M),
  164. end : my_end_token(M)
  165. };
  166. if (val === null) return new AST_Null(args);
  167. switch (typeof val) {
  168. case "string":
  169. args.value = val;
  170. return new AST_String(args);
  171. case "number":
  172. args.value = val;
  173. return new AST_Number(args);
  174. case "boolean":
  175. return new (val ? AST_True : AST_False)(args);
  176. default:
  177. var rx = M.regex;
  178. if (rx && rx.pattern) {
  179. // RegExpLiteral as per ESTree AST spec
  180. args.value = new RegExp(rx.pattern, rx.flags).toString();
  181. } else {
  182. // support legacy RegExp
  183. args.value = M.regex && M.raw ? M.raw : val;
  184. }
  185. return new AST_RegExp(args);
  186. }
  187. },
  188. Identifier: function(M) {
  189. var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2];
  190. return new ( p.type == "LabeledStatement" ? AST_Label
  191. : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : AST_SymbolVar)
  192. : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg)
  193. : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg)
  194. : p.type == "CatchClause" ? AST_SymbolCatch
  195. : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef
  196. : AST_SymbolRef)({
  197. start : my_start_token(M),
  198. end : my_end_token(M),
  199. name : M.name
  200. });
  201. }
  202. };
  203. MOZ_TO_ME.UpdateExpression =
  204. MOZ_TO_ME.UnaryExpression = function To_Moz_Unary(M) {
  205. var prefix = "prefix" in M ? M.prefix
  206. : M.type == "UnaryExpression" ? true : false;
  207. return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({
  208. start : my_start_token(M),
  209. end : my_end_token(M),
  210. operator : M.operator,
  211. expression : from_moz(M.argument)
  212. });
  213. };
  214. map("EmptyStatement", AST_EmptyStatement);
  215. map("BlockStatement", AST_BlockStatement, "body@body");
  216. map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative");
  217. map("LabeledStatement", AST_LabeledStatement, "label>label, body>body");
  218. map("BreakStatement", AST_Break, "label>label");
  219. map("ContinueStatement", AST_Continue, "label>label");
  220. map("WithStatement", AST_With, "object>expression, body>body");
  221. map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body");
  222. map("ReturnStatement", AST_Return, "argument>value");
  223. map("ThrowStatement", AST_Throw, "argument>value");
  224. map("WhileStatement", AST_While, "test>condition, body>body");
  225. map("DoWhileStatement", AST_Do, "test>condition, body>body");
  226. map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body");
  227. map("ForInStatement", AST_ForIn, "left>init, right>object, body>body");
  228. map("DebuggerStatement", AST_Debugger);
  229. map("VariableDeclarator", AST_VarDef, "id>name, init>value");
  230. map("CatchClause", AST_Catch, "param>argname, body%body");
  231. map("ThisExpression", AST_This);
  232. map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right");
  233. map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right");
  234. map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right");
  235. map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative");
  236. map("NewExpression", AST_New, "callee>expression, arguments@args");
  237. map("CallExpression", AST_Call, "callee>expression, arguments@args");
  238. def_to_moz(AST_Toplevel, function To_Moz_Program(M) {
  239. return to_moz_scope("Program", M);
  240. });
  241. def_to_moz(AST_Defun, function To_Moz_FunctionDeclaration(M) {
  242. return {
  243. type: "FunctionDeclaration",
  244. id: to_moz(M.name),
  245. params: M.argnames.map(to_moz),
  246. body: to_moz_scope("BlockStatement", M)
  247. }
  248. });
  249. def_to_moz(AST_Function, function To_Moz_FunctionExpression(M) {
  250. return {
  251. type: "FunctionExpression",
  252. id: to_moz(M.name),
  253. params: M.argnames.map(to_moz),
  254. body: to_moz_scope("BlockStatement", M)
  255. }
  256. });
  257. def_to_moz(AST_Directive, function To_Moz_Directive(M) {
  258. return {
  259. type: "ExpressionStatement",
  260. expression: {
  261. type: "Literal",
  262. value: M.value
  263. }
  264. };
  265. });
  266. def_to_moz(AST_SimpleStatement, function To_Moz_ExpressionStatement(M) {
  267. return {
  268. type: "ExpressionStatement",
  269. expression: to_moz(M.body)
  270. };
  271. });
  272. def_to_moz(AST_SwitchBranch, function To_Moz_SwitchCase(M) {
  273. return {
  274. type: "SwitchCase",
  275. test: to_moz(M.expression),
  276. consequent: M.body.map(to_moz)
  277. };
  278. });
  279. def_to_moz(AST_Try, function To_Moz_TryStatement(M) {
  280. return {
  281. type: "TryStatement",
  282. block: to_moz_block(M),
  283. handler: to_moz(M.bcatch),
  284. guardedHandlers: [],
  285. finalizer: to_moz(M.bfinally)
  286. };
  287. });
  288. def_to_moz(AST_Catch, function To_Moz_CatchClause(M) {
  289. return {
  290. type: "CatchClause",
  291. param: to_moz(M.argname),
  292. guard: null,
  293. body: to_moz_block(M)
  294. };
  295. });
  296. def_to_moz(AST_Definitions, function To_Moz_VariableDeclaration(M) {
  297. return {
  298. type: "VariableDeclaration",
  299. kind: M instanceof AST_Const ? "const" : "var",
  300. declarations: M.definitions.map(to_moz)
  301. };
  302. });
  303. def_to_moz(AST_Sequence, function To_Moz_SequenceExpression(M) {
  304. return {
  305. type: "SequenceExpression",
  306. expressions: M.expressions.map(to_moz)
  307. };
  308. });
  309. def_to_moz(AST_PropAccess, function To_Moz_MemberExpression(M) {
  310. var isComputed = M instanceof AST_Sub;
  311. return {
  312. type: "MemberExpression",
  313. object: to_moz(M.expression),
  314. computed: isComputed,
  315. property: isComputed ? to_moz(M.property) : {type: "Identifier", name: M.property}
  316. };
  317. });
  318. def_to_moz(AST_Unary, function To_Moz_Unary(M) {
  319. return {
  320. type: M.operator == "++" || M.operator == "--" ? "UpdateExpression" : "UnaryExpression",
  321. operator: M.operator,
  322. prefix: M instanceof AST_UnaryPrefix,
  323. argument: to_moz(M.expression)
  324. };
  325. });
  326. def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) {
  327. return {
  328. type: M.operator == "&&" || M.operator == "||" ? "LogicalExpression" : "BinaryExpression",
  329. left: to_moz(M.left),
  330. operator: M.operator,
  331. right: to_moz(M.right)
  332. };
  333. });
  334. def_to_moz(AST_Array, function To_Moz_ArrayExpression(M) {
  335. return {
  336. type: "ArrayExpression",
  337. elements: M.elements.map(to_moz)
  338. };
  339. });
  340. def_to_moz(AST_Object, function To_Moz_ObjectExpression(M) {
  341. return {
  342. type: "ObjectExpression",
  343. properties: M.properties.map(to_moz)
  344. };
  345. });
  346. def_to_moz(AST_ObjectProperty, function To_Moz_Property(M) {
  347. var key = {
  348. type: "Literal",
  349. value: M.key instanceof AST_SymbolMethod ? M.key.name : M.key
  350. };
  351. var kind;
  352. if (M instanceof AST_ObjectKeyVal) {
  353. kind = "init";
  354. } else
  355. if (M instanceof AST_ObjectGetter) {
  356. kind = "get";
  357. } else
  358. if (M instanceof AST_ObjectSetter) {
  359. kind = "set";
  360. }
  361. return {
  362. type: "Property",
  363. kind: kind,
  364. key: key,
  365. value: to_moz(M.value)
  366. };
  367. });
  368. def_to_moz(AST_Symbol, function To_Moz_Identifier(M) {
  369. var def = M.definition();
  370. return {
  371. type: "Identifier",
  372. name: def ? def.mangled_name || def.name : M.name
  373. };
  374. });
  375. def_to_moz(AST_RegExp, function To_Moz_RegExpLiteral(M) {
  376. var value = M.value;
  377. return {
  378. type: "Literal",
  379. value: value,
  380. raw: value.toString(),
  381. regex: {
  382. pattern: value.source,
  383. flags: value.toString().match(/[gimuy]*$/)[0]
  384. }
  385. };
  386. });
  387. def_to_moz(AST_Constant, function To_Moz_Literal(M) {
  388. var value = M.value;
  389. if (typeof value === 'number' && (value < 0 || (value === 0 && 1 / value < 0))) {
  390. return {
  391. type: "UnaryExpression",
  392. operator: "-",
  393. prefix: true,
  394. argument: {
  395. type: "Literal",
  396. value: -value,
  397. raw: M.start.raw
  398. }
  399. };
  400. }
  401. return {
  402. type: "Literal",
  403. value: value,
  404. raw: M.start.raw
  405. };
  406. });
  407. def_to_moz(AST_Atom, function To_Moz_Atom(M) {
  408. return {
  409. type: "Identifier",
  410. name: String(M.value)
  411. };
  412. });
  413. AST_Boolean.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast);
  414. AST_Null.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast);
  415. AST_Hole.DEFMETHOD("to_mozilla_ast", function To_Moz_ArrayHole() { return null });
  416. AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast);
  417. AST_Lambda.DEFMETHOD("to_mozilla_ast", AST_Function.prototype.to_mozilla_ast);
  418. /* -----[ tools ]----- */
  419. function raw_token(moznode) {
  420. if (moznode.type == "Literal") {
  421. return moznode.raw != null ? moznode.raw : moznode.value + "";
  422. }
  423. }
  424. function my_start_token(moznode) {
  425. var loc = moznode.loc, start = loc && loc.start;
  426. var range = moznode.range;
  427. return new AST_Token({
  428. file : loc && loc.source,
  429. line : start && start.line,
  430. col : start && start.column,
  431. pos : range ? range[0] : moznode.start,
  432. endline : start && start.line,
  433. endcol : start && start.column,
  434. endpos : range ? range[0] : moznode.start,
  435. raw : raw_token(moznode),
  436. });
  437. };
  438. function my_end_token(moznode) {
  439. var loc = moznode.loc, end = loc && loc.end;
  440. var range = moznode.range;
  441. return new AST_Token({
  442. file : loc && loc.source,
  443. line : end && end.line,
  444. col : end && end.column,
  445. pos : range ? range[1] : moznode.end,
  446. endline : end && end.line,
  447. endcol : end && end.column,
  448. endpos : range ? range[1] : moznode.end,
  449. raw : raw_token(moznode),
  450. });
  451. };
  452. function map(moztype, mytype, propmap) {
  453. var moz_to_me = "function From_Moz_" + moztype + "(M){\n";
  454. moz_to_me += "return new U2." + mytype.name + "({\n" +
  455. "start: my_start_token(M),\n" +
  456. "end: my_end_token(M)";
  457. var me_to_moz = "function To_Moz_" + moztype + "(M){\n";
  458. me_to_moz += "return {\n" +
  459. "type: " + JSON.stringify(moztype);
  460. if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop){
  461. var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop);
  462. if (!m) throw new Error("Can't understand property map: " + prop);
  463. var moz = m[1], how = m[2], my = m[3];
  464. moz_to_me += ",\n" + my + ": ";
  465. me_to_moz += ",\n" + moz + ": ";
  466. switch (how) {
  467. case "@":
  468. moz_to_me += "M." + moz + ".map(from_moz)";
  469. me_to_moz += "M." + my + ".map(to_moz)";
  470. break;
  471. case ">":
  472. moz_to_me += "from_moz(M." + moz + ")";
  473. me_to_moz += "to_moz(M." + my + ")";
  474. break;
  475. case "=":
  476. moz_to_me += "M." + moz;
  477. me_to_moz += "M." + my;
  478. break;
  479. case "%":
  480. moz_to_me += "from_moz(M." + moz + ").body";
  481. me_to_moz += "to_moz_block(M)";
  482. break;
  483. default:
  484. throw new Error("Can't understand operator in propmap: " + prop);
  485. }
  486. });
  487. moz_to_me += "\n})\n}";
  488. me_to_moz += "\n}\n}";
  489. //moz_to_me = parse(moz_to_me).print_to_string({ beautify: true });
  490. //me_to_moz = parse(me_to_moz).print_to_string({ beautify: true });
  491. //console.log(moz_to_me);
  492. moz_to_me = new Function("U2", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")(
  493. exports, my_start_token, my_end_token, from_moz
  494. );
  495. me_to_moz = new Function("to_moz", "to_moz_block", "to_moz_scope", "return(" + me_to_moz + ")")(
  496. to_moz, to_moz_block, to_moz_scope
  497. );
  498. MOZ_TO_ME[moztype] = moz_to_me;
  499. def_to_moz(mytype, me_to_moz);
  500. };
  501. var FROM_MOZ_STACK = null;
  502. function from_moz(node) {
  503. FROM_MOZ_STACK.push(node);
  504. var ret = node != null ? MOZ_TO_ME[node.type](node) : null;
  505. FROM_MOZ_STACK.pop();
  506. return ret;
  507. };
  508. AST_Node.from_mozilla_ast = function(node){
  509. var save_stack = FROM_MOZ_STACK;
  510. FROM_MOZ_STACK = [];
  511. var ast = from_moz(node);
  512. FROM_MOZ_STACK = save_stack;
  513. return ast;
  514. };
  515. function set_moz_loc(mynode, moznode, myparent) {
  516. var start = mynode.start;
  517. var end = mynode.end;
  518. if (start.pos != null && end.endpos != null) {
  519. moznode.range = [start.pos, end.endpos];
  520. }
  521. if (start.line) {
  522. moznode.loc = {
  523. start: {line: start.line, column: start.col},
  524. end: end.endline ? {line: end.endline, column: end.endcol} : null
  525. };
  526. if (start.file) {
  527. moznode.loc.source = start.file;
  528. }
  529. }
  530. return moznode;
  531. };
  532. function def_to_moz(mytype, handler) {
  533. mytype.DEFMETHOD("to_mozilla_ast", function() {
  534. return set_moz_loc(this, handler(this));
  535. });
  536. };
  537. function to_moz(node) {
  538. return node != null ? node.to_mozilla_ast() : null;
  539. };
  540. function to_moz_block(node) {
  541. return {
  542. type: "BlockStatement",
  543. body: node.body.map(to_moz)
  544. };
  545. };
  546. function to_moz_scope(type, node) {
  547. var body = node.body.map(to_moz);
  548. if (node.body[0] instanceof AST_SimpleStatement && node.body[0].body instanceof AST_String) {
  549. body.unshift(to_moz(new AST_EmptyStatement(node.body[0])));
  550. }
  551. return {
  552. type: type,
  553. body: body
  554. };
  555. };
  556. })();