mozilla-ast.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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 MOZ_TO_ME = {
  36. ExpressionStatement: function(M) {
  37. var expr = M.expression;
  38. if (expr.type === "Literal" && typeof expr.value === "string") {
  39. return new AST_Directive({
  40. start: my_start_token(M),
  41. end: my_end_token(M),
  42. value: expr.value
  43. });
  44. }
  45. return new AST_SimpleStatement({
  46. start: my_start_token(M),
  47. end: my_end_token(M),
  48. body: from_moz(expr)
  49. });
  50. },
  51. TryStatement: function(M) {
  52. var handlers = M.handlers || [M.handler];
  53. if (handlers.length > 1 || M.guardedHandlers && M.guardedHandlers.length) {
  54. throw new Error("Multiple catch clauses are not supported.");
  55. }
  56. return new AST_Try({
  57. start : my_start_token(M),
  58. end : my_end_token(M),
  59. body : from_moz(M.block).body,
  60. bcatch : from_moz(handlers[0]),
  61. bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null
  62. });
  63. },
  64. Property: function(M) {
  65. var key = M.key;
  66. var name = key.type == "Identifier" ? key.name : key.value;
  67. var args = {
  68. start : my_start_token(key),
  69. end : my_end_token(M.value),
  70. key : name,
  71. value : from_moz(M.value)
  72. };
  73. switch (M.kind) {
  74. case "init":
  75. return new AST_ObjectKeyVal(args);
  76. case "set":
  77. args.value.name = from_moz(key);
  78. return new AST_ObjectSetter(args);
  79. case "get":
  80. args.value.name = from_moz(key);
  81. return new AST_ObjectGetter(args);
  82. }
  83. },
  84. ObjectExpression: function(M) {
  85. return new AST_Object({
  86. start : my_start_token(M),
  87. end : my_end_token(M),
  88. properties : M.properties.map(function(prop){
  89. prop.type = "Property";
  90. return from_moz(prop)
  91. })
  92. });
  93. },
  94. SequenceExpression: function(M) {
  95. return AST_Seq.from_array(M.expressions.map(from_moz));
  96. },
  97. MemberExpression: function(M) {
  98. return new (M.computed ? AST_Sub : AST_Dot)({
  99. start : my_start_token(M),
  100. end : my_end_token(M),
  101. property : M.computed ? from_moz(M.property) : M.property.name,
  102. expression : from_moz(M.object)
  103. });
  104. },
  105. SwitchCase: function(M) {
  106. return new (M.test ? AST_Case : AST_Default)({
  107. start : my_start_token(M),
  108. end : my_end_token(M),
  109. expression : from_moz(M.test),
  110. body : M.consequent.map(from_moz)
  111. });
  112. },
  113. VariableDeclaration: function(M) {
  114. return new (M.kind === "const" ? AST_Const : AST_Var)({
  115. start : my_start_token(M),
  116. end : my_end_token(M),
  117. definitions : M.declarations.map(from_moz)
  118. });
  119. },
  120. Literal: function(M) {
  121. var val = M.value, args = {
  122. start : my_start_token(M),
  123. end : my_end_token(M)
  124. };
  125. if (val === null) return new AST_Null(args);
  126. switch (typeof val) {
  127. case "string":
  128. args.value = val;
  129. return new AST_String(args);
  130. case "number":
  131. args.value = val;
  132. return new AST_Number(args);
  133. case "boolean":
  134. return new (val ? AST_True : AST_False)(args);
  135. default:
  136. args.value = val;
  137. return new AST_RegExp(args);
  138. }
  139. },
  140. Identifier: function(M) {
  141. var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2];
  142. return new ( p.type == "LabeledStatement" ? AST_Label
  143. : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : AST_SymbolVar)
  144. : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg)
  145. : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg)
  146. : p.type == "CatchClause" ? AST_SymbolCatch
  147. : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef
  148. : AST_SymbolRef)({
  149. start : my_start_token(M),
  150. end : my_end_token(M),
  151. name : M.name
  152. });
  153. }
  154. };
  155. MOZ_TO_ME.UpdateExpression =
  156. MOZ_TO_ME.UnaryExpression = function To_Moz_Unary(M) {
  157. var prefix = "prefix" in M ? M.prefix
  158. : M.type == "UnaryExpression" ? true : false;
  159. return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({
  160. start : my_start_token(M),
  161. end : my_end_token(M),
  162. operator : M.operator,
  163. expression : from_moz(M.argument)
  164. });
  165. };
  166. map("Program", AST_Toplevel, "body@body");
  167. map("EmptyStatement", AST_EmptyStatement);
  168. map("BlockStatement", AST_BlockStatement, "body@body");
  169. map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative");
  170. map("LabeledStatement", AST_LabeledStatement, "label>label, body>body");
  171. map("BreakStatement", AST_Break, "label>label");
  172. map("ContinueStatement", AST_Continue, "label>label");
  173. map("WithStatement", AST_With, "object>expression, body>body");
  174. map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body");
  175. map("ReturnStatement", AST_Return, "argument>value");
  176. map("ThrowStatement", AST_Throw, "argument>value");
  177. map("WhileStatement", AST_While, "test>condition, body>body");
  178. map("DoWhileStatement", AST_Do, "test>condition, body>body");
  179. map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body");
  180. map("ForInStatement", AST_ForIn, "left>init, right>object, body>body");
  181. map("DebuggerStatement", AST_Debugger);
  182. map("FunctionDeclaration", AST_Defun, "id>name, params@argnames, body%body");
  183. map("VariableDeclarator", AST_VarDef, "id>name, init>value");
  184. map("CatchClause", AST_Catch, "param>argname, body%body");
  185. map("ThisExpression", AST_This);
  186. map("ArrayExpression", AST_Array, "elements@elements");
  187. map("FunctionExpression", AST_Function, "id>name, params@argnames, body%body");
  188. map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right");
  189. map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right");
  190. map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right");
  191. map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative");
  192. map("NewExpression", AST_New, "callee>expression, arguments@args");
  193. map("CallExpression", AST_Call, "callee>expression, arguments@args");
  194. def_to_moz(AST_Directive, function To_Moz_Directive(M) {
  195. return {
  196. type: "ExpressionStatement",
  197. expression: {
  198. type: "Literal",
  199. value: M.value
  200. }
  201. };
  202. });
  203. def_to_moz(AST_SimpleStatement, function To_Moz_ExpressionStatement(M) {
  204. return {
  205. type: "ExpressionStatement",
  206. expression: to_moz(M.body)
  207. };
  208. });
  209. def_to_moz(AST_SwitchBranch, function To_Moz_SwitchCase(M) {
  210. return {
  211. type: "SwitchCase",
  212. test: to_moz(M.expression),
  213. consequent: M.body.map(to_moz)
  214. };
  215. });
  216. def_to_moz(AST_Try, function To_Moz_TryStatement(M) {
  217. return {
  218. type: "TryStatement",
  219. block: to_moz_block(M),
  220. handler: to_moz(M.bcatch),
  221. guardedHandlers: [],
  222. finalizer: to_moz(M.bfinally)
  223. };
  224. });
  225. def_to_moz(AST_Catch, function To_Moz_CatchClause(M) {
  226. return {
  227. type: "CatchClause",
  228. param: to_moz(M.argname),
  229. guard: null,
  230. body: to_moz_block(M)
  231. };
  232. });
  233. def_to_moz(AST_Definitions, function To_Moz_VariableDeclaration(M) {
  234. return {
  235. type: "VariableDeclaration",
  236. kind: M instanceof AST_Const ? "const" : "var",
  237. declarations: M.definitions.map(to_moz)
  238. };
  239. });
  240. def_to_moz(AST_Seq, function To_Moz_SequenceExpression(M) {
  241. return {
  242. type: "SequenceExpression",
  243. expressions: M.to_array().map(to_moz)
  244. };
  245. });
  246. def_to_moz(AST_PropAccess, function To_Moz_MemberExpression(M) {
  247. var isComputed = M instanceof AST_Sub;
  248. return {
  249. type: "MemberExpression",
  250. object: to_moz(M.expression),
  251. computed: isComputed,
  252. property: isComputed ? to_moz(M.property) : {type: "Identifier", name: M.property}
  253. };
  254. });
  255. def_to_moz(AST_Unary, function To_Moz_Unary(M) {
  256. return {
  257. type: M.operator == "++" || M.operator == "--" ? "UpdateExpression" : "UnaryExpression",
  258. operator: M.operator,
  259. prefix: M instanceof AST_UnaryPrefix,
  260. argument: to_moz(M.expression)
  261. };
  262. });
  263. def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) {
  264. return {
  265. type: M.operator == "&&" || M.operator == "||" ? "LogicalExpression" : "BinaryExpression",
  266. left: to_moz(M.left),
  267. operator: M.operator,
  268. right: to_moz(M.right)
  269. };
  270. });
  271. def_to_moz(AST_Object, function To_Moz_ObjectExpression(M) {
  272. return {
  273. type: "ObjectExpression",
  274. properties: M.properties.map(to_moz)
  275. };
  276. });
  277. def_to_moz(AST_ObjectProperty, function To_Moz_Property(M) {
  278. var key = (
  279. is_identifier(M.key)
  280. ? {type: "Identifier", name: M.key}
  281. : {type: "Literal", value: M.key}
  282. );
  283. var kind;
  284. if (M instanceof AST_ObjectKeyVal) {
  285. kind = "init";
  286. } else
  287. if (M instanceof AST_ObjectGetter) {
  288. kind = "get";
  289. } else
  290. if (M instanceof AST_ObjectSetter) {
  291. kind = "set";
  292. }
  293. return {
  294. type: "Property",
  295. kind: kind,
  296. key: key,
  297. value: to_moz(M.value)
  298. };
  299. });
  300. def_to_moz(AST_Symbol, function To_Moz_Identifier(M) {
  301. var def = M.definition();
  302. return {
  303. type: "Identifier",
  304. name: def ? def.mangled_name || def.name : M.name
  305. };
  306. });
  307. def_to_moz(AST_Constant, function To_Moz_Literal(M) {
  308. var value = M.value;
  309. if (typeof value === 'number' && (value < 0 || (value === 0 && 1 / value < 0))) {
  310. return {
  311. type: "UnaryExpression",
  312. operator: "-",
  313. prefix: true,
  314. argument: {
  315. type: "Literal",
  316. value: -value
  317. }
  318. };
  319. }
  320. return {
  321. type: "Literal",
  322. value: value
  323. };
  324. });
  325. def_to_moz(AST_Atom, function To_Moz_Atom(M) {
  326. return {
  327. type: "Identifier",
  328. name: String(M.value)
  329. };
  330. });
  331. AST_Boolean.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast);
  332. AST_Null.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast);
  333. AST_Hole.DEFMETHOD("to_mozilla_ast", function To_Moz_ArrayHole() { return null });
  334. AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast);
  335. AST_Lambda.DEFMETHOD("to_mozilla_ast", AST_Function.prototype.to_mozilla_ast);
  336. /* -----[ tools ]----- */
  337. function my_start_token(moznode) {
  338. var loc = moznode.loc, start = loc && loc.start;
  339. var range = moznode.range;
  340. return new AST_Token({
  341. file : loc && loc.source,
  342. line : start && start.line,
  343. col : start && start.column,
  344. pos : range ? range[0] : moznode.start,
  345. endline : start && start.line,
  346. endcol : start && start.column,
  347. endpos : range ? range[0] : moznode.start
  348. });
  349. };
  350. function my_end_token(moznode) {
  351. var loc = moznode.loc, end = loc && loc.end;
  352. var range = moznode.range;
  353. return new AST_Token({
  354. file : loc && loc.source,
  355. line : end && end.line,
  356. col : end && end.column,
  357. pos : range ? range[1] : moznode.end,
  358. endline : end && end.line,
  359. endcol : end && end.column,
  360. endpos : range ? range[1] : moznode.end
  361. });
  362. };
  363. function map(moztype, mytype, propmap) {
  364. var moz_to_me = "function From_Moz_" + moztype + "(M){\n";
  365. moz_to_me += "return new " + mytype.name + "({\n" +
  366. "start: my_start_token(M),\n" +
  367. "end: my_end_token(M)";
  368. var me_to_moz = "function To_Moz_" + moztype + "(M){\n";
  369. me_to_moz += "return {\n" +
  370. "type: " + JSON.stringify(moztype);
  371. if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop){
  372. var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop);
  373. if (!m) throw new Error("Can't understand property map: " + prop);
  374. var moz = m[1], how = m[2], my = m[3];
  375. moz_to_me += ",\n" + my + ": ";
  376. me_to_moz += ",\n" + moz + ": ";
  377. switch (how) {
  378. case "@":
  379. moz_to_me += "M." + moz + ".map(from_moz)";
  380. me_to_moz += "M." + my + ".map(to_moz)";
  381. break;
  382. case ">":
  383. moz_to_me += "from_moz(M." + moz + ")";
  384. me_to_moz += "to_moz(M." + my + ")";
  385. break;
  386. case "=":
  387. moz_to_me += "M." + moz;
  388. me_to_moz += "M." + my;
  389. break;
  390. case "%":
  391. moz_to_me += "from_moz(M." + moz + ").body";
  392. me_to_moz += "to_moz_block(M)";
  393. break;
  394. default:
  395. throw new Error("Can't understand operator in propmap: " + prop);
  396. }
  397. });
  398. moz_to_me += "\n})\n}";
  399. me_to_moz += "\n}\n}";
  400. //moz_to_me = parse(moz_to_me).print_to_string({ beautify: true });
  401. //me_to_moz = parse(me_to_moz).print_to_string({ beautify: true });
  402. //console.log(moz_to_me);
  403. moz_to_me = new Function("my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")(
  404. my_start_token, my_end_token, from_moz
  405. );
  406. me_to_moz = new Function("to_moz", "to_moz_block", "return(" + me_to_moz + ")")(
  407. to_moz, to_moz_block
  408. );
  409. MOZ_TO_ME[moztype] = moz_to_me;
  410. def_to_moz(mytype, me_to_moz);
  411. };
  412. var FROM_MOZ_STACK = null;
  413. function from_moz(node) {
  414. FROM_MOZ_STACK.push(node);
  415. var ret = node != null ? MOZ_TO_ME[node.type](node) : null;
  416. FROM_MOZ_STACK.pop();
  417. return ret;
  418. };
  419. AST_Node.from_mozilla_ast = function(node){
  420. var save_stack = FROM_MOZ_STACK;
  421. FROM_MOZ_STACK = [];
  422. var ast = from_moz(node);
  423. FROM_MOZ_STACK = save_stack;
  424. return ast;
  425. };
  426. function set_moz_loc(mynode, moznode, myparent) {
  427. var start = mynode.start;
  428. var end = mynode.end;
  429. if (start.pos != null && end.endpos != null) {
  430. moznode.range = [start.pos, end.endpos];
  431. }
  432. if (start.line) {
  433. moznode.loc = {
  434. start: {line: start.line, column: start.col},
  435. end: end.endline ? {line: end.endline, column: end.endcol} : null
  436. };
  437. if (start.file) {
  438. moznode.loc.source = start.file;
  439. }
  440. }
  441. return moznode;
  442. };
  443. function def_to_moz(mytype, handler) {
  444. mytype.DEFMETHOD("to_mozilla_ast", function() {
  445. return set_moz_loc(this, handler(this));
  446. });
  447. };
  448. function to_moz(node) {
  449. return node != null ? node.to_mozilla_ast() : null;
  450. };
  451. function to_moz_block(node) {
  452. return {
  453. type: "BlockStatement",
  454. body: node.body.map(to_moz)
  455. };
  456. };
  457. })();