You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

629 lines
22 KiB

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