mozilla-ast.js 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272
  1. /***********************************************************************
  2. A JavaScript tokenizer / parser / beautifier / compressor.
  3. https://github.com/mishoo/UglifyJS
  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. Program: function(M) {
  37. return new AST_Toplevel({
  38. start: my_start_token(M),
  39. end: my_end_token(M),
  40. body: normalize_directives(M.body.map(from_moz)),
  41. });
  42. },
  43. ArrowFunctionExpression: function(M) {
  44. var argnames = [], rest = null;
  45. M.params.forEach(function(param) {
  46. if (param.type == "RestElement") {
  47. rest = from_moz(param.argument);
  48. } else {
  49. argnames.push(from_moz(param));
  50. }
  51. });
  52. var fn = new (M.async ? AST_AsyncArrow : AST_Arrow)({
  53. start: my_start_token(M),
  54. end: my_end_token(M),
  55. argnames: argnames,
  56. rest: rest,
  57. });
  58. var node = from_moz(M.body);
  59. if (node instanceof AST_BlockStatement) {
  60. fn.body = normalize_directives(node.body);
  61. fn.value = null;
  62. } else {
  63. fn.body = [];
  64. fn.value = node;
  65. }
  66. return fn;
  67. },
  68. FunctionDeclaration: function(M) {
  69. var ctor;
  70. if (M.async) {
  71. ctor = M.generator ? AST_AsyncGeneratorDefun : AST_AsyncDefun;
  72. } else {
  73. ctor = M.generator ? AST_GeneratorDefun : AST_Defun;
  74. }
  75. var argnames = [], rest = null;
  76. M.params.forEach(function(param) {
  77. if (param.type == "RestElement") {
  78. rest = from_moz(param.argument);
  79. } else {
  80. argnames.push(from_moz(param));
  81. }
  82. });
  83. return new ctor({
  84. start: my_start_token(M),
  85. end: my_end_token(M),
  86. name: from_moz(M.id),
  87. argnames: argnames,
  88. rest: rest,
  89. body: normalize_directives(from_moz(M.body).body),
  90. });
  91. },
  92. FunctionExpression: function(M) {
  93. var ctor;
  94. if (M.async) {
  95. ctor = M.generator ? AST_AsyncGeneratorFunction : AST_AsyncFunction;
  96. } else {
  97. ctor = M.generator ? AST_GeneratorFunction : AST_Function;
  98. }
  99. var argnames = [], rest = null;
  100. M.params.forEach(function(param) {
  101. if (param.type == "RestElement") {
  102. rest = from_moz(param.argument);
  103. } else {
  104. argnames.push(from_moz(param));
  105. }
  106. });
  107. return new ctor({
  108. start: my_start_token(M),
  109. end: my_end_token(M),
  110. name: from_moz(M.id),
  111. argnames: argnames,
  112. rest: rest,
  113. body: normalize_directives(from_moz(M.body).body),
  114. });
  115. },
  116. ClassDeclaration: function(M) {
  117. return new AST_DefClass({
  118. start: my_start_token(M),
  119. end: my_end_token(M),
  120. name: from_moz(M.id),
  121. extends: from_moz(M.superClass),
  122. properties: M.body.body.map(from_moz),
  123. });
  124. },
  125. ClassExpression: function(M) {
  126. return new AST_ClassExpression({
  127. start: my_start_token(M),
  128. end: my_end_token(M),
  129. name: from_moz(M.id),
  130. extends: from_moz(M.superClass),
  131. properties: M.body.body.map(from_moz),
  132. });
  133. },
  134. MethodDefinition: function(M) {
  135. var key = M.key, internal = false;
  136. if (M.computed) {
  137. key = from_moz(key);
  138. } else if (key.type == "PrivateIdentifier") {
  139. internal = true;
  140. key = "#" + key.name;
  141. } else {
  142. key = read_name(key);
  143. }
  144. var ctor = AST_ClassMethod, value = from_moz(M.value);
  145. switch (M.kind) {
  146. case "get":
  147. ctor = AST_ClassGetter;
  148. value = new AST_Accessor(value);
  149. break;
  150. case "set":
  151. ctor = AST_ClassSetter;
  152. value = new AST_Accessor(value);
  153. break;
  154. }
  155. return new ctor({
  156. start: my_start_token(M),
  157. end: my_end_token(M),
  158. key: key,
  159. private: internal,
  160. static: M.static,
  161. value: value,
  162. });
  163. },
  164. PropertyDefinition: function(M) {
  165. var key = M.key, internal = false;
  166. if (M.computed) {
  167. key = from_moz(key);
  168. } else if (key.type == "PrivateIdentifier") {
  169. internal = true;
  170. key = "#" + key.name;
  171. } else {
  172. key = read_name(key);
  173. }
  174. return new AST_ClassField({
  175. start: my_start_token(M),
  176. end: my_end_token(M),
  177. key: key,
  178. private: internal,
  179. static: M.static,
  180. value: from_moz(M.value),
  181. });
  182. },
  183. ForOfStatement: function(M) {
  184. return new (M.await ? AST_ForAwaitOf : AST_ForOf)({
  185. start: my_start_token(M),
  186. end: my_end_token(M),
  187. init: from_moz(M.left),
  188. object: from_moz(M.right),
  189. body: from_moz(M.body),
  190. });
  191. },
  192. TryStatement: function(M) {
  193. var handlers = M.handlers || [M.handler];
  194. if (handlers.length > 1 || M.guardedHandlers && M.guardedHandlers.length) {
  195. throw new Error("Multiple catch clauses are not supported.");
  196. }
  197. return new AST_Try({
  198. start : my_start_token(M),
  199. end : my_end_token(M),
  200. body : from_moz(M.block).body,
  201. bcatch : from_moz(handlers[0]),
  202. bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null,
  203. });
  204. },
  205. Property: function(M) {
  206. var key = M.computed ? from_moz(M.key) : read_name(M.key);
  207. var args = {
  208. start: my_start_token(M),
  209. end: my_end_token(M),
  210. key: key,
  211. value: from_moz(M.value),
  212. };
  213. if (M.kind == "init") return new (M.method ? AST_ObjectMethod : AST_ObjectKeyVal)(args);
  214. args.value = new AST_Accessor(args.value);
  215. if (M.kind == "get") return new AST_ObjectGetter(args);
  216. if (M.kind == "set") return new AST_ObjectSetter(args);
  217. },
  218. ArrayExpression: function(M) {
  219. return new AST_Array({
  220. start: my_start_token(M),
  221. end: my_end_token(M),
  222. elements: M.elements.map(function(elem) {
  223. return elem === null ? new AST_Hole() : from_moz(elem);
  224. }),
  225. });
  226. },
  227. ArrayPattern: function(M) {
  228. var elements = [], rest = null;
  229. M.elements.forEach(function(el) {
  230. if (el === null) {
  231. elements.push(new AST_Hole());
  232. } else if (el.type == "RestElement") {
  233. rest = from_moz(el.argument);
  234. } else {
  235. elements.push(from_moz(el));
  236. }
  237. });
  238. return new AST_DestructuredArray({
  239. start: my_start_token(M),
  240. end: my_end_token(M),
  241. elements: elements,
  242. rest: rest,
  243. });
  244. },
  245. ObjectPattern: function(M) {
  246. var props = [], rest = null;
  247. M.properties.forEach(function(prop) {
  248. if (prop.type == "RestElement") {
  249. rest = from_moz(prop.argument);
  250. } else {
  251. props.push(new AST_DestructuredKeyVal(from_moz(prop)));
  252. }
  253. });
  254. return new AST_DestructuredObject({
  255. start: my_start_token(M),
  256. end: my_end_token(M),
  257. properties: props,
  258. rest: rest,
  259. });
  260. },
  261. MemberExpression: function(M) {
  262. return new (M.computed ? AST_Sub : AST_Dot)({
  263. start: my_start_token(M),
  264. end: my_end_token(M),
  265. optional: M.optional,
  266. expression: from_moz(M.object),
  267. property: M.computed ? from_moz(M.property) : M.property.name,
  268. });
  269. },
  270. MetaProperty: function(M) {
  271. var expr = from_moz(M.meta);
  272. var prop = read_name(M.property);
  273. if (expr.name == "new" && prop == "target") return new AST_NewTarget({
  274. start: my_start_token(M),
  275. end: my_end_token(M),
  276. name: "new.target",
  277. });
  278. return new AST_Dot({
  279. start: my_start_token(M),
  280. end: my_end_token(M),
  281. expression: expr,
  282. property: prop,
  283. });
  284. },
  285. SwitchCase: function(M) {
  286. return new (M.test ? AST_Case : AST_Default)({
  287. start : my_start_token(M),
  288. end : my_end_token(M),
  289. expression : from_moz(M.test),
  290. body : M.consequent.map(from_moz),
  291. });
  292. },
  293. ExportAllDeclaration: function(M) {
  294. var alias = M.exported ? read_name(M.exported) : "*";
  295. return new AST_ExportForeign({
  296. start: my_start_token(M),
  297. end: my_end_token(M),
  298. aliases: [ alias ],
  299. keys: [ "*" ],
  300. path: M.source.value,
  301. });
  302. },
  303. ExportDefaultDeclaration: function(M) {
  304. var decl = from_moz(M.declaration);
  305. if (!decl.name) switch (decl.CTOR) {
  306. case AST_AsyncDefun:
  307. decl = new AST_AsyncFunction(decl);
  308. break;
  309. case AST_AsyncGeneratorDefun:
  310. decl = new AST_AsyncGeneratorFunction(decl);
  311. break;
  312. case AST_DefClass:
  313. decl = new AST_ClassExpression(decl);
  314. break;
  315. case AST_Defun:
  316. decl = new AST_Function(decl);
  317. break;
  318. case AST_GeneratorDefun:
  319. decl = new AST_GeneratorFunction(decl);
  320. break;
  321. }
  322. return new AST_ExportDefault({
  323. start: my_start_token(M),
  324. end: my_end_token(M),
  325. body: decl,
  326. });
  327. },
  328. ExportNamedDeclaration: function(M) {
  329. if (M.declaration) return new AST_ExportDeclaration({
  330. start: my_start_token(M),
  331. end: my_end_token(M),
  332. body: from_moz(M.declaration),
  333. });
  334. if (M.source) {
  335. var aliases = [], keys = [];
  336. M.specifiers.forEach(function(prop) {
  337. aliases.push(read_name(prop.exported));
  338. keys.push(read_name(prop.local));
  339. });
  340. return new AST_ExportForeign({
  341. start: my_start_token(M),
  342. end: my_end_token(M),
  343. aliases: aliases,
  344. keys: keys,
  345. path: M.source.value,
  346. });
  347. }
  348. return new AST_ExportReferences({
  349. start: my_start_token(M),
  350. end: my_end_token(M),
  351. properties: M.specifiers.map(function(prop) {
  352. var sym = new AST_SymbolExport(from_moz(prop.local));
  353. sym.alias = read_name(prop.exported);
  354. return sym;
  355. }),
  356. });
  357. },
  358. ImportDeclaration: function(M) {
  359. var all = null, def = null, props = null;
  360. M.specifiers.forEach(function(prop) {
  361. var sym = new AST_SymbolImport(from_moz(prop.local));
  362. switch (prop.type) {
  363. case "ImportDefaultSpecifier":
  364. def = sym;
  365. def.key = "";
  366. break;
  367. case "ImportNamespaceSpecifier":
  368. all = sym;
  369. all.key = "*";
  370. break;
  371. default:
  372. sym.key = prop.imported.name || syn.name;
  373. if (!props) props = [];
  374. props.push(sym);
  375. break;
  376. }
  377. });
  378. return new AST_Import({
  379. start: my_start_token(M),
  380. end: my_end_token(M),
  381. all: all,
  382. default: def,
  383. properties: props,
  384. path: M.source.value,
  385. });
  386. },
  387. ImportExpression: function(M) {
  388. var start = my_start_token(M);
  389. var arg = from_moz(M.source);
  390. return new AST_Call({
  391. start: start,
  392. end: my_end_token(M),
  393. expression: new AST_SymbolRef({
  394. start: start,
  395. end: arg.start,
  396. name: "import",
  397. }),
  398. args: [ arg ],
  399. });
  400. },
  401. VariableDeclaration: function(M) {
  402. return new ({
  403. const: AST_Const,
  404. let: AST_Let,
  405. }[M.kind] || AST_Var)({
  406. start: my_start_token(M),
  407. end: my_end_token(M),
  408. definitions: M.declarations.map(from_moz),
  409. });
  410. },
  411. Literal: function(M) {
  412. var args = {
  413. start: my_start_token(M),
  414. end: my_end_token(M),
  415. };
  416. if (M.bigint) {
  417. args.value = M.bigint.toLowerCase() + "n";
  418. return new AST_BigInt(args);
  419. }
  420. var val = M.value;
  421. if (val === null) return new AST_Null(args);
  422. var rx = M.regex;
  423. if (rx && rx.pattern) {
  424. // RegExpLiteral as per ESTree AST spec
  425. args.value = new RegExp(rx.pattern, rx.flags);
  426. args.value.raw_source = rx.pattern;
  427. return new AST_RegExp(args);
  428. } else if (rx) {
  429. // support legacy RegExp
  430. args.value = M.regex && M.raw ? M.raw : val;
  431. return new AST_RegExp(args);
  432. }
  433. switch (typeof val) {
  434. case "string":
  435. args.value = val;
  436. return new AST_String(args);
  437. case "number":
  438. if (isNaN(val)) return new AST_NaN(args);
  439. var negate, node;
  440. if (isFinite(val)) {
  441. negate = 1 / val < 0;
  442. args.value = negate ? -val : val;
  443. node = new AST_Number(args);
  444. } else {
  445. negate = val < 0;
  446. node = new AST_Infinity(args);
  447. }
  448. return negate ? new AST_UnaryPrefix({
  449. start: args.start,
  450. end: args.end,
  451. operator: "-",
  452. expression: node,
  453. }) : node;
  454. case "boolean":
  455. return new (val ? AST_True : AST_False)(args);
  456. }
  457. },
  458. TemplateLiteral: function(M) {
  459. return new AST_Template({
  460. start: my_start_token(M),
  461. end: my_end_token(M),
  462. expressions: M.expressions.map(from_moz),
  463. strings: M.quasis.map(function(el) {
  464. return el.value.raw;
  465. }),
  466. });
  467. },
  468. TaggedTemplateExpression: function(M) {
  469. var tmpl = from_moz(M.quasi);
  470. tmpl.start = my_start_token(M);
  471. tmpl.end = my_end_token(M);
  472. tmpl.tag = from_moz(M.tag);
  473. return tmpl;
  474. },
  475. Identifier: function(M) {
  476. var p, level = FROM_MOZ_STACK.length - 1;
  477. do {
  478. p = FROM_MOZ_STACK[--level];
  479. } while (p.type == "ArrayPattern"
  480. || p.type == "AssignmentPattern" && p.left === FROM_MOZ_STACK[level + 1]
  481. || p.type == "ObjectPattern"
  482. || p.type == "Property" && p.value === FROM_MOZ_STACK[level + 1]
  483. || p.type == "VariableDeclarator" && p.id === FROM_MOZ_STACK[level + 1]);
  484. var ctor = AST_SymbolRef;
  485. switch (p.type) {
  486. case "ArrowFunctionExpression":
  487. if (p.body !== FROM_MOZ_STACK[level + 1]) ctor = AST_SymbolFunarg;
  488. break;
  489. case "BreakStatement":
  490. case "ContinueStatement":
  491. ctor = AST_LabelRef;
  492. break;
  493. case "CatchClause":
  494. ctor = AST_SymbolCatch;
  495. break;
  496. case "ClassDeclaration":
  497. if (p.id === FROM_MOZ_STACK[level + 1]) ctor = AST_SymbolDefClass;
  498. break;
  499. case "ClassExpression":
  500. if (p.id === FROM_MOZ_STACK[level + 1]) ctor = AST_SymbolClass;
  501. break;
  502. case "FunctionDeclaration":
  503. ctor = p.id === FROM_MOZ_STACK[level + 1] ? AST_SymbolDefun : AST_SymbolFunarg;
  504. break;
  505. case "FunctionExpression":
  506. ctor = p.id === FROM_MOZ_STACK[level + 1] ? AST_SymbolLambda : AST_SymbolFunarg;
  507. break;
  508. case "LabeledStatement":
  509. ctor = AST_Label;
  510. break;
  511. case "VariableDeclaration":
  512. ctor = {
  513. const: AST_SymbolConst,
  514. let: AST_SymbolLet,
  515. }[p.kind] || AST_SymbolVar;
  516. break;
  517. }
  518. return new ctor({
  519. start: my_start_token(M),
  520. end: my_end_token(M),
  521. name: M.name,
  522. });
  523. },
  524. Super: function(M) {
  525. return new AST_Super({
  526. start: my_start_token(M),
  527. end: my_end_token(M),
  528. name: "super",
  529. });
  530. },
  531. ThisExpression: function(M) {
  532. return new AST_This({
  533. start: my_start_token(M),
  534. end: my_end_token(M),
  535. name: "this",
  536. });
  537. },
  538. ParenthesizedExpression: function(M) {
  539. var node = from_moz(M.expression);
  540. if (!node.start.parens) node.start.parens = [];
  541. node.start.parens.push(my_start_token(M));
  542. if (!node.end.parens) node.end.parens = [];
  543. node.end.parens.push(my_end_token(M));
  544. return node;
  545. },
  546. ChainExpression: function(M) {
  547. return from_moz(M.expression);
  548. },
  549. };
  550. MOZ_TO_ME.UpdateExpression =
  551. MOZ_TO_ME.UnaryExpression = function To_Moz_Unary(M) {
  552. var prefix = "prefix" in M ? M.prefix
  553. : M.type == "UnaryExpression" ? true : false;
  554. return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({
  555. start : my_start_token(M),
  556. end : my_end_token(M),
  557. operator : M.operator,
  558. expression : from_moz(M.argument)
  559. });
  560. };
  561. map("EmptyStatement", AST_EmptyStatement);
  562. map("ExpressionStatement", AST_SimpleStatement, "expression>body");
  563. map("BlockStatement", AST_BlockStatement, "body@body");
  564. map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative");
  565. map("LabeledStatement", AST_LabeledStatement, "label>label, body>body");
  566. map("BreakStatement", AST_Break, "label>label");
  567. map("ContinueStatement", AST_Continue, "label>label");
  568. map("WithStatement", AST_With, "object>expression, body>body");
  569. map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body");
  570. map("ReturnStatement", AST_Return, "argument>value");
  571. map("ThrowStatement", AST_Throw, "argument>value");
  572. map("WhileStatement", AST_While, "test>condition, body>body");
  573. map("DoWhileStatement", AST_Do, "test>condition, body>body");
  574. map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body");
  575. map("ForInStatement", AST_ForIn, "left>init, right>object, body>body");
  576. map("DebuggerStatement", AST_Debugger);
  577. map("VariableDeclarator", AST_VarDef, "id>name, init>value");
  578. map("CatchClause", AST_Catch, "param>argname, body%body");
  579. map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right");
  580. map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right");
  581. map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right");
  582. map("AssignmentPattern", AST_DefaultValue, "left>name, right>value");
  583. map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative");
  584. map("NewExpression", AST_New, "callee>expression, arguments@args, pure=pure");
  585. map("CallExpression", AST_Call, "callee>expression, arguments@args, optional=optional, pure=pure");
  586. map("SequenceExpression", AST_Sequence, "expressions@expressions");
  587. map("SpreadElement", AST_Spread, "argument>expression");
  588. map("ObjectExpression", AST_Object, "properties@properties");
  589. map("AwaitExpression", AST_Await, "argument>expression");
  590. map("YieldExpression", AST_Yield, "argument>expression, delegate=nested");
  591. def_to_moz(AST_Toplevel, function To_Moz_Program(M) {
  592. return to_moz_scope("Program", M);
  593. });
  594. def_to_moz(AST_LambdaDefinition, function To_Moz_FunctionDeclaration(M) {
  595. var params = M.argnames.map(to_moz);
  596. if (M.rest) params.push({
  597. type: "RestElement",
  598. argument: to_moz(M.rest),
  599. });
  600. return {
  601. type: "FunctionDeclaration",
  602. id: to_moz(M.name),
  603. async: is_async(M),
  604. generator: is_generator(M),
  605. params: params,
  606. body: to_moz_scope("BlockStatement", M),
  607. };
  608. });
  609. def_to_moz(AST_Lambda, function To_Moz_FunctionExpression(M) {
  610. var params = M.argnames.map(to_moz);
  611. if (M.rest) params.push({
  612. type: "RestElement",
  613. argument: to_moz(M.rest),
  614. });
  615. if (is_arrow(M)) return {
  616. type: "ArrowFunctionExpression",
  617. async: is_async(M),
  618. params: params,
  619. body: M.value ? to_moz(M.value) : to_moz_scope("BlockStatement", M),
  620. };
  621. return {
  622. type: "FunctionExpression",
  623. id: to_moz(M.name),
  624. async: is_async(M),
  625. generator: is_generator(M),
  626. params: params,
  627. body: to_moz_scope("BlockStatement", M),
  628. };
  629. });
  630. def_to_moz(AST_DefClass, function To_Moz_ClassDeclaration(M) {
  631. return {
  632. type: "ClassDeclaration",
  633. id: to_moz(M.name),
  634. superClass: to_moz(M.extends),
  635. body: {
  636. type: "ClassBody",
  637. body: M.properties.map(to_moz),
  638. },
  639. };
  640. });
  641. def_to_moz(AST_ClassExpression, function To_Moz_ClassExpression(M) {
  642. return {
  643. type: "ClassExpression",
  644. id: to_moz(M.name),
  645. superClass: to_moz(M.extends),
  646. body: {
  647. type: "ClassBody",
  648. body: M.properties.map(to_moz),
  649. },
  650. };
  651. });
  652. function To_Moz_MethodDefinition(kind) {
  653. return function(M) {
  654. var computed = M.key instanceof AST_Node;
  655. var key = computed ? to_moz(M.key) : M.private ? {
  656. type: "PrivateIdentifier",
  657. name: M.key.slice(1),
  658. } : {
  659. type: "Literal",
  660. value: M.key,
  661. };
  662. return {
  663. type: "MethodDefinition",
  664. kind: kind,
  665. computed: computed,
  666. key: key,
  667. static: M.static,
  668. value: to_moz(M.value),
  669. };
  670. };
  671. }
  672. def_to_moz(AST_ClassGetter, To_Moz_MethodDefinition("get"));
  673. def_to_moz(AST_ClassSetter, To_Moz_MethodDefinition("set"));
  674. def_to_moz(AST_ClassMethod, To_Moz_MethodDefinition("method"));
  675. def_to_moz(AST_ClassField, function To_Moz_PropertyDefinition(M) {
  676. var computed = M.key instanceof AST_Node;
  677. var key = computed ? to_moz(M.key) : M.private ? {
  678. type: "PrivateIdentifier",
  679. name: M.key.slice(1),
  680. } : {
  681. type: "Literal",
  682. value: M.key,
  683. };
  684. return {
  685. type: "PropertyDefinition",
  686. computed: computed,
  687. key: key,
  688. static: M.static,
  689. value: to_moz(M.value),
  690. };
  691. });
  692. function To_Moz_ForOfStatement(is_await) {
  693. return function(M) {
  694. return {
  695. type: "ForOfStatement",
  696. await: is_await,
  697. left: to_moz(M.init),
  698. right: to_moz(M.object),
  699. body: to_moz(M.body),
  700. };
  701. };
  702. }
  703. def_to_moz(AST_ForAwaitOf, To_Moz_ForOfStatement(true));
  704. def_to_moz(AST_ForOf, To_Moz_ForOfStatement(false));
  705. def_to_moz(AST_Directive, function To_Moz_Directive(M) {
  706. return {
  707. type: "ExpressionStatement",
  708. expression: set_moz_loc(M, {
  709. type: "Literal",
  710. value: M.value,
  711. }),
  712. };
  713. });
  714. def_to_moz(AST_SwitchBranch, function To_Moz_SwitchCase(M) {
  715. return {
  716. type: "SwitchCase",
  717. test: to_moz(M.expression),
  718. consequent: M.body.map(to_moz),
  719. };
  720. });
  721. def_to_moz(AST_Try, function To_Moz_TryStatement(M) {
  722. return {
  723. type: "TryStatement",
  724. block: to_moz_block(M),
  725. handler: to_moz(M.bcatch),
  726. guardedHandlers: [],
  727. finalizer: to_moz(M.bfinally),
  728. };
  729. });
  730. def_to_moz(AST_Catch, function To_Moz_CatchClause(M) {
  731. return {
  732. type: "CatchClause",
  733. param: to_moz(M.argname),
  734. guard: null,
  735. body: to_moz_block(M),
  736. };
  737. });
  738. def_to_moz(AST_ExportDeclaration, function To_Moz_ExportNamedDeclaration_declaration(M) {
  739. return {
  740. type: "ExportNamedDeclaration",
  741. declaration: to_moz(M.body),
  742. };
  743. });
  744. def_to_moz(AST_ExportDefault, function To_Moz_ExportDefaultDeclaration(M) {
  745. return {
  746. type: "ExportDefaultDeclaration",
  747. declaration: to_moz(M.body),
  748. };
  749. });
  750. def_to_moz(AST_ExportForeign, function To_Moz_ExportAllDeclaration_ExportNamedDeclaration(M) {
  751. if (M.keys[0] == "*") return {
  752. type: "ExportAllDeclaration",
  753. exported: M.aliases[0] == "*" ? null : {
  754. type: "Identifier",
  755. name: M.aliases[0],
  756. },
  757. source: {
  758. type: "Literal",
  759. value: M.path,
  760. },
  761. };
  762. var specifiers = [];
  763. for (var i = 0; i < M.aliases.length; i++) {
  764. specifiers.push({
  765. type: "ExportSpecifier",
  766. exported: {
  767. type: "Identifier",
  768. name: M.aliases[i],
  769. },
  770. local: {
  771. type: "Identifier",
  772. name: M.keys[i],
  773. },
  774. });
  775. }
  776. return {
  777. type: "ExportNamedDeclaration",
  778. specifiers: specifiers,
  779. source: {
  780. type: "Literal",
  781. value: M.path,
  782. },
  783. };
  784. });
  785. def_to_moz(AST_ExportReferences, function To_Moz_ExportNamedDeclaration_specifiers(M) {
  786. return {
  787. type: "ExportNamedDeclaration",
  788. specifiers: M.properties.map(function(prop) {
  789. return {
  790. type: "ExportSpecifier",
  791. local: to_moz(prop),
  792. exported: {
  793. type: "Identifier",
  794. name: prop.alias,
  795. },
  796. };
  797. }),
  798. };
  799. });
  800. def_to_moz(AST_Import, function To_Moz_ImportDeclaration(M) {
  801. var specifiers = M.properties ? M.properties.map(function(prop) {
  802. return {
  803. type: "ImportSpecifier",
  804. local: to_moz(prop),
  805. imported: {
  806. type: "Identifier",
  807. name: prop.key,
  808. },
  809. };
  810. }) : [];
  811. if (M.all) specifiers.unshift({
  812. type: "ImportNamespaceSpecifier",
  813. local: to_moz(M.all),
  814. });
  815. if (M.default) specifiers.unshift({
  816. type: "ImportDefaultSpecifier",
  817. local: to_moz(M.default),
  818. });
  819. return {
  820. type: "ImportDeclaration",
  821. specifiers: specifiers,
  822. source: {
  823. type: "Literal",
  824. value: M.path,
  825. },
  826. };
  827. });
  828. def_to_moz(AST_Definitions, function To_Moz_VariableDeclaration(M) {
  829. return {
  830. type: "VariableDeclaration",
  831. kind: M.TYPE.toLowerCase(),
  832. declarations: M.definitions.map(to_moz),
  833. };
  834. });
  835. def_to_moz(AST_PropAccess, function To_Moz_MemberExpression(M) {
  836. var computed = M instanceof AST_Sub;
  837. return {
  838. type: "MemberExpression",
  839. object: to_moz(M.expression),
  840. computed: computed,
  841. optional: M.optional,
  842. property: computed ? to_moz(M.property) : {
  843. type: "Identifier",
  844. name: M.property,
  845. },
  846. };
  847. });
  848. def_to_moz(AST_Unary, function To_Moz_Unary(M) {
  849. return {
  850. type: M.operator == "++" || M.operator == "--" ? "UpdateExpression" : "UnaryExpression",
  851. operator: M.operator,
  852. prefix: M instanceof AST_UnaryPrefix,
  853. argument: to_moz(M.expression)
  854. };
  855. });
  856. def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) {
  857. return {
  858. type: M.operator == "&&" || M.operator == "||" ? "LogicalExpression" : "BinaryExpression",
  859. left: to_moz(M.left),
  860. operator: M.operator,
  861. right: to_moz(M.right)
  862. };
  863. });
  864. def_to_moz(AST_Array, function To_Moz_ArrayExpression(M) {
  865. return {
  866. type: "ArrayExpression",
  867. elements: M.elements.map(to_moz),
  868. };
  869. });
  870. def_to_moz(AST_DestructuredArray, function To_Moz_ArrayPattern(M) {
  871. var elements = M.elements.map(to_moz);
  872. if (M.rest) elements.push({
  873. type: "RestElement",
  874. argument: to_moz(M.rest),
  875. });
  876. return {
  877. type: "ArrayPattern",
  878. elements: elements,
  879. };
  880. });
  881. def_to_moz(AST_DestructuredKeyVal, function To_Moz_Property(M) {
  882. var computed = M.key instanceof AST_Node;
  883. var key = computed ? to_moz(M.key) : {
  884. type: "Literal",
  885. value: M.key,
  886. };
  887. return {
  888. type: "Property",
  889. kind: "init",
  890. computed: computed,
  891. key: key,
  892. value: to_moz(M.value),
  893. };
  894. });
  895. def_to_moz(AST_DestructuredObject, function To_Moz_ObjectPattern(M) {
  896. var props = M.properties.map(to_moz);
  897. if (M.rest) props.push({
  898. type: "RestElement",
  899. argument: to_moz(M.rest),
  900. });
  901. return {
  902. type: "ObjectPattern",
  903. properties: props,
  904. };
  905. });
  906. def_to_moz(AST_ObjectProperty, function To_Moz_Property(M) {
  907. var computed = M.key instanceof AST_Node;
  908. var key = computed ? to_moz(M.key) : {
  909. type: "Literal",
  910. value: M.key,
  911. };
  912. var kind;
  913. if (M instanceof AST_ObjectKeyVal) {
  914. kind = "init";
  915. } else if (M instanceof AST_ObjectGetter) {
  916. kind = "get";
  917. } else if (M instanceof AST_ObjectSetter) {
  918. kind = "set";
  919. }
  920. return {
  921. type: "Property",
  922. kind: kind,
  923. computed: computed,
  924. method: M instanceof AST_ObjectMethod,
  925. key: key,
  926. value: to_moz(M.value),
  927. };
  928. });
  929. def_to_moz(AST_Symbol, function To_Moz_Identifier(M) {
  930. var def = M.definition();
  931. return {
  932. type: "Identifier",
  933. name: def && def.mangled_name || M.name,
  934. };
  935. });
  936. def_to_moz(AST_Super, function To_Moz_Super() {
  937. return { type: "Super" };
  938. });
  939. def_to_moz(AST_This, function To_Moz_ThisExpression() {
  940. return { type: "ThisExpression" };
  941. });
  942. def_to_moz(AST_NewTarget, function To_Moz_MetaProperty() {
  943. return {
  944. type: "MetaProperty",
  945. meta: {
  946. type: "Identifier",
  947. name: "new",
  948. },
  949. property: {
  950. type: "Identifier",
  951. name: "target",
  952. },
  953. };
  954. });
  955. def_to_moz(AST_RegExp, function To_Moz_RegExpLiteral(M) {
  956. var flags = M.value.toString().match(/[gimuy]*$/)[0];
  957. var value = "/" + M.value.raw_source + "/" + flags;
  958. return {
  959. type: "Literal",
  960. value: value,
  961. raw: value,
  962. regex: {
  963. pattern: M.value.raw_source,
  964. flags: flags
  965. }
  966. };
  967. });
  968. def_to_moz(AST_BigInt, function To_Moz_BigInt(M) {
  969. var value = M.value;
  970. return {
  971. type: "Literal",
  972. bigint: value.slice(0, -1),
  973. raw: value,
  974. };
  975. });
  976. function To_Moz_Literal(M) {
  977. var value = M.value;
  978. if (typeof value === "number" && (value < 0 || (value === 0 && 1 / value < 0))) {
  979. return {
  980. type: "UnaryExpression",
  981. operator: "-",
  982. prefix: true,
  983. argument: {
  984. type: "Literal",
  985. value: -value,
  986. raw: M.start.raw,
  987. },
  988. };
  989. }
  990. return {
  991. type: "Literal",
  992. value: value,
  993. raw: M.start.raw,
  994. };
  995. }
  996. def_to_moz(AST_Boolean, To_Moz_Literal);
  997. def_to_moz(AST_Constant, To_Moz_Literal);
  998. def_to_moz(AST_Null, To_Moz_Literal);
  999. def_to_moz(AST_Atom, function To_Moz_Atom(M) {
  1000. return {
  1001. type: "Identifier",
  1002. name: String(M.value),
  1003. };
  1004. });
  1005. def_to_moz(AST_Template, function To_Moz_TemplateLiteral_TaggedTemplateExpression(M) {
  1006. var last = M.strings.length - 1;
  1007. var tmpl = {
  1008. type: "TemplateLiteral",
  1009. expressions: M.expressions.map(to_moz),
  1010. quasis: M.strings.map(function(str, index) {
  1011. return {
  1012. type: "TemplateElement",
  1013. tail: index == last,
  1014. value: { raw: str },
  1015. };
  1016. }),
  1017. };
  1018. if (!M.tag) return tmpl;
  1019. return {
  1020. type: "TaggedTemplateExpression",
  1021. tag: to_moz(M.tag),
  1022. quasi: tmpl,
  1023. };
  1024. });
  1025. AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast);
  1026. AST_Hole.DEFMETHOD("to_mozilla_ast", return_null);
  1027. AST_Node.DEFMETHOD("to_mozilla_ast", function() {
  1028. throw new Error("Cannot convert AST_" + this.TYPE);
  1029. });
  1030. /* -----[ tools ]----- */
  1031. function normalize_directives(body) {
  1032. for (var i = 0; i < body.length; i++) {
  1033. var stat = body[i];
  1034. if (!(stat instanceof AST_SimpleStatement)) break;
  1035. var node = stat.body;
  1036. if (!(node instanceof AST_String)) break;
  1037. if (stat.start.pos !== node.start.pos) break;
  1038. body[i] = new AST_Directive(node);
  1039. }
  1040. return body;
  1041. }
  1042. function raw_token(moznode) {
  1043. if (moznode.type == "Literal") {
  1044. return moznode.raw != null ? moznode.raw : moznode.value + "";
  1045. }
  1046. }
  1047. function my_start_token(moznode) {
  1048. var loc = moznode.loc, start = loc && loc.start;
  1049. var range = moznode.range;
  1050. return new AST_Token({
  1051. file : loc && loc.source,
  1052. line : start && start.line,
  1053. col : start && start.column,
  1054. pos : range ? range[0] : moznode.start,
  1055. endline : start && start.line,
  1056. endcol : start && start.column,
  1057. endpos : range ? range[0] : moznode.start,
  1058. raw : raw_token(moznode),
  1059. });
  1060. }
  1061. function my_end_token(moznode) {
  1062. var loc = moznode.loc, end = loc && loc.end;
  1063. var range = moznode.range;
  1064. return new AST_Token({
  1065. file : loc && loc.source,
  1066. line : end && end.line,
  1067. col : end && end.column,
  1068. pos : range ? range[1] : moznode.end,
  1069. endline : end && end.line,
  1070. endcol : end && end.column,
  1071. endpos : range ? range[1] : moznode.end,
  1072. raw : raw_token(moznode),
  1073. });
  1074. }
  1075. function read_name(M) {
  1076. return "" + M[M.type == "Identifier" ? "name" : "value"];
  1077. }
  1078. function map(moztype, mytype, propmap) {
  1079. var moz_to_me = "function From_Moz_" + moztype + "(M){\n";
  1080. moz_to_me += "return new U2." + mytype.name + "({\n" +
  1081. "start: my_start_token(M),\n" +
  1082. "end: my_end_token(M)";
  1083. var me_to_moz = "function To_Moz_" + moztype + "(M){\n";
  1084. me_to_moz += "return {\n" +
  1085. "type: " + JSON.stringify(moztype);
  1086. if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop) {
  1087. var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop);
  1088. if (!m) throw new Error("Can't understand property map: " + prop);
  1089. var moz = m[1], how = m[2], my = m[3];
  1090. moz_to_me += ",\n" + my + ": ";
  1091. me_to_moz += ",\n" + moz + ": ";
  1092. switch (how) {
  1093. case "@":
  1094. moz_to_me += "M." + moz + ".map(from_moz)";
  1095. me_to_moz += "M." + my + ".map(to_moz)";
  1096. break;
  1097. case ">":
  1098. moz_to_me += "from_moz(M." + moz + ")";
  1099. me_to_moz += "to_moz(M." + my + ")";
  1100. break;
  1101. case "=":
  1102. moz_to_me += "M." + moz;
  1103. me_to_moz += "M." + my;
  1104. break;
  1105. case "%":
  1106. moz_to_me += "from_moz(M." + moz + ").body";
  1107. me_to_moz += "to_moz_block(M)";
  1108. break;
  1109. default:
  1110. throw new Error("Can't understand operator in propmap: " + prop);
  1111. }
  1112. });
  1113. moz_to_me += "\n})\n}";
  1114. me_to_moz += "\n}\n}";
  1115. //moz_to_me = parse(moz_to_me).print_to_string({ beautify: true });
  1116. //me_to_moz = parse(me_to_moz).print_to_string({ beautify: true });
  1117. //console.log(moz_to_me);
  1118. moz_to_me = new Function("U2", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")(
  1119. exports, my_start_token, my_end_token, from_moz
  1120. );
  1121. me_to_moz = new Function("to_moz", "to_moz_block", "to_moz_scope", "return(" + me_to_moz + ")")(
  1122. to_moz, to_moz_block, to_moz_scope
  1123. );
  1124. MOZ_TO_ME[moztype] = moz_to_me;
  1125. def_to_moz(mytype, me_to_moz);
  1126. }
  1127. var FROM_MOZ_STACK = null;
  1128. function from_moz(moz) {
  1129. FROM_MOZ_STACK.push(moz);
  1130. var node = null;
  1131. if (moz) {
  1132. if (!HOP(MOZ_TO_ME, moz.type)) throw new Error("Unsupported type: " + moz.type);
  1133. node = MOZ_TO_ME[moz.type](moz);
  1134. }
  1135. FROM_MOZ_STACK.pop();
  1136. return node;
  1137. }
  1138. AST_Node.from_mozilla_ast = function(node) {
  1139. var save_stack = FROM_MOZ_STACK;
  1140. FROM_MOZ_STACK = [];
  1141. var ast = from_moz(node);
  1142. FROM_MOZ_STACK = save_stack;
  1143. ast.walk(new TreeWalker(function(node) {
  1144. if (node instanceof AST_LabelRef) {
  1145. for (var level = 0, parent; parent = this.parent(level); level++) {
  1146. if (parent instanceof AST_Scope) break;
  1147. if (parent instanceof AST_LabeledStatement && parent.label.name == node.name) {
  1148. node.thedef = parent.label;
  1149. break;
  1150. }
  1151. }
  1152. if (!node.thedef) {
  1153. var s = node.start;
  1154. js_error("Undefined label " + node.name, s.file, s.line, s.col, s.pos);
  1155. }
  1156. }
  1157. }));
  1158. return ast;
  1159. };
  1160. function set_moz_loc(mynode, moznode) {
  1161. var start = mynode.start;
  1162. var end = mynode.end;
  1163. if (start.pos != null && end.endpos != null) {
  1164. moznode.range = [start.pos, end.endpos];
  1165. }
  1166. if (start.line) {
  1167. moznode.loc = {
  1168. start: {line: start.line, column: start.col},
  1169. end: end.endline ? {line: end.endline, column: end.endcol} : null,
  1170. };
  1171. if (start.file) {
  1172. moznode.loc.source = start.file;
  1173. }
  1174. }
  1175. return moznode;
  1176. }
  1177. function def_to_moz(mytype, handler) {
  1178. mytype.DEFMETHOD("to_mozilla_ast", function() {
  1179. return set_moz_loc(this, handler(this));
  1180. });
  1181. }
  1182. function to_moz(node) {
  1183. return node != null ? node.to_mozilla_ast() : null;
  1184. }
  1185. function to_moz_block(node) {
  1186. return {
  1187. type: "BlockStatement",
  1188. body: node.body.map(to_moz),
  1189. };
  1190. }
  1191. function to_moz_scope(type, node) {
  1192. var body = node.body.map(to_moz);
  1193. if (node.body[0] instanceof AST_SimpleStatement && node.body[0].body instanceof AST_String) {
  1194. body.unshift(to_moz(new AST_EmptyStatement(node.body[0])));
  1195. }
  1196. return {
  1197. type: type,
  1198. body: body,
  1199. };
  1200. }
  1201. })();