mozilla-ast.js 44 KB

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