mozilla-ast.js 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087
  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. ArrayPattern: function(M) {
  59. return new AST_Destructuring({
  60. start: my_start_token(M),
  61. end: my_end_token(M),
  62. names: M.elements.map(function(elm) {
  63. if (elm === null) {
  64. return new AST_Hole();
  65. }
  66. return from_moz(elm);
  67. }),
  68. is_array: true
  69. });
  70. },
  71. ObjectPattern: function(M) {
  72. return new AST_Destructuring({
  73. start: my_start_token(M),
  74. end: my_end_token(M),
  75. names: M.properties.map(from_moz),
  76. is_array: false
  77. });
  78. },
  79. AssignmentPattern: function(M) {
  80. return new AST_Binary({
  81. start: my_start_token(M),
  82. end: my_end_token(M),
  83. left: from_moz(M.left),
  84. operator: "=",
  85. right: from_moz(M.right)
  86. });
  87. },
  88. SpreadElement: function(M) {
  89. return new AST_Expansion({
  90. start: my_start_token(M),
  91. end: my_end_token(M),
  92. expression: from_moz(M.argument)
  93. });
  94. },
  95. RestElement: function(M) {
  96. return new AST_Expansion({
  97. start: my_start_token(M),
  98. end: my_end_token(M),
  99. expression: from_moz(M.argument)
  100. });
  101. },
  102. TemplateElement: function(M) {
  103. return new AST_TemplateSegment({
  104. start: my_start_token(M),
  105. end: my_end_token(M),
  106. value: M.value.cooked,
  107. raw: M.value.raw
  108. });
  109. },
  110. TemplateLiteral: function(M) {
  111. var segments = [];
  112. for (var i = 0; i < M.quasis.length; i++) {
  113. segments.push(from_moz(M.quasis[i]));
  114. if (M.expressions[i]) {
  115. segments.push(from_moz(M.expressions[i]));
  116. }
  117. }
  118. return new AST_TemplateString({
  119. start: my_start_token(M),
  120. end: my_end_token(M),
  121. segments: segments
  122. });
  123. },
  124. TaggedTemplateExpression: function(M) {
  125. return new AST_PrefixedTemplateString({
  126. start: my_start_token(M),
  127. end: my_end_token(M),
  128. template_string: from_moz(M.quasi),
  129. prefix: from_moz(M.tag)
  130. });
  131. },
  132. FunctionDeclaration: function(M) {
  133. return new AST_Defun({
  134. start: my_start_token(M),
  135. end: my_end_token(M),
  136. name: from_moz(M.id),
  137. argnames: M.params.map(from_moz),
  138. is_generator: M.generator,
  139. async: M.async,
  140. body: normalize_directives(from_moz(M.body).body)
  141. });
  142. },
  143. FunctionExpression: function(M) {
  144. return new AST_Function({
  145. start: my_start_token(M),
  146. end: my_end_token(M),
  147. name: from_moz(M.id),
  148. argnames: M.params.map(from_moz),
  149. is_generator: M.generator,
  150. async: M.async,
  151. body: normalize_directives(from_moz(M.body).body)
  152. });
  153. },
  154. ArrowFunctionExpression: function(M) {
  155. return new AST_Arrow({
  156. start: my_start_token(M),
  157. end: my_end_token(M),
  158. argnames: M.params.map(from_moz),
  159. body: from_moz(M.body),
  160. async: M.async,
  161. });
  162. },
  163. ExpressionStatement: function(M) {
  164. return new AST_SimpleStatement({
  165. start: my_start_token(M),
  166. end: my_end_token(M),
  167. body: from_moz(M.expression)
  168. });
  169. },
  170. TryStatement: function(M) {
  171. var handlers = M.handlers || [M.handler];
  172. if (handlers.length > 1 || M.guardedHandlers && M.guardedHandlers.length) {
  173. throw new Error("Multiple catch clauses are not supported.");
  174. }
  175. return new AST_Try({
  176. start : my_start_token(M),
  177. end : my_end_token(M),
  178. body : from_moz(M.block).body,
  179. bcatch : from_moz(handlers[0]),
  180. bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null
  181. });
  182. },
  183. Property: function(M) {
  184. var key = M.key;
  185. var args = {
  186. start : my_start_token(key || M.value),
  187. end : my_end_token(M.value),
  188. key : key.type == "Identifier" ? key.name : key.value,
  189. value : from_moz(M.value)
  190. };
  191. if (M.computed) {
  192. args.key = from_moz(M.key);
  193. }
  194. if (M.method) {
  195. args.is_generator = M.value.generator;
  196. args.async = M.value.async;
  197. if (!M.computed) {
  198. args.key = new AST_SymbolMethod({ name: args.key });
  199. } else {
  200. args.key = from_moz(M.key);
  201. }
  202. return new AST_ConciseMethod(args);
  203. }
  204. if (M.kind == "init") {
  205. if (key.type != "Identifier" && key.type != "Literal") {
  206. args.key = from_moz(key);
  207. }
  208. return new AST_ObjectKeyVal(args);
  209. }
  210. if (typeof args.key === "string" || typeof args.key === "number") {
  211. args.key = new AST_SymbolMethod({
  212. name: args.key
  213. });
  214. }
  215. args.value = new AST_Accessor(args.value);
  216. if (M.kind == "get") return new AST_ObjectGetter(args);
  217. if (M.kind == "set") return new AST_ObjectSetter(args);
  218. if (M.kind == "method") {
  219. args.async = M.value.async;
  220. args.is_generator = M.value.generator;
  221. args.quote = M.computed ? "\"" : null;
  222. return new AST_ConciseMethod(args);
  223. }
  224. },
  225. MethodDefinition: function(M) {
  226. var args = {
  227. start : my_start_token(M),
  228. end : my_end_token(M),
  229. key : M.computed ? from_moz(M.key) : new AST_SymbolMethod({ name: M.key.name || M.key.value }),
  230. value : from_moz(M.value),
  231. static : M.static,
  232. };
  233. if (M.kind == "get") {
  234. return new AST_ObjectGetter(args);
  235. }
  236. if (M.kind == "set") {
  237. return new AST_ObjectSetter(args);
  238. }
  239. args.is_generator = M.value.generator;
  240. args.async = M.value.async;
  241. return new AST_ConciseMethod(args);
  242. },
  243. ArrayExpression: function(M) {
  244. return new AST_Array({
  245. start : my_start_token(M),
  246. end : my_end_token(M),
  247. elements : M.elements.map(function(elem) {
  248. return elem === null ? new AST_Hole() : from_moz(elem);
  249. })
  250. });
  251. },
  252. ObjectExpression: function(M) {
  253. return new AST_Object({
  254. start : my_start_token(M),
  255. end : my_end_token(M),
  256. properties : M.properties.map(function(prop) {
  257. if (prop.type === "SpreadElement") {
  258. return from_moz(prop);
  259. }
  260. prop.type = "Property";
  261. return from_moz(prop);
  262. })
  263. });
  264. },
  265. SequenceExpression: function(M) {
  266. return new AST_Sequence({
  267. start : my_start_token(M),
  268. end : my_end_token(M),
  269. expressions: M.expressions.map(from_moz)
  270. });
  271. },
  272. MemberExpression: function(M) {
  273. return new (M.computed ? AST_Sub : AST_Dot)({
  274. start : my_start_token(M),
  275. end : my_end_token(M),
  276. property : M.computed ? from_moz(M.property) : M.property.name,
  277. expression : from_moz(M.object)
  278. });
  279. },
  280. SwitchCase: function(M) {
  281. return new (M.test ? AST_Case : AST_Default)({
  282. start : my_start_token(M),
  283. end : my_end_token(M),
  284. expression : from_moz(M.test),
  285. body : M.consequent.map(from_moz)
  286. });
  287. },
  288. VariableDeclaration: function(M) {
  289. return new (M.kind === "const" ? AST_Const :
  290. M.kind === "let" ? AST_Let : AST_Var)({
  291. start : my_start_token(M),
  292. end : my_end_token(M),
  293. definitions : M.declarations.map(from_moz)
  294. });
  295. },
  296. ImportDeclaration: function(M) {
  297. var imported_name = null;
  298. var imported_names = null;
  299. M.specifiers.forEach(function (specifier) {
  300. if (specifier.type === "ImportSpecifier") {
  301. if (!imported_names) { imported_names = []; }
  302. imported_names.push(new AST_NameMapping({
  303. start: my_start_token(specifier),
  304. end: my_end_token(specifier),
  305. foreign_name: from_moz(specifier.imported),
  306. name: from_moz(specifier.local)
  307. }));
  308. } else if (specifier.type === "ImportDefaultSpecifier") {
  309. imported_name = from_moz(specifier.local);
  310. } else if (specifier.type === "ImportNamespaceSpecifier") {
  311. if (!imported_names) { imported_names = []; }
  312. imported_names.push(new AST_NameMapping({
  313. start: my_start_token(specifier),
  314. end: my_end_token(specifier),
  315. foreign_name: new AST_SymbolImportForeign({ name: "*" }),
  316. name: from_moz(specifier.local)
  317. }));
  318. }
  319. });
  320. return new AST_Import({
  321. start : my_start_token(M),
  322. end : my_end_token(M),
  323. imported_name: imported_name,
  324. imported_names : imported_names,
  325. module_name : from_moz(M.source)
  326. });
  327. },
  328. ExportAllDeclaration: function(M) {
  329. return new AST_Export({
  330. start: my_start_token(M),
  331. end: my_end_token(M),
  332. exported_names: [
  333. new AST_NameMapping({
  334. name: new AST_SymbolExportForeign({ name: "*" }),
  335. foreign_name: new AST_SymbolExportForeign({ name: "*" })
  336. })
  337. ],
  338. module_name: from_moz(M.source)
  339. });
  340. },
  341. ExportNamedDeclaration: function(M) {
  342. return new AST_Export({
  343. start: my_start_token(M),
  344. end: my_end_token(M),
  345. exported_definition: from_moz(M.declaration),
  346. exported_names: M.specifiers && M.specifiers.length ? M.specifiers.map(function (specifier) {
  347. return new AST_NameMapping({
  348. foreign_name: from_moz(specifier.exported),
  349. name: from_moz(specifier.local)
  350. });
  351. }) : null,
  352. module_name: from_moz(M.source)
  353. });
  354. },
  355. ExportDefaultDeclaration: function(M) {
  356. return new AST_Export({
  357. start: my_start_token(M),
  358. end: my_end_token(M),
  359. exported_value: from_moz(M.declaration),
  360. is_default: true
  361. });
  362. },
  363. Literal: function(M) {
  364. var val = M.value, args = {
  365. start : my_start_token(M),
  366. end : my_end_token(M)
  367. };
  368. if (val === null) return new AST_Null(args);
  369. var rx = M.regex;
  370. if (rx && rx.pattern) {
  371. // RegExpLiteral as per ESTree AST spec
  372. args.value = new RegExp(rx.pattern, rx.flags);
  373. var raw = args.value.toString();
  374. args.value.raw_source = rx.flags
  375. ? raw.substring(0, raw.length - rx.flags.length) + rx.flags
  376. : raw;
  377. return new AST_RegExp(args);
  378. } else if (rx) {
  379. // support legacy RegExp
  380. args.value = M.regex && M.raw ? M.raw : val;
  381. return new AST_RegExp(args);
  382. }
  383. switch (typeof val) {
  384. case "string":
  385. args.value = val;
  386. return new AST_String(args);
  387. case "number":
  388. args.value = val;
  389. return new AST_Number(args);
  390. case "boolean":
  391. return new (val ? AST_True : AST_False)(args);
  392. }
  393. },
  394. MetaProperty: function(M) {
  395. if (M.meta.name === "new" && M.property.name === "target") {
  396. return new AST_NewTarget({
  397. start: my_start_token(M),
  398. end: my_end_token(M)
  399. });
  400. }
  401. },
  402. Identifier: function(M) {
  403. var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2];
  404. return new ( p.type == "LabeledStatement" ? AST_Label
  405. : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : p.kind == "let" ? AST_SymbolLet : AST_SymbolVar)
  406. : /Import.*Specifier/.test(p.type) ? (p.local === M ? AST_SymbolImport : AST_SymbolImportForeign)
  407. : p.type == "ExportSpecifier" ? (p.local === M ? AST_SymbolExport : AST_SymbolExportForeign)
  408. : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg)
  409. : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg)
  410. : p.type == "ArrowFunctionExpression" ? (p.params.indexOf(M) !== -1) ? AST_SymbolFunarg : AST_SymbolRef
  411. : p.type == "ClassExpression" ? (p.id === M ? AST_SymbolClass : AST_SymbolRef)
  412. : p.type == "Property" ? (p.key === M && p.computed || p.value === M ? AST_SymbolRef : AST_SymbolMethod)
  413. : p.type == "ClassDeclaration" ? (p.id === M ? AST_SymbolDefClass : AST_SymbolRef)
  414. : p.type == "MethodDefinition" ? (p.computed ? AST_SymbolRef : AST_SymbolMethod)
  415. : p.type == "CatchClause" ? AST_SymbolCatch
  416. : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef
  417. : AST_SymbolRef)({
  418. start : my_start_token(M),
  419. end : my_end_token(M),
  420. name : M.name
  421. });
  422. }
  423. };
  424. MOZ_TO_ME.UpdateExpression =
  425. MOZ_TO_ME.UnaryExpression = function To_Moz_Unary(M) {
  426. var prefix = "prefix" in M ? M.prefix
  427. : M.type == "UnaryExpression" ? true : false;
  428. return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({
  429. start : my_start_token(M),
  430. end : my_end_token(M),
  431. operator : M.operator,
  432. expression : from_moz(M.argument)
  433. });
  434. };
  435. MOZ_TO_ME.ClassDeclaration =
  436. MOZ_TO_ME.ClassExpression = function From_Moz_Class(M) {
  437. return new (M.type === "ClassDeclaration" ? AST_DefClass : AST_ClassExpression)({
  438. start : my_start_token(M),
  439. end : my_end_token(M),
  440. name : from_moz(M.id),
  441. extends : from_moz(M.superClass),
  442. properties: M.body.body.map(from_moz)
  443. });
  444. };
  445. map("EmptyStatement", AST_EmptyStatement);
  446. map("BlockStatement", AST_BlockStatement, "body@body");
  447. map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative");
  448. map("LabeledStatement", AST_LabeledStatement, "label>label, body>body");
  449. map("BreakStatement", AST_Break, "label>label");
  450. map("ContinueStatement", AST_Continue, "label>label");
  451. map("WithStatement", AST_With, "object>expression, body>body");
  452. map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body");
  453. map("ReturnStatement", AST_Return, "argument>value");
  454. map("ThrowStatement", AST_Throw, "argument>value");
  455. map("WhileStatement", AST_While, "test>condition, body>body");
  456. map("DoWhileStatement", AST_Do, "test>condition, body>body");
  457. map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body");
  458. map("ForInStatement", AST_ForIn, "left>init, right>object, body>body");
  459. map("ForOfStatement", AST_ForOf, "left>init, right>object, body>body, await=await");
  460. map("AwaitExpression", AST_Await, "argument>expression");
  461. map("YieldExpression", AST_Yield, "argument>expression, delegate=is_star");
  462. map("DebuggerStatement", AST_Debugger);
  463. map("VariableDeclarator", AST_VarDef, "id>name, init>value");
  464. map("CatchClause", AST_Catch, "param>argname, body%body");
  465. map("ThisExpression", AST_This);
  466. map("Super", AST_Super);
  467. map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right");
  468. map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right");
  469. map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right");
  470. map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative");
  471. map("NewExpression", AST_New, "callee>expression, arguments@args");
  472. map("CallExpression", AST_Call, "callee>expression, arguments@args");
  473. def_to_moz(AST_Toplevel, function To_Moz_Program(M) {
  474. return to_moz_scope("Program", M);
  475. });
  476. def_to_moz(AST_Expansion, function To_Moz_Spread(M, parent) {
  477. return {
  478. type: to_moz_in_destructuring() ? "RestElement" : "SpreadElement",
  479. argument: to_moz(M.expression)
  480. };
  481. });
  482. def_to_moz(AST_PrefixedTemplateString, function To_Moz_TaggedTemplateExpression(M) {
  483. return {
  484. type: "TaggedTemplateExpression",
  485. tag: to_moz(M.prefix),
  486. quasi: to_moz(M.template_string)
  487. };
  488. });
  489. def_to_moz(AST_TemplateString, function To_Moz_TemplateLiteral(M) {
  490. var quasis = [];
  491. var expressions = [];
  492. for (var i = 0; i < M.segments.length; i++) {
  493. if (i % 2 !== 0) {
  494. expressions.push(to_moz(M.segments[i]));
  495. } else {
  496. quasis.push({
  497. type: "TemplateElement",
  498. value: {
  499. raw: M.segments[i].raw,
  500. cooked: M.segments[i].value
  501. },
  502. tail: i === M.segments.length - 1
  503. });
  504. }
  505. }
  506. return {
  507. type: "TemplateLiteral",
  508. quasis: quasis,
  509. expressions: expressions
  510. };
  511. });
  512. def_to_moz(AST_Defun, function To_Moz_FunctionDeclaration(M) {
  513. return {
  514. type: "FunctionDeclaration",
  515. id: to_moz(M.name),
  516. params: M.argnames.map(to_moz),
  517. generator: M.is_generator,
  518. async: M.async,
  519. body: to_moz_scope("BlockStatement", M)
  520. };
  521. });
  522. def_to_moz(AST_Function, function To_Moz_FunctionExpression(M, parent) {
  523. var is_generator = parent.is_generator !== undefined ?
  524. parent.is_generator : M.is_generator;
  525. return {
  526. type: "FunctionExpression",
  527. id: to_moz(M.name),
  528. params: M.argnames.map(to_moz),
  529. generator: is_generator,
  530. async: M.async,
  531. body: to_moz_scope("BlockStatement", M)
  532. };
  533. });
  534. def_to_moz(AST_Arrow, function To_Moz_ArrowFunctionExpression(M) {
  535. var body = M.body instanceof Array ? {
  536. type: "BlockStatement",
  537. body: M.body.map(to_moz)
  538. } : to_moz(M.body);
  539. return {
  540. type: "ArrowFunctionExpression",
  541. params: M.argnames.map(to_moz),
  542. async: M.async,
  543. body: body
  544. };
  545. });
  546. def_to_moz(AST_Destructuring, function To_Moz_ObjectPattern(M) {
  547. if (M.is_array) {
  548. return {
  549. type: "ArrayPattern",
  550. elements: M.names.map(to_moz)
  551. };
  552. }
  553. return {
  554. type: "ObjectPattern",
  555. properties: M.names.map(to_moz)
  556. };
  557. });
  558. def_to_moz(AST_Directive, function To_Moz_Directive(M) {
  559. return {
  560. type: "ExpressionStatement",
  561. expression: {
  562. type: "Literal",
  563. value: M.value
  564. }
  565. };
  566. });
  567. def_to_moz(AST_SimpleStatement, function To_Moz_ExpressionStatement(M) {
  568. return {
  569. type: "ExpressionStatement",
  570. expression: to_moz(M.body)
  571. };
  572. });
  573. def_to_moz(AST_SwitchBranch, function To_Moz_SwitchCase(M) {
  574. return {
  575. type: "SwitchCase",
  576. test: to_moz(M.expression),
  577. consequent: M.body.map(to_moz)
  578. };
  579. });
  580. def_to_moz(AST_Try, function To_Moz_TryStatement(M) {
  581. return {
  582. type: "TryStatement",
  583. block: to_moz_block(M),
  584. handler: to_moz(M.bcatch),
  585. guardedHandlers: [],
  586. finalizer: to_moz(M.bfinally)
  587. };
  588. });
  589. def_to_moz(AST_Catch, function To_Moz_CatchClause(M) {
  590. return {
  591. type: "CatchClause",
  592. param: to_moz(M.argname),
  593. guard: null,
  594. body: to_moz_block(M)
  595. };
  596. });
  597. def_to_moz(AST_Definitions, function To_Moz_VariableDeclaration(M) {
  598. return {
  599. type: "VariableDeclaration",
  600. kind:
  601. M instanceof AST_Const ? "const" :
  602. M instanceof AST_Let ? "let" : "var",
  603. declarations: M.definitions.map(to_moz)
  604. };
  605. });
  606. def_to_moz(AST_Export, function To_Moz_ExportDeclaration(M) {
  607. if (M.exported_names) {
  608. if (M.exported_names[0].name.name === "*") {
  609. return {
  610. type: "ExportAllDeclaration",
  611. source: to_moz(M.module_name)
  612. };
  613. }
  614. return {
  615. type: "ExportNamedDeclaration",
  616. specifiers: M.exported_names.map(function (name_mapping) {
  617. return {
  618. type: "ExportSpecifier",
  619. exported: to_moz(name_mapping.foreign_name),
  620. local: to_moz(name_mapping.name)
  621. };
  622. }),
  623. declaration: to_moz(M.exported_definition),
  624. source: to_moz(M.module_name)
  625. };
  626. }
  627. return {
  628. type: M.is_default ? "ExportDefaultDeclaration" : "ExportNamedDeclaration",
  629. declaration: to_moz(M.exported_value || M.exported_definition)
  630. };
  631. });
  632. def_to_moz(AST_Import, function To_Moz_ImportDeclaration(M) {
  633. var specifiers = [];
  634. if (M.imported_name) {
  635. specifiers.push({
  636. type: "ImportDefaultSpecifier",
  637. local: to_moz(M.imported_name)
  638. });
  639. }
  640. if (M.imported_names && M.imported_names[0].foreign_name.name === "*") {
  641. specifiers.push({
  642. type: "ImportNamespaceSpecifier",
  643. local: to_moz(M.imported_names[0].name)
  644. });
  645. } else if (M.imported_names) {
  646. M.imported_names.forEach(function(name_mapping) {
  647. specifiers.push({
  648. type: "ImportSpecifier",
  649. local: to_moz(name_mapping.name),
  650. imported: to_moz(name_mapping.foreign_name)
  651. });
  652. });
  653. }
  654. return {
  655. type: "ImportDeclaration",
  656. specifiers: specifiers,
  657. source: to_moz(M.module_name)
  658. };
  659. });
  660. def_to_moz(AST_Sequence, function To_Moz_SequenceExpression(M) {
  661. return {
  662. type: "SequenceExpression",
  663. expressions: M.expressions.map(to_moz)
  664. };
  665. });
  666. def_to_moz(AST_PropAccess, function To_Moz_MemberExpression(M) {
  667. var isComputed = M instanceof AST_Sub;
  668. return {
  669. type: "MemberExpression",
  670. object: to_moz(M.expression),
  671. computed: isComputed,
  672. property: isComputed ? to_moz(M.property) : {type: "Identifier", name: M.property}
  673. };
  674. });
  675. def_to_moz(AST_Unary, function To_Moz_Unary(M) {
  676. return {
  677. type: M.operator == "++" || M.operator == "--" ? "UpdateExpression" : "UnaryExpression",
  678. operator: M.operator,
  679. prefix: M instanceof AST_UnaryPrefix,
  680. argument: to_moz(M.expression)
  681. };
  682. });
  683. def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) {
  684. if (M.operator == "=" && to_moz_in_destructuring()) {
  685. return {
  686. type: "AssignmentPattern",
  687. left: to_moz(M.left),
  688. right: to_moz(M.right)
  689. };
  690. }
  691. return {
  692. type: M.operator == "&&" || M.operator == "||" ? "LogicalExpression" : "BinaryExpression",
  693. left: to_moz(M.left),
  694. operator: M.operator,
  695. right: to_moz(M.right)
  696. };
  697. });
  698. def_to_moz(AST_Array, function To_Moz_ArrayExpression(M) {
  699. return {
  700. type: "ArrayExpression",
  701. elements: M.elements.map(to_moz)
  702. };
  703. });
  704. def_to_moz(AST_Object, function To_Moz_ObjectExpression(M) {
  705. return {
  706. type: "ObjectExpression",
  707. properties: M.properties.map(to_moz)
  708. };
  709. });
  710. def_to_moz(AST_ObjectProperty, function To_Moz_Property(M, parent) {
  711. var key = M.key instanceof AST_Node ? to_moz(M.key) : {
  712. type: "Identifier",
  713. value: M.key
  714. };
  715. if (typeof M.key === "number") {
  716. key = {
  717. type: "Literal",
  718. value: Number(M.key)
  719. };
  720. }
  721. if (typeof M.key === "string") {
  722. key = {
  723. type: "Identifier",
  724. name: M.key
  725. };
  726. }
  727. var kind;
  728. var string_or_num = typeof M.key === "string" || typeof M.key === "number";
  729. var computed = string_or_num ? false : !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef;
  730. if (M instanceof AST_ObjectKeyVal) {
  731. kind = "init";
  732. computed = !string_or_num;
  733. } else
  734. if (M instanceof AST_ObjectGetter) {
  735. kind = "get";
  736. } else
  737. if (M instanceof AST_ObjectSetter) {
  738. kind = "set";
  739. }
  740. if (parent instanceof AST_Class) {
  741. return {
  742. type: "MethodDefinition",
  743. computed: computed,
  744. kind: kind,
  745. static: M.static,
  746. key: to_moz(M.key),
  747. value: to_moz(M.value)
  748. };
  749. }
  750. return {
  751. type: "Property",
  752. computed: computed,
  753. kind: kind,
  754. key: key,
  755. value: to_moz(M.value)
  756. };
  757. });
  758. def_to_moz(AST_ConciseMethod, function To_Moz_MethodDefinition(M, parent) {
  759. if (parent instanceof AST_Object) {
  760. return {
  761. type: "Property",
  762. computed: !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef,
  763. kind: "init",
  764. method: true,
  765. shorthand: false,
  766. key: to_moz(M.key),
  767. value: to_moz(M.value)
  768. };
  769. }
  770. return {
  771. type: "MethodDefinition",
  772. computed: !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef,
  773. kind: M.key === "constructor" ? "constructor" : "method",
  774. static: M.static,
  775. key: to_moz(M.key),
  776. value: to_moz(M.value)
  777. };
  778. });
  779. def_to_moz(AST_Class, function To_Moz_Class(M) {
  780. var type = M instanceof AST_ClassExpression ? "ClassExpression" : "ClassDeclaration";
  781. return {
  782. type: type,
  783. superClass: to_moz(M.extends),
  784. id: M.name ? to_moz(M.name) : null,
  785. body: {
  786. type: "ClassBody",
  787. body: M.properties.map(to_moz)
  788. }
  789. };
  790. });
  791. def_to_moz(AST_NewTarget, function To_Moz_MetaProperty(M) {
  792. return {
  793. type: "MetaProperty",
  794. meta: {
  795. type: "Identifier",
  796. name: "new"
  797. },
  798. property: {
  799. type: "Identifier",
  800. name: "target"
  801. }
  802. };
  803. });
  804. def_to_moz(AST_Symbol, function To_Moz_Identifier(M, parent) {
  805. if (M instanceof AST_SymbolMethod && parent.quote) {
  806. return {
  807. type: "Literal",
  808. value: M.name
  809. };
  810. }
  811. var def = M.definition();
  812. return {
  813. type: "Identifier",
  814. name: def ? def.mangled_name || def.name : M.name
  815. };
  816. });
  817. def_to_moz(AST_RegExp, function To_Moz_RegExpLiteral(M) {
  818. var pattern = M.value.source;
  819. var flags = M.value.toString().match(/[gimuys]*$/)[0];
  820. return {
  821. type: "Literal",
  822. value: new RegExp(pattern, flags),
  823. raw: M.value.raw_source,
  824. regex: {
  825. pattern: pattern,
  826. flags: flags,
  827. }
  828. };
  829. });
  830. def_to_moz(AST_Constant, function To_Moz_Literal(M) {
  831. var value = M.value;
  832. if (typeof value === "number" && (value < 0 || (value === 0 && 1 / value < 0))) {
  833. return {
  834. type: "UnaryExpression",
  835. operator: "-",
  836. prefix: true,
  837. argument: {
  838. type: "Literal",
  839. value: -value,
  840. raw: M.start.raw
  841. }
  842. };
  843. }
  844. return {
  845. type: "Literal",
  846. value: value,
  847. raw: M.start.raw
  848. };
  849. });
  850. def_to_moz(AST_Atom, function To_Moz_Atom(M) {
  851. return {
  852. type: "Identifier",
  853. name: String(M.value)
  854. };
  855. });
  856. AST_Boolean.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast);
  857. AST_Null.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast);
  858. AST_Hole.DEFMETHOD("to_mozilla_ast", function To_Moz_ArrayHole() { return null; });
  859. AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast);
  860. AST_Lambda.DEFMETHOD("to_mozilla_ast", AST_Function.prototype.to_mozilla_ast);
  861. /* -----[ tools ]----- */
  862. function raw_token(moznode) {
  863. if (moznode.type == "Literal") {
  864. return moznode.raw != null ? moznode.raw : moznode.value + "";
  865. }
  866. }
  867. function my_start_token(moznode) {
  868. var loc = moznode.loc, start = loc && loc.start;
  869. var range = moznode.range;
  870. return new AST_Token({
  871. file : loc && loc.source,
  872. line : start && start.line,
  873. col : start && start.column,
  874. pos : range ? range[0] : moznode.start,
  875. endline : start && start.line,
  876. endcol : start && start.column,
  877. endpos : range ? range[0] : moznode.start,
  878. raw : raw_token(moznode),
  879. });
  880. }
  881. function my_end_token(moznode) {
  882. var loc = moznode.loc, end = loc && loc.end;
  883. var range = moznode.range;
  884. return new AST_Token({
  885. file : loc && loc.source,
  886. line : end && end.line,
  887. col : end && end.column,
  888. pos : range ? range[1] : moznode.end,
  889. endline : end && end.line,
  890. endcol : end && end.column,
  891. endpos : range ? range[1] : moznode.end,
  892. raw : raw_token(moznode),
  893. });
  894. }
  895. function map(moztype, mytype, propmap) {
  896. var moz_to_me = "function From_Moz_" + moztype + "(M){\n";
  897. moz_to_me += "return new U2." + mytype.name + "({\n" +
  898. "start: my_start_token(M),\n" +
  899. "end: my_end_token(M)";
  900. var me_to_moz = "function To_Moz_" + moztype + "(M){\n";
  901. me_to_moz += "return {\n" +
  902. "type: " + JSON.stringify(moztype);
  903. if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop) {
  904. var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop);
  905. if (!m) throw new Error("Can't understand property map: " + prop);
  906. var moz = m[1], how = m[2], my = m[3];
  907. moz_to_me += ",\n" + my + ": ";
  908. me_to_moz += ",\n" + moz + ": ";
  909. switch (how) {
  910. case "@":
  911. moz_to_me += "M." + moz + ".map(from_moz)";
  912. me_to_moz += "M." + my + ".map(to_moz)";
  913. break;
  914. case ">":
  915. moz_to_me += "from_moz(M." + moz + ")";
  916. me_to_moz += "to_moz(M." + my + ")";
  917. break;
  918. case "=":
  919. moz_to_me += "M." + moz;
  920. me_to_moz += "M." + my;
  921. break;
  922. case "%":
  923. moz_to_me += "from_moz(M." + moz + ").body";
  924. me_to_moz += "to_moz_block(M)";
  925. break;
  926. default:
  927. throw new Error("Can't understand operator in propmap: " + prop);
  928. }
  929. });
  930. moz_to_me += "\n})\n}";
  931. me_to_moz += "\n}\n}";
  932. //moz_to_me = parse(moz_to_me).print_to_string({ beautify: true });
  933. //me_to_moz = parse(me_to_moz).print_to_string({ beautify: true });
  934. //console.log(moz_to_me);
  935. moz_to_me = new Function("U2", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")(
  936. exports, my_start_token, my_end_token, from_moz
  937. );
  938. me_to_moz = new Function("to_moz", "to_moz_block", "to_moz_scope", "return(" + me_to_moz + ")")(
  939. to_moz, to_moz_block, to_moz_scope
  940. );
  941. MOZ_TO_ME[moztype] = moz_to_me;
  942. def_to_moz(mytype, me_to_moz);
  943. }
  944. var FROM_MOZ_STACK = null;
  945. function from_moz(node) {
  946. FROM_MOZ_STACK.push(node);
  947. var ret = node != null ? MOZ_TO_ME[node.type](node) : null;
  948. FROM_MOZ_STACK.pop();
  949. return ret;
  950. }
  951. AST_Node.from_mozilla_ast = function(node) {
  952. var save_stack = FROM_MOZ_STACK;
  953. FROM_MOZ_STACK = [];
  954. var ast = from_moz(node);
  955. FROM_MOZ_STACK = save_stack;
  956. return ast;
  957. };
  958. function set_moz_loc(mynode, moznode, myparent) {
  959. var start = mynode.start;
  960. var end = mynode.end;
  961. if (start.pos != null && end.endpos != null) {
  962. moznode.range = [start.pos, end.endpos];
  963. }
  964. if (start.line) {
  965. moznode.loc = {
  966. start: {line: start.line, column: start.col},
  967. end: end.endline ? {line: end.endline, column: end.endcol} : null
  968. };
  969. if (start.file) {
  970. moznode.loc.source = start.file;
  971. }
  972. }
  973. return moznode;
  974. }
  975. function def_to_moz(mytype, handler) {
  976. mytype.DEFMETHOD("to_mozilla_ast", function(parent) {
  977. return set_moz_loc(this, handler(this, parent));
  978. });
  979. }
  980. var TO_MOZ_STACK = null;
  981. function to_moz(node) {
  982. if (TO_MOZ_STACK === null) { TO_MOZ_STACK = []; }
  983. TO_MOZ_STACK.push(node);
  984. var ast = node != null ? node.to_mozilla_ast(TO_MOZ_STACK[TO_MOZ_STACK.length - 2]) : null;
  985. TO_MOZ_STACK.pop();
  986. if (TO_MOZ_STACK.length === 0) { TO_MOZ_STACK = null; }
  987. return ast;
  988. }
  989. function to_moz_in_destructuring() {
  990. var i = TO_MOZ_STACK.length;
  991. while (i--) {
  992. if (TO_MOZ_STACK[i] instanceof AST_Destructuring) {
  993. return true;
  994. }
  995. }
  996. return false;
  997. }
  998. function to_moz_block(node) {
  999. return {
  1000. type: "BlockStatement",
  1001. body: node.body.map(to_moz)
  1002. };
  1003. }
  1004. function to_moz_scope(type, node) {
  1005. var body = node.body.map(to_moz);
  1006. if (node.body[0] instanceof AST_SimpleStatement && node.body[0].body instanceof AST_String) {
  1007. body.unshift(to_moz(new AST_EmptyStatement(node.body[0])));
  1008. }
  1009. return {
  1010. type: type,
  1011. body: body
  1012. };
  1013. }
  1014. })();