output.js 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387
  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. import {
  35. defaults,
  36. makePredicate,
  37. noop,
  38. regexp_source_fix,
  39. sort_regexp_flags,
  40. return_false,
  41. return_true,
  42. } from "./utils/index.js";
  43. import { first_in_statement, left_is_object } from "./utils/first_in_statement.js";
  44. import {
  45. AST_Array,
  46. AST_Arrow,
  47. AST_Assign,
  48. AST_Await,
  49. AST_BigInt,
  50. AST_Binary,
  51. AST_BlockStatement,
  52. AST_Break,
  53. AST_Call,
  54. AST_Case,
  55. AST_Catch,
  56. AST_Chain,
  57. AST_Class,
  58. AST_ClassExpression,
  59. AST_ClassPrivateProperty,
  60. AST_ClassProperty,
  61. AST_ClassStaticBlock,
  62. AST_ConciseMethod,
  63. AST_PrivateGetter,
  64. AST_PrivateMethod,
  65. AST_SymbolPrivateProperty,
  66. AST_PrivateSetter,
  67. AST_PrivateIn,
  68. AST_Conditional,
  69. AST_Const,
  70. AST_Constant,
  71. AST_Continue,
  72. AST_Debugger,
  73. AST_Default,
  74. AST_DefaultAssign,
  75. AST_Definitions,
  76. AST_Defun,
  77. AST_Destructuring,
  78. AST_Directive,
  79. AST_Do,
  80. AST_Dot,
  81. AST_DotHash,
  82. AST_EmptyStatement,
  83. AST_Exit,
  84. AST_Expansion,
  85. AST_Export,
  86. AST_Finally,
  87. AST_For,
  88. AST_ForIn,
  89. AST_ForOf,
  90. AST_Function,
  91. AST_Hole,
  92. AST_If,
  93. AST_Import,
  94. AST_ImportMeta,
  95. AST_Jump,
  96. AST_LabeledStatement,
  97. AST_Lambda,
  98. AST_Let,
  99. AST_LoopControl,
  100. AST_NameMapping,
  101. AST_New,
  102. AST_NewTarget,
  103. AST_Node,
  104. AST_Number,
  105. AST_Object,
  106. AST_ObjectGetter,
  107. AST_ObjectKeyVal,
  108. AST_ObjectProperty,
  109. AST_ObjectSetter,
  110. AST_PrefixedTemplateString,
  111. AST_PropAccess,
  112. AST_RegExp,
  113. AST_Return,
  114. AST_Scope,
  115. AST_Sequence,
  116. AST_SimpleStatement,
  117. AST_Statement,
  118. AST_StatementWithBody,
  119. AST_String,
  120. AST_Sub,
  121. AST_Super,
  122. AST_Switch,
  123. AST_SwitchBranch,
  124. AST_Symbol,
  125. AST_SymbolClassProperty,
  126. AST_SymbolMethod,
  127. AST_SymbolRef,
  128. AST_TemplateSegment,
  129. AST_TemplateString,
  130. AST_This,
  131. AST_Throw,
  132. AST_Toplevel,
  133. AST_Try,
  134. AST_Unary,
  135. AST_UnaryPostfix,
  136. AST_UnaryPrefix,
  137. AST_Var,
  138. AST_VarDef,
  139. AST_While,
  140. AST_With,
  141. AST_Yield,
  142. TreeWalker,
  143. walk,
  144. walk_abort
  145. } from "./ast.js";
  146. import {
  147. get_full_char_code,
  148. get_full_char,
  149. is_identifier_char,
  150. is_basic_identifier_string,
  151. is_identifier_string,
  152. PRECEDENCE,
  153. ALL_RESERVED_WORDS,
  154. } from "./parse.js";
  155. const EXPECT_DIRECTIVE = /^$|[;{][\s\n]*$/;
  156. const CODE_LINE_BREAK = 10;
  157. const CODE_SPACE = 32;
  158. const r_annotation = /[@#]__(PURE|INLINE|NOINLINE)__/g;
  159. function is_some_comments(comment) {
  160. // multiline comment
  161. return (
  162. (comment.type === "comment2" || comment.type === "comment1")
  163. && /@preserve|@copyright|@lic|@cc_on|^\**!/i.test(comment.value)
  164. );
  165. }
  166. class Rope {
  167. constructor() {
  168. this.committed = "";
  169. this.current = "";
  170. }
  171. append(str) {
  172. this.current += str;
  173. }
  174. insertAt(char, index) {
  175. const { committed, current } = this;
  176. if (index < committed.length) {
  177. this.committed = committed.slice(0, index) + char + committed.slice(index);
  178. } else if (index === committed.length) {
  179. this.committed += char;
  180. } else {
  181. index -= committed.length;
  182. this.committed += current.slice(0, index) + char;
  183. this.current = current.slice(index);
  184. }
  185. }
  186. charAt(index) {
  187. const { committed } = this;
  188. if (index < committed.length) return committed[index];
  189. return this.current[index - committed.length];
  190. }
  191. curLength() {
  192. return this.current.length;
  193. }
  194. length() {
  195. return this.committed.length + this.current.length;
  196. }
  197. toString() {
  198. return this.committed + this.current;
  199. }
  200. }
  201. function OutputStream(options) {
  202. var readonly = !options;
  203. options = defaults(options, {
  204. ascii_only : false,
  205. beautify : false,
  206. braces : false,
  207. comments : "some",
  208. ecma : 5,
  209. ie8 : false,
  210. indent_level : 4,
  211. indent_start : 0,
  212. inline_script : true,
  213. keep_numbers : false,
  214. keep_quoted_props : false,
  215. max_line_len : false,
  216. preamble : null,
  217. preserve_annotations : false,
  218. quote_keys : false,
  219. quote_style : 0,
  220. safari10 : false,
  221. semicolons : true,
  222. shebang : true,
  223. shorthand : undefined,
  224. source_map : null,
  225. webkit : false,
  226. width : 80,
  227. wrap_iife : false,
  228. wrap_func_args : true,
  229. _destroy_ast : false
  230. }, true);
  231. if (options.shorthand === undefined)
  232. options.shorthand = options.ecma > 5;
  233. // Convert comment option to RegExp if necessary and set up comments filter
  234. var comment_filter = return_false; // Default case, throw all comments away
  235. if (options.comments) {
  236. let comments = options.comments;
  237. if (typeof options.comments === "string" && /^\/.*\/[a-zA-Z]*$/.test(options.comments)) {
  238. var regex_pos = options.comments.lastIndexOf("/");
  239. comments = new RegExp(
  240. options.comments.substr(1, regex_pos - 1),
  241. options.comments.substr(regex_pos + 1)
  242. );
  243. }
  244. if (comments instanceof RegExp) {
  245. comment_filter = function(comment) {
  246. return comment.type != "comment5" && comments.test(comment.value);
  247. };
  248. } else if (typeof comments === "function") {
  249. comment_filter = function(comment) {
  250. return comment.type != "comment5" && comments(this, comment);
  251. };
  252. } else if (comments === "some") {
  253. comment_filter = is_some_comments;
  254. } else { // NOTE includes "all" option
  255. comment_filter = return_true;
  256. }
  257. }
  258. var indentation = 0;
  259. var current_col = 0;
  260. var current_line = 1;
  261. var current_pos = 0;
  262. var OUTPUT = new Rope();
  263. let printed_comments = new Set();
  264. var to_utf8 = options.ascii_only ? function(str, identifier = false, regexp = false) {
  265. if (options.ecma >= 2015 && !options.safari10 && !regexp) {
  266. str = str.replace(/[\ud800-\udbff][\udc00-\udfff]/g, function(ch) {
  267. var code = get_full_char_code(ch, 0).toString(16);
  268. return "\\u{" + code + "}";
  269. });
  270. }
  271. return str.replace(/[\u0000-\u001f\u007f-\uffff]/g, function(ch) {
  272. var code = ch.charCodeAt(0).toString(16);
  273. if (code.length <= 2 && !identifier) {
  274. while (code.length < 2) code = "0" + code;
  275. return "\\x" + code;
  276. } else {
  277. while (code.length < 4) code = "0" + code;
  278. return "\\u" + code;
  279. }
  280. });
  281. } : function(str) {
  282. return str.replace(/[\ud800-\udbff][\udc00-\udfff]|([\ud800-\udbff]|[\udc00-\udfff])/g, function(match, lone) {
  283. if (lone) {
  284. return "\\u" + lone.charCodeAt(0).toString(16);
  285. }
  286. return match;
  287. });
  288. };
  289. function make_string(str, quote) {
  290. var dq = 0, sq = 0;
  291. str = str.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g,
  292. function(s, i) {
  293. switch (s) {
  294. case '"': ++dq; return '"';
  295. case "'": ++sq; return "'";
  296. case "\\": return "\\\\";
  297. case "\n": return "\\n";
  298. case "\r": return "\\r";
  299. case "\t": return "\\t";
  300. case "\b": return "\\b";
  301. case "\f": return "\\f";
  302. case "\x0B": return options.ie8 ? "\\x0B" : "\\v";
  303. case "\u2028": return "\\u2028";
  304. case "\u2029": return "\\u2029";
  305. case "\ufeff": return "\\ufeff";
  306. case "\0":
  307. return /[0-9]/.test(get_full_char(str, i+1)) ? "\\x00" : "\\0";
  308. }
  309. return s;
  310. });
  311. function quote_single() {
  312. return "'" + str.replace(/\x27/g, "\\'") + "'";
  313. }
  314. function quote_double() {
  315. return '"' + str.replace(/\x22/g, '\\"') + '"';
  316. }
  317. function quote_template() {
  318. return "`" + str.replace(/`/g, "\\`") + "`";
  319. }
  320. str = to_utf8(str);
  321. if (quote === "`") return quote_template();
  322. switch (options.quote_style) {
  323. case 1:
  324. return quote_single();
  325. case 2:
  326. return quote_double();
  327. case 3:
  328. return quote == "'" ? quote_single() : quote_double();
  329. default:
  330. return dq > sq ? quote_single() : quote_double();
  331. }
  332. }
  333. function encode_string(str, quote) {
  334. var ret = make_string(str, quote);
  335. if (options.inline_script) {
  336. ret = ret.replace(/<\x2f(script)([>\/\t\n\f\r ])/gi, "<\\/$1$2");
  337. ret = ret.replace(/\x3c!--/g, "\\x3c!--");
  338. ret = ret.replace(/--\x3e/g, "--\\x3e");
  339. }
  340. return ret;
  341. }
  342. function make_name(name) {
  343. name = name.toString();
  344. name = to_utf8(name, true);
  345. return name;
  346. }
  347. function make_indent(back) {
  348. return " ".repeat(options.indent_start + indentation - back * options.indent_level);
  349. }
  350. /* -----[ beautification/minification ]----- */
  351. var has_parens = false;
  352. var might_need_space = false;
  353. var might_need_semicolon = false;
  354. var might_add_newline = 0;
  355. var need_newline_indented = false;
  356. var need_space = false;
  357. var newline_insert = -1;
  358. var last = "";
  359. var mapping_token, mapping_name, mappings = options.source_map && [];
  360. var do_add_mapping = mappings ? function() {
  361. mappings.forEach(function(mapping) {
  362. try {
  363. let { name, token } = mapping;
  364. if (token.type == "name" || token.type === "privatename") {
  365. name = token.value;
  366. } else if (name instanceof AST_Symbol) {
  367. name = token.type === "string" ? token.value : name.name;
  368. }
  369. options.source_map.add(
  370. mapping.token.file,
  371. mapping.line, mapping.col,
  372. mapping.token.line, mapping.token.col,
  373. is_basic_identifier_string(name) ? name : undefined
  374. );
  375. } catch(ex) {
  376. // Ignore bad mapping
  377. }
  378. });
  379. mappings = [];
  380. } : noop;
  381. var ensure_line_len = options.max_line_len ? function() {
  382. if (current_col > options.max_line_len) {
  383. if (might_add_newline) {
  384. OUTPUT.insertAt("\n", might_add_newline);
  385. const curLength = OUTPUT.curLength();
  386. if (mappings) {
  387. var delta = curLength - current_col;
  388. mappings.forEach(function(mapping) {
  389. mapping.line++;
  390. mapping.col += delta;
  391. });
  392. }
  393. current_line++;
  394. current_pos++;
  395. current_col = curLength;
  396. }
  397. }
  398. if (might_add_newline) {
  399. might_add_newline = 0;
  400. do_add_mapping();
  401. }
  402. } : noop;
  403. var requireSemicolonChars = makePredicate("( [ + * / - , . `");
  404. function print(str) {
  405. str = String(str);
  406. var ch = get_full_char(str, 0);
  407. if (need_newline_indented && ch) {
  408. need_newline_indented = false;
  409. if (ch !== "\n") {
  410. print("\n");
  411. indent();
  412. }
  413. }
  414. if (need_space && ch) {
  415. need_space = false;
  416. if (!/[\s;})]/.test(ch)) {
  417. space();
  418. }
  419. }
  420. newline_insert = -1;
  421. var prev = last.charAt(last.length - 1);
  422. if (might_need_semicolon) {
  423. might_need_semicolon = false;
  424. if (prev === ":" && ch === "}" || (!ch || !";}".includes(ch)) && prev !== ";") {
  425. if (options.semicolons || requireSemicolonChars.has(ch)) {
  426. OUTPUT.append(";");
  427. current_col++;
  428. current_pos++;
  429. } else {
  430. ensure_line_len();
  431. if (current_col > 0) {
  432. OUTPUT.append("\n");
  433. current_pos++;
  434. current_line++;
  435. current_col = 0;
  436. }
  437. if (/^\s+$/.test(str)) {
  438. // reset the semicolon flag, since we didn't print one
  439. // now and might still have to later
  440. might_need_semicolon = true;
  441. }
  442. }
  443. if (!options.beautify)
  444. might_need_space = false;
  445. }
  446. }
  447. if (might_need_space) {
  448. if ((is_identifier_char(prev)
  449. && (is_identifier_char(ch) || ch == "\\"))
  450. || (ch == "/" && ch == prev)
  451. || ((ch == "+" || ch == "-") && ch == last)
  452. ) {
  453. OUTPUT.append(" ");
  454. current_col++;
  455. current_pos++;
  456. }
  457. might_need_space = false;
  458. }
  459. if (mapping_token) {
  460. mappings.push({
  461. token: mapping_token,
  462. name: mapping_name,
  463. line: current_line,
  464. col: current_col
  465. });
  466. mapping_token = false;
  467. if (!might_add_newline) do_add_mapping();
  468. }
  469. OUTPUT.append(str);
  470. has_parens = str[str.length - 1] == "(";
  471. current_pos += str.length;
  472. var a = str.split(/\r?\n/), n = a.length - 1;
  473. current_line += n;
  474. current_col += a[0].length;
  475. if (n > 0) {
  476. ensure_line_len();
  477. current_col = a[n].length;
  478. }
  479. last = str;
  480. }
  481. var star = function() {
  482. print("*");
  483. };
  484. var space = options.beautify ? function() {
  485. print(" ");
  486. } : function() {
  487. might_need_space = true;
  488. };
  489. var indent = options.beautify ? function(half) {
  490. if (options.beautify) {
  491. print(make_indent(half ? 0.5 : 0));
  492. }
  493. } : noop;
  494. var with_indent = options.beautify ? function(col, cont) {
  495. if (col === true) col = next_indent();
  496. var save_indentation = indentation;
  497. indentation = col;
  498. var ret = cont();
  499. indentation = save_indentation;
  500. return ret;
  501. } : function(col, cont) { return cont(); };
  502. var newline = options.beautify ? function() {
  503. if (newline_insert < 0) return print("\n");
  504. if (OUTPUT.charAt(newline_insert) != "\n") {
  505. OUTPUT.insertAt("\n", newline_insert);
  506. current_pos++;
  507. current_line++;
  508. }
  509. newline_insert++;
  510. } : options.max_line_len ? function() {
  511. ensure_line_len();
  512. might_add_newline = OUTPUT.length();
  513. } : noop;
  514. var semicolon = options.beautify ? function() {
  515. print(";");
  516. } : function() {
  517. might_need_semicolon = true;
  518. };
  519. function force_semicolon() {
  520. might_need_semicolon = false;
  521. print(";");
  522. }
  523. function next_indent() {
  524. return indentation + options.indent_level;
  525. }
  526. function with_block(cont) {
  527. var ret;
  528. print("{");
  529. newline();
  530. with_indent(next_indent(), function() {
  531. ret = cont();
  532. });
  533. indent();
  534. print("}");
  535. return ret;
  536. }
  537. function with_parens(cont) {
  538. print("(");
  539. //XXX: still nice to have that for argument lists
  540. //var ret = with_indent(current_col, cont);
  541. var ret = cont();
  542. print(")");
  543. return ret;
  544. }
  545. function with_square(cont) {
  546. print("[");
  547. //var ret = with_indent(current_col, cont);
  548. var ret = cont();
  549. print("]");
  550. return ret;
  551. }
  552. function comma() {
  553. print(",");
  554. space();
  555. }
  556. function colon() {
  557. print(":");
  558. space();
  559. }
  560. var add_mapping = mappings ? function(token, name) {
  561. mapping_token = token;
  562. mapping_name = name;
  563. } : noop;
  564. function get() {
  565. if (might_add_newline) {
  566. ensure_line_len();
  567. }
  568. return OUTPUT.toString();
  569. }
  570. function has_nlb() {
  571. const output = OUTPUT.toString();
  572. let n = output.length - 1;
  573. while (n >= 0) {
  574. const code = output.charCodeAt(n);
  575. if (code === CODE_LINE_BREAK) {
  576. return true;
  577. }
  578. if (code !== CODE_SPACE) {
  579. return false;
  580. }
  581. n--;
  582. }
  583. return true;
  584. }
  585. function filter_comment(comment) {
  586. if (!options.preserve_annotations) {
  587. comment = comment.replace(r_annotation, " ");
  588. }
  589. if (/^\s*$/.test(comment)) {
  590. return "";
  591. }
  592. return comment.replace(/(<\s*\/\s*)(script)/i, "<\\/$2");
  593. }
  594. function prepend_comments(node) {
  595. var self = this;
  596. var start = node.start;
  597. if (!start) return;
  598. var printed_comments = self.printed_comments;
  599. // There cannot be a newline between return and its value.
  600. const return_with_value = node instanceof AST_Exit && node.value;
  601. if (
  602. start.comments_before
  603. && printed_comments.has(start.comments_before)
  604. ) {
  605. if (return_with_value) {
  606. start.comments_before = [];
  607. } else {
  608. return;
  609. }
  610. }
  611. var comments = start.comments_before;
  612. if (!comments) {
  613. comments = start.comments_before = [];
  614. }
  615. printed_comments.add(comments);
  616. if (return_with_value) {
  617. var tw = new TreeWalker(function(node) {
  618. var parent = tw.parent();
  619. if (parent instanceof AST_Exit
  620. || parent instanceof AST_Binary && parent.left === node
  621. || parent.TYPE == "Call" && parent.expression === node
  622. || parent instanceof AST_Conditional && parent.condition === node
  623. || parent instanceof AST_Dot && parent.expression === node
  624. || parent instanceof AST_Sequence && parent.expressions[0] === node
  625. || parent instanceof AST_Sub && parent.expression === node
  626. || parent instanceof AST_UnaryPostfix) {
  627. if (!node.start) return;
  628. var text = node.start.comments_before;
  629. if (text && !printed_comments.has(text)) {
  630. printed_comments.add(text);
  631. comments = comments.concat(text);
  632. }
  633. } else {
  634. return true;
  635. }
  636. });
  637. tw.push(node);
  638. node.value.walk(tw);
  639. }
  640. if (current_pos == 0) {
  641. if (comments.length > 0 && options.shebang && comments[0].type === "comment5"
  642. && !printed_comments.has(comments[0])) {
  643. print("#!" + comments.shift().value + "\n");
  644. indent();
  645. }
  646. var preamble = options.preamble;
  647. if (preamble) {
  648. print(preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n"));
  649. }
  650. }
  651. comments = comments.filter(comment_filter, node).filter(c => !printed_comments.has(c));
  652. if (comments.length == 0) return;
  653. var last_nlb = has_nlb();
  654. comments.forEach(function(c, i) {
  655. printed_comments.add(c);
  656. if (!last_nlb) {
  657. if (c.nlb) {
  658. print("\n");
  659. indent();
  660. last_nlb = true;
  661. } else if (i > 0) {
  662. space();
  663. }
  664. }
  665. if (/comment[134]/.test(c.type)) {
  666. var value = filter_comment(c.value);
  667. if (value) {
  668. print("//" + value + "\n");
  669. indent();
  670. }
  671. last_nlb = true;
  672. } else if (c.type == "comment2") {
  673. var value = filter_comment(c.value);
  674. if (value) {
  675. print("/*" + value + "*/");
  676. }
  677. last_nlb = false;
  678. }
  679. });
  680. if (!last_nlb) {
  681. if (start.nlb) {
  682. print("\n");
  683. indent();
  684. } else {
  685. space();
  686. }
  687. }
  688. }
  689. function append_comments(node, tail) {
  690. var self = this;
  691. var token = node.end;
  692. if (!token) return;
  693. var printed_comments = self.printed_comments;
  694. var comments = token[tail ? "comments_before" : "comments_after"];
  695. if (!comments || printed_comments.has(comments)) return;
  696. if (!(node instanceof AST_Statement || comments.every((c) =>
  697. !/comment[134]/.test(c.type)
  698. ))) return;
  699. printed_comments.add(comments);
  700. var insert = OUTPUT.length();
  701. comments.filter(comment_filter, node).forEach(function(c, i) {
  702. if (printed_comments.has(c)) return;
  703. printed_comments.add(c);
  704. need_space = false;
  705. if (need_newline_indented) {
  706. print("\n");
  707. indent();
  708. need_newline_indented = false;
  709. } else if (c.nlb && (i > 0 || !has_nlb())) {
  710. print("\n");
  711. indent();
  712. } else if (i > 0 || !tail) {
  713. space();
  714. }
  715. if (/comment[134]/.test(c.type)) {
  716. const value = filter_comment(c.value);
  717. if (value) {
  718. print("//" + value);
  719. }
  720. need_newline_indented = true;
  721. } else if (c.type == "comment2") {
  722. const value = filter_comment(c.value);
  723. if (value) {
  724. print("/*" + value + "*/");
  725. }
  726. need_space = true;
  727. }
  728. });
  729. if (OUTPUT.length() > insert) newline_insert = insert;
  730. }
  731. /**
  732. * When output.option("_destroy_ast") is enabled, destroy the function.
  733. * Call this after printing it.
  734. */
  735. const gc_scope =
  736. options["_destroy_ast"]
  737. ? function gc_scope(scope) {
  738. scope.body.length = 0;
  739. scope.argnames.length = 0;
  740. }
  741. : noop;
  742. var stack = [];
  743. return {
  744. get : get,
  745. toString : get,
  746. indent : indent,
  747. in_directive : false,
  748. use_asm : null,
  749. active_scope : null,
  750. indentation : function() { return indentation; },
  751. current_width : function() { return current_col - indentation; },
  752. should_break : function() { return options.width && this.current_width() >= options.width; },
  753. has_parens : function() { return has_parens; },
  754. newline : newline,
  755. print : print,
  756. star : star,
  757. space : space,
  758. comma : comma,
  759. colon : colon,
  760. last : function() { return last; },
  761. semicolon : semicolon,
  762. force_semicolon : force_semicolon,
  763. to_utf8 : to_utf8,
  764. print_name : function(name) { print(make_name(name)); },
  765. print_string : function(str, quote, escape_directive) {
  766. var encoded = encode_string(str, quote);
  767. if (escape_directive === true && !encoded.includes("\\")) {
  768. // Insert semicolons to break directive prologue
  769. if (!EXPECT_DIRECTIVE.test(OUTPUT.toString())) {
  770. force_semicolon();
  771. }
  772. force_semicolon();
  773. }
  774. print(encoded);
  775. },
  776. print_template_string_chars: function(str) {
  777. var encoded = encode_string(str, "`").replace(/\${/g, "\\${");
  778. return print(encoded.substr(1, encoded.length - 2));
  779. },
  780. encode_string : encode_string,
  781. next_indent : next_indent,
  782. with_indent : with_indent,
  783. with_block : with_block,
  784. with_parens : with_parens,
  785. with_square : with_square,
  786. add_mapping : add_mapping,
  787. option : function(opt) { return options[opt]; },
  788. gc_scope,
  789. printed_comments: printed_comments,
  790. prepend_comments: readonly ? noop : prepend_comments,
  791. append_comments : readonly || comment_filter === return_false ? noop : append_comments,
  792. line : function() { return current_line; },
  793. col : function() { return current_col; },
  794. pos : function() { return current_pos; },
  795. push_node : function(node) { stack.push(node); },
  796. pop_node : function() { return stack.pop(); },
  797. parent : function(n) {
  798. return stack[stack.length - 2 - (n || 0)];
  799. }
  800. };
  801. }
  802. /* -----[ code generators ]----- */
  803. (function() {
  804. /* -----[ utils ]----- */
  805. function DEFPRINT(nodetype, generator) {
  806. nodetype.DEFMETHOD("_codegen", generator);
  807. }
  808. AST_Node.DEFMETHOD("print", function(output, force_parens) {
  809. var self = this, generator = self._codegen;
  810. if (self instanceof AST_Scope) {
  811. output.active_scope = self;
  812. } else if (!output.use_asm && self instanceof AST_Directive && self.value == "use asm") {
  813. output.use_asm = output.active_scope;
  814. }
  815. function doit() {
  816. output.prepend_comments(self);
  817. self.add_source_map(output);
  818. generator(self, output);
  819. output.append_comments(self);
  820. }
  821. output.push_node(self);
  822. if (force_parens || self.needs_parens(output)) {
  823. output.with_parens(doit);
  824. } else {
  825. doit();
  826. }
  827. output.pop_node();
  828. if (self === output.use_asm) {
  829. output.use_asm = null;
  830. }
  831. });
  832. AST_Node.DEFMETHOD("_print", AST_Node.prototype.print);
  833. AST_Node.DEFMETHOD("print_to_string", function(options) {
  834. var output = OutputStream(options);
  835. this.print(output);
  836. return output.get();
  837. });
  838. /* -----[ PARENTHESES ]----- */
  839. function PARENS(nodetype, func) {
  840. if (Array.isArray(nodetype)) {
  841. nodetype.forEach(function(nodetype) {
  842. PARENS(nodetype, func);
  843. });
  844. } else {
  845. nodetype.DEFMETHOD("needs_parens", func);
  846. }
  847. }
  848. PARENS(AST_Node, return_false);
  849. // a function expression needs parens around it when it's provably
  850. // the first token to appear in a statement.
  851. PARENS(AST_Function, function(output) {
  852. if (!output.has_parens() && first_in_statement(output)) {
  853. return true;
  854. }
  855. if (output.option("webkit")) {
  856. var p = output.parent();
  857. if (p instanceof AST_PropAccess && p.expression === this) {
  858. return true;
  859. }
  860. }
  861. if (output.option("wrap_iife")) {
  862. var p = output.parent();
  863. if (p instanceof AST_Call && p.expression === this) {
  864. return true;
  865. }
  866. }
  867. if (output.option("wrap_func_args")) {
  868. var p = output.parent();
  869. if (p instanceof AST_Call && p.args.includes(this)) {
  870. return true;
  871. }
  872. }
  873. return false;
  874. });
  875. PARENS(AST_Arrow, function(output) {
  876. var p = output.parent();
  877. if (
  878. output.option("wrap_func_args")
  879. && p instanceof AST_Call
  880. && p.args.includes(this)
  881. ) {
  882. return true;
  883. }
  884. return p instanceof AST_PropAccess && p.expression === this;
  885. });
  886. // same goes for an object literal (as in AST_Function), because
  887. // otherwise {...} would be interpreted as a block of code.
  888. PARENS(AST_Object, function(output) {
  889. return !output.has_parens() && first_in_statement(output);
  890. });
  891. PARENS(AST_ClassExpression, first_in_statement);
  892. PARENS(AST_Unary, function(output) {
  893. var p = output.parent();
  894. return p instanceof AST_PropAccess && p.expression === this
  895. || p instanceof AST_Call && p.expression === this
  896. || p instanceof AST_Binary
  897. && p.operator === "**"
  898. && this instanceof AST_UnaryPrefix
  899. && p.left === this
  900. && this.operator !== "++"
  901. && this.operator !== "--";
  902. });
  903. PARENS(AST_Await, function(output) {
  904. var p = output.parent();
  905. return p instanceof AST_PropAccess && p.expression === this
  906. || p instanceof AST_Call && p.expression === this
  907. || p instanceof AST_Binary && p.operator === "**" && p.left === this
  908. || output.option("safari10") && p instanceof AST_UnaryPrefix;
  909. });
  910. PARENS(AST_Sequence, function(output) {
  911. var p = output.parent();
  912. return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4)
  913. || p instanceof AST_Unary // !(foo, bar, baz)
  914. || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8
  915. || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4
  916. || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2
  917. || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ]
  918. || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2
  919. || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30)
  920. * ==> 20 (side effect, set a := 10 and b := 20) */
  921. || p instanceof AST_Arrow // x => (x, x)
  922. || p instanceof AST_DefaultAssign // x => (x = (0, function(){}))
  923. || p instanceof AST_Expansion // [...(a, b)]
  924. || p instanceof AST_ForOf && this === p.object // for (e of (foo, bar)) {}
  925. || p instanceof AST_Yield // yield (foo, bar)
  926. || p instanceof AST_Export // export default (foo, bar)
  927. ;
  928. });
  929. PARENS(AST_Binary, function(output) {
  930. var p = output.parent();
  931. // (foo && bar)()
  932. if (p instanceof AST_Call && p.expression === this)
  933. return true;
  934. // typeof (foo && bar)
  935. if (p instanceof AST_Unary)
  936. return true;
  937. // (foo && bar)["prop"], (foo && bar).prop
  938. if (p instanceof AST_PropAccess && p.expression === this)
  939. return true;
  940. // this deals with precedence: 3 * (2 + 1)
  941. if (p instanceof AST_Binary) {
  942. const po = p.operator;
  943. const so = this.operator;
  944. if (so === "??" && (po === "||" || po === "&&")) {
  945. return true;
  946. }
  947. if (po === "??" && (so === "||" || so === "&&")) {
  948. return true;
  949. }
  950. const pp = PRECEDENCE[po];
  951. const sp = PRECEDENCE[so];
  952. if (pp > sp
  953. || (pp == sp
  954. && (this === p.right || po == "**"))) {
  955. return true;
  956. }
  957. }
  958. });
  959. PARENS(AST_Yield, function(output) {
  960. var p = output.parent();
  961. // (yield 1) + (yield 2)
  962. // a = yield 3
  963. if (p instanceof AST_Binary && p.operator !== "=")
  964. return true;
  965. // (yield 1)()
  966. // new (yield 1)()
  967. if (p instanceof AST_Call && p.expression === this)
  968. return true;
  969. // (yield 1) ? yield 2 : yield 3
  970. if (p instanceof AST_Conditional && p.condition === this)
  971. return true;
  972. // -(yield 4)
  973. if (p instanceof AST_Unary)
  974. return true;
  975. // (yield x).foo
  976. // (yield x)['foo']
  977. if (p instanceof AST_PropAccess && p.expression === this)
  978. return true;
  979. });
  980. PARENS(AST_PropAccess, function(output) {
  981. var p = output.parent();
  982. if (p instanceof AST_New && p.expression === this) {
  983. // i.e. new (foo.bar().baz)
  984. //
  985. // if there's one call into this subtree, then we need
  986. // parens around it too, otherwise the call will be
  987. // interpreted as passing the arguments to the upper New
  988. // expression.
  989. return walk(this, node => {
  990. if (node instanceof AST_Scope) return true;
  991. if (node instanceof AST_Call) {
  992. return walk_abort; // makes walk() return true.
  993. }
  994. });
  995. }
  996. });
  997. PARENS(AST_Call, function(output) {
  998. var p = output.parent(), p1;
  999. if (p instanceof AST_New && p.expression === this
  1000. || p instanceof AST_Export && p.is_default && this.expression instanceof AST_Function)
  1001. return true;
  1002. // workaround for Safari bug.
  1003. // https://bugs.webkit.org/show_bug.cgi?id=123506
  1004. return this.expression instanceof AST_Function
  1005. && p instanceof AST_PropAccess
  1006. && p.expression === this
  1007. && (p1 = output.parent(1)) instanceof AST_Assign
  1008. && p1.left === p;
  1009. });
  1010. PARENS(AST_New, function(output) {
  1011. var p = output.parent();
  1012. if (this.args.length === 0
  1013. && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]()
  1014. || p instanceof AST_Call && p.expression === this
  1015. || p instanceof AST_PrefixedTemplateString && p.prefix === this)) // (new foo)(bar)
  1016. return true;
  1017. });
  1018. PARENS(AST_Number, function(output) {
  1019. var p = output.parent();
  1020. if (p instanceof AST_PropAccess && p.expression === this) {
  1021. var value = this.getValue();
  1022. if (value < 0 || /^0/.test(make_num(value))) {
  1023. return true;
  1024. }
  1025. }
  1026. });
  1027. PARENS(AST_BigInt, function(output) {
  1028. var p = output.parent();
  1029. if (p instanceof AST_PropAccess && p.expression === this) {
  1030. var value = this.getValue();
  1031. if (value.startsWith("-")) {
  1032. return true;
  1033. }
  1034. }
  1035. });
  1036. PARENS([ AST_Assign, AST_Conditional ], function(output) {
  1037. var p = output.parent();
  1038. // !(a = false) → true
  1039. if (p instanceof AST_Unary)
  1040. return true;
  1041. // 1 + (a = 2) + 3 → 6, side effect setting a = 2
  1042. if (p instanceof AST_Binary && !(p instanceof AST_Assign))
  1043. return true;
  1044. // (a = func)() —or— new (a = Object)()
  1045. if (p instanceof AST_Call && p.expression === this)
  1046. return true;
  1047. // (a = foo) ? bar : baz
  1048. if (p instanceof AST_Conditional && p.condition === this)
  1049. return true;
  1050. // (a = foo)["prop"] —or— (a = foo).prop
  1051. if (p instanceof AST_PropAccess && p.expression === this)
  1052. return true;
  1053. // ({a, b} = {a: 1, b: 2}), a destructuring assignment
  1054. if (this instanceof AST_Assign && this.left instanceof AST_Destructuring && this.left.is_array === false)
  1055. return true;
  1056. });
  1057. /* -----[ PRINTERS ]----- */
  1058. DEFPRINT(AST_Directive, function(self, output) {
  1059. output.print_string(self.value, self.quote);
  1060. output.semicolon();
  1061. });
  1062. DEFPRINT(AST_Expansion, function (self, output) {
  1063. output.print("...");
  1064. self.expression.print(output);
  1065. });
  1066. DEFPRINT(AST_Destructuring, function (self, output) {
  1067. output.print(self.is_array ? "[" : "{");
  1068. var len = self.names.length;
  1069. self.names.forEach(function (name, i) {
  1070. if (i > 0) output.comma();
  1071. name.print(output);
  1072. // If the final element is a hole, we need to make sure it
  1073. // doesn't look like a trailing comma, by inserting an actual
  1074. // trailing comma.
  1075. if (i == len - 1 && name instanceof AST_Hole) output.comma();
  1076. });
  1077. output.print(self.is_array ? "]" : "}");
  1078. });
  1079. DEFPRINT(AST_Debugger, function(self, output) {
  1080. output.print("debugger");
  1081. output.semicolon();
  1082. });
  1083. /* -----[ statements ]----- */
  1084. function display_body(body, is_toplevel, output, allow_directives) {
  1085. var last = body.length - 1;
  1086. output.in_directive = allow_directives;
  1087. body.forEach(function(stmt, i) {
  1088. if (output.in_directive === true && !(stmt instanceof AST_Directive ||
  1089. stmt instanceof AST_EmptyStatement ||
  1090. (stmt instanceof AST_SimpleStatement && stmt.body instanceof AST_String)
  1091. )) {
  1092. output.in_directive = false;
  1093. }
  1094. if (!(stmt instanceof AST_EmptyStatement)) {
  1095. output.indent();
  1096. stmt.print(output);
  1097. if (!(i == last && is_toplevel)) {
  1098. output.newline();
  1099. if (is_toplevel) output.newline();
  1100. }
  1101. }
  1102. if (output.in_directive === true &&
  1103. stmt instanceof AST_SimpleStatement &&
  1104. stmt.body instanceof AST_String
  1105. ) {
  1106. output.in_directive = false;
  1107. }
  1108. });
  1109. output.in_directive = false;
  1110. }
  1111. AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output) {
  1112. force_statement(this.body, output);
  1113. });
  1114. DEFPRINT(AST_Statement, function(self, output) {
  1115. self.body.print(output);
  1116. output.semicolon();
  1117. });
  1118. DEFPRINT(AST_Toplevel, function(self, output) {
  1119. display_body(self.body, true, output, true);
  1120. output.print("");
  1121. });
  1122. DEFPRINT(AST_LabeledStatement, function(self, output) {
  1123. self.label.print(output);
  1124. output.colon();
  1125. self.body.print(output);
  1126. });
  1127. DEFPRINT(AST_SimpleStatement, function(self, output) {
  1128. self.body.print(output);
  1129. output.semicolon();
  1130. });
  1131. function print_braced_empty(self, output) {
  1132. output.print("{");
  1133. output.with_indent(output.next_indent(), function() {
  1134. output.append_comments(self, true);
  1135. });
  1136. output.add_mapping(self.end);
  1137. output.print("}");
  1138. }
  1139. function print_braced(self, output, allow_directives) {
  1140. if (self.body.length > 0) {
  1141. output.with_block(function() {
  1142. display_body(self.body, false, output, allow_directives);
  1143. output.add_mapping(self.end);
  1144. });
  1145. } else print_braced_empty(self, output);
  1146. }
  1147. DEFPRINT(AST_BlockStatement, function(self, output) {
  1148. print_braced(self, output);
  1149. });
  1150. DEFPRINT(AST_EmptyStatement, function(self, output) {
  1151. output.semicolon();
  1152. });
  1153. DEFPRINT(AST_Do, function(self, output) {
  1154. output.print("do");
  1155. output.space();
  1156. make_block(self.body, output);
  1157. output.space();
  1158. output.print("while");
  1159. output.space();
  1160. output.with_parens(function() {
  1161. self.condition.print(output);
  1162. });
  1163. output.semicolon();
  1164. });
  1165. DEFPRINT(AST_While, function(self, output) {
  1166. output.print("while");
  1167. output.space();
  1168. output.with_parens(function() {
  1169. self.condition.print(output);
  1170. });
  1171. output.space();
  1172. self._do_print_body(output);
  1173. });
  1174. DEFPRINT(AST_For, function(self, output) {
  1175. output.print("for");
  1176. output.space();
  1177. output.with_parens(function() {
  1178. if (self.init) {
  1179. if (self.init instanceof AST_Definitions) {
  1180. self.init.print(output);
  1181. } else {
  1182. parenthesize_for_noin(self.init, output, true);
  1183. }
  1184. output.print(";");
  1185. output.space();
  1186. } else {
  1187. output.print(";");
  1188. }
  1189. if (self.condition) {
  1190. self.condition.print(output);
  1191. output.print(";");
  1192. output.space();
  1193. } else {
  1194. output.print(";");
  1195. }
  1196. if (self.step) {
  1197. self.step.print(output);
  1198. }
  1199. });
  1200. output.space();
  1201. self._do_print_body(output);
  1202. });
  1203. DEFPRINT(AST_ForIn, function(self, output) {
  1204. output.print("for");
  1205. if (self.await) {
  1206. output.space();
  1207. output.print("await");
  1208. }
  1209. output.space();
  1210. output.with_parens(function() {
  1211. self.init.print(output);
  1212. output.space();
  1213. output.print(self instanceof AST_ForOf ? "of" : "in");
  1214. output.space();
  1215. self.object.print(output);
  1216. });
  1217. output.space();
  1218. self._do_print_body(output);
  1219. });
  1220. DEFPRINT(AST_With, function(self, output) {
  1221. output.print("with");
  1222. output.space();
  1223. output.with_parens(function() {
  1224. self.expression.print(output);
  1225. });
  1226. output.space();
  1227. self._do_print_body(output);
  1228. });
  1229. /* -----[ functions ]----- */
  1230. AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword) {
  1231. var self = this;
  1232. if (!nokeyword) {
  1233. if (self.async) {
  1234. output.print("async");
  1235. output.space();
  1236. }
  1237. output.print("function");
  1238. if (self.is_generator) {
  1239. output.star();
  1240. }
  1241. if (self.name) {
  1242. output.space();
  1243. }
  1244. }
  1245. if (self.name instanceof AST_Symbol) {
  1246. self.name.print(output);
  1247. } else if (nokeyword && self.name instanceof AST_Node) {
  1248. output.with_square(function() {
  1249. self.name.print(output); // Computed method name
  1250. });
  1251. }
  1252. output.with_parens(function() {
  1253. self.argnames.forEach(function(arg, i) {
  1254. if (i) output.comma();
  1255. arg.print(output);
  1256. });
  1257. });
  1258. output.space();
  1259. print_braced(self, output, true);
  1260. });
  1261. DEFPRINT(AST_Lambda, function(self, output) {
  1262. self._do_print(output);
  1263. output.gc_scope(self);
  1264. });
  1265. DEFPRINT(AST_PrefixedTemplateString, function(self, output) {
  1266. var tag = self.prefix;
  1267. var parenthesize_tag = tag instanceof AST_Lambda
  1268. || tag instanceof AST_Binary
  1269. || tag instanceof AST_Conditional
  1270. || tag instanceof AST_Sequence
  1271. || tag instanceof AST_Unary
  1272. || tag instanceof AST_Dot && tag.expression instanceof AST_Object;
  1273. if (parenthesize_tag) output.print("(");
  1274. self.prefix.print(output);
  1275. if (parenthesize_tag) output.print(")");
  1276. self.template_string.print(output);
  1277. });
  1278. DEFPRINT(AST_TemplateString, function(self, output) {
  1279. var is_tagged = output.parent() instanceof AST_PrefixedTemplateString;
  1280. output.print("`");
  1281. for (var i = 0; i < self.segments.length; i++) {
  1282. if (!(self.segments[i] instanceof AST_TemplateSegment)) {
  1283. output.print("${");
  1284. self.segments[i].print(output);
  1285. output.print("}");
  1286. } else if (is_tagged) {
  1287. output.print(self.segments[i].raw);
  1288. } else {
  1289. output.print_template_string_chars(self.segments[i].value);
  1290. }
  1291. }
  1292. output.print("`");
  1293. });
  1294. DEFPRINT(AST_TemplateSegment, function(self, output) {
  1295. output.print_template_string_chars(self.value);
  1296. });
  1297. AST_Arrow.DEFMETHOD("_do_print", function(output) {
  1298. var self = this;
  1299. var parent = output.parent();
  1300. var needs_parens = (parent instanceof AST_Binary && !(parent instanceof AST_Assign)) ||
  1301. parent instanceof AST_Unary ||
  1302. (parent instanceof AST_Call && self === parent.expression);
  1303. if (needs_parens) { output.print("("); }
  1304. if (self.async) {
  1305. output.print("async");
  1306. output.space();
  1307. }
  1308. if (self.argnames.length === 1 && self.argnames[0] instanceof AST_Symbol) {
  1309. self.argnames[0].print(output);
  1310. } else {
  1311. output.with_parens(function() {
  1312. self.argnames.forEach(function(arg, i) {
  1313. if (i) output.comma();
  1314. arg.print(output);
  1315. });
  1316. });
  1317. }
  1318. output.space();
  1319. output.print("=>");
  1320. output.space();
  1321. const first_statement = self.body[0];
  1322. if (
  1323. self.body.length === 1
  1324. && first_statement instanceof AST_Return
  1325. ) {
  1326. const returned = first_statement.value;
  1327. if (!returned) {
  1328. output.print("{}");
  1329. } else if (left_is_object(returned)) {
  1330. output.print("(");
  1331. returned.print(output);
  1332. output.print(")");
  1333. } else {
  1334. returned.print(output);
  1335. }
  1336. } else {
  1337. print_braced(self, output);
  1338. }
  1339. if (needs_parens) { output.print(")"); }
  1340. output.gc_scope(self);
  1341. });
  1342. /* -----[ exits ]----- */
  1343. AST_Exit.DEFMETHOD("_do_print", function(output, kind) {
  1344. output.print(kind);
  1345. if (this.value) {
  1346. output.space();
  1347. const comments = this.value.start.comments_before;
  1348. if (comments && comments.length && !output.printed_comments.has(comments)) {
  1349. output.print("(");
  1350. this.value.print(output);
  1351. output.print(")");
  1352. } else {
  1353. this.value.print(output);
  1354. }
  1355. }
  1356. output.semicolon();
  1357. });
  1358. DEFPRINT(AST_Return, function(self, output) {
  1359. self._do_print(output, "return");
  1360. });
  1361. DEFPRINT(AST_Throw, function(self, output) {
  1362. self._do_print(output, "throw");
  1363. });
  1364. /* -----[ yield ]----- */
  1365. DEFPRINT(AST_Yield, function(self, output) {
  1366. var star = self.is_star ? "*" : "";
  1367. output.print("yield" + star);
  1368. if (self.expression) {
  1369. output.space();
  1370. self.expression.print(output);
  1371. }
  1372. });
  1373. DEFPRINT(AST_Await, function(self, output) {
  1374. output.print("await");
  1375. output.space();
  1376. var e = self.expression;
  1377. var parens = !(
  1378. e instanceof AST_Call
  1379. || e instanceof AST_SymbolRef
  1380. || e instanceof AST_PropAccess
  1381. || e instanceof AST_Unary
  1382. || e instanceof AST_Constant
  1383. || e instanceof AST_Await
  1384. || e instanceof AST_Object
  1385. );
  1386. if (parens) output.print("(");
  1387. self.expression.print(output);
  1388. if (parens) output.print(")");
  1389. });
  1390. /* -----[ loop control ]----- */
  1391. AST_LoopControl.DEFMETHOD("_do_print", function(output, kind) {
  1392. output.print(kind);
  1393. if (this.label) {
  1394. output.space();
  1395. this.label.print(output);
  1396. }
  1397. output.semicolon();
  1398. });
  1399. DEFPRINT(AST_Break, function(self, output) {
  1400. self._do_print(output, "break");
  1401. });
  1402. DEFPRINT(AST_Continue, function(self, output) {
  1403. self._do_print(output, "continue");
  1404. });
  1405. /* -----[ if ]----- */
  1406. function make_then(self, output) {
  1407. var b = self.body;
  1408. if (output.option("braces")
  1409. || output.option("ie8") && b instanceof AST_Do)
  1410. return make_block(b, output);
  1411. // The squeezer replaces "block"-s that contain only a single
  1412. // statement with the statement itself; technically, the AST
  1413. // is correct, but this can create problems when we output an
  1414. // IF having an ELSE clause where the THEN clause ends in an
  1415. // IF *without* an ELSE block (then the outer ELSE would refer
  1416. // to the inner IF). This function checks for this case and
  1417. // adds the block braces if needed.
  1418. if (!b) return output.force_semicolon();
  1419. while (true) {
  1420. if (b instanceof AST_If) {
  1421. if (!b.alternative) {
  1422. make_block(self.body, output);
  1423. return;
  1424. }
  1425. b = b.alternative;
  1426. } else if (b instanceof AST_StatementWithBody) {
  1427. b = b.body;
  1428. } else break;
  1429. }
  1430. force_statement(self.body, output);
  1431. }
  1432. DEFPRINT(AST_If, function(self, output) {
  1433. output.print("if");
  1434. output.space();
  1435. output.with_parens(function() {
  1436. self.condition.print(output);
  1437. });
  1438. output.space();
  1439. if (self.alternative) {
  1440. make_then(self, output);
  1441. output.space();
  1442. output.print("else");
  1443. output.space();
  1444. if (self.alternative instanceof AST_If)
  1445. self.alternative.print(output);
  1446. else
  1447. force_statement(self.alternative, output);
  1448. } else {
  1449. self._do_print_body(output);
  1450. }
  1451. });
  1452. /* -----[ switch ]----- */
  1453. DEFPRINT(AST_Switch, function(self, output) {
  1454. output.print("switch");
  1455. output.space();
  1456. output.with_parens(function() {
  1457. self.expression.print(output);
  1458. });
  1459. output.space();
  1460. var last = self.body.length - 1;
  1461. if (last < 0) print_braced_empty(self, output);
  1462. else output.with_block(function() {
  1463. self.body.forEach(function(branch, i) {
  1464. output.indent(true);
  1465. branch.print(output);
  1466. if (i < last && branch.body.length > 0)
  1467. output.newline();
  1468. });
  1469. });
  1470. });
  1471. AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output) {
  1472. output.newline();
  1473. this.body.forEach(function(stmt) {
  1474. output.indent();
  1475. stmt.print(output);
  1476. output.newline();
  1477. });
  1478. });
  1479. DEFPRINT(AST_Default, function(self, output) {
  1480. output.print("default:");
  1481. self._do_print_body(output);
  1482. });
  1483. DEFPRINT(AST_Case, function(self, output) {
  1484. output.print("case");
  1485. output.space();
  1486. self.expression.print(output);
  1487. output.print(":");
  1488. self._do_print_body(output);
  1489. });
  1490. /* -----[ exceptions ]----- */
  1491. DEFPRINT(AST_Try, function(self, output) {
  1492. output.print("try");
  1493. output.space();
  1494. print_braced(self, output);
  1495. if (self.bcatch) {
  1496. output.space();
  1497. self.bcatch.print(output);
  1498. }
  1499. if (self.bfinally) {
  1500. output.space();
  1501. self.bfinally.print(output);
  1502. }
  1503. });
  1504. DEFPRINT(AST_Catch, function(self, output) {
  1505. output.print("catch");
  1506. if (self.argname) {
  1507. output.space();
  1508. output.with_parens(function() {
  1509. self.argname.print(output);
  1510. });
  1511. }
  1512. output.space();
  1513. print_braced(self, output);
  1514. });
  1515. DEFPRINT(AST_Finally, function(self, output) {
  1516. output.print("finally");
  1517. output.space();
  1518. print_braced(self, output);
  1519. });
  1520. /* -----[ var/const ]----- */
  1521. AST_Definitions.DEFMETHOD("_do_print", function(output, kind) {
  1522. output.print(kind);
  1523. output.space();
  1524. this.definitions.forEach(function(def, i) {
  1525. if (i) output.comma();
  1526. def.print(output);
  1527. });
  1528. var p = output.parent();
  1529. var in_for = p instanceof AST_For || p instanceof AST_ForIn;
  1530. var output_semicolon = !in_for || p && p.init !== this;
  1531. if (output_semicolon)
  1532. output.semicolon();
  1533. });
  1534. DEFPRINT(AST_Let, function(self, output) {
  1535. self._do_print(output, "let");
  1536. });
  1537. DEFPRINT(AST_Var, function(self, output) {
  1538. self._do_print(output, "var");
  1539. });
  1540. DEFPRINT(AST_Const, function(self, output) {
  1541. self._do_print(output, "const");
  1542. });
  1543. DEFPRINT(AST_Import, function(self, output) {
  1544. output.print("import");
  1545. output.space();
  1546. if (self.imported_name) {
  1547. self.imported_name.print(output);
  1548. }
  1549. if (self.imported_name && self.imported_names) {
  1550. output.print(",");
  1551. output.space();
  1552. }
  1553. if (self.imported_names) {
  1554. if (self.imported_names.length === 1 && self.imported_names[0].foreign_name.name === "*") {
  1555. self.imported_names[0].print(output);
  1556. } else {
  1557. output.print("{");
  1558. self.imported_names.forEach(function (name_import, i) {
  1559. output.space();
  1560. name_import.print(output);
  1561. if (i < self.imported_names.length - 1) {
  1562. output.print(",");
  1563. }
  1564. });
  1565. output.space();
  1566. output.print("}");
  1567. }
  1568. }
  1569. if (self.imported_name || self.imported_names) {
  1570. output.space();
  1571. output.print("from");
  1572. output.space();
  1573. }
  1574. self.module_name.print(output);
  1575. if (self.assert_clause) {
  1576. output.print("assert");
  1577. self.assert_clause.print(output);
  1578. }
  1579. output.semicolon();
  1580. });
  1581. DEFPRINT(AST_ImportMeta, function(self, output) {
  1582. output.print("import.meta");
  1583. });
  1584. DEFPRINT(AST_NameMapping, function(self, output) {
  1585. var is_import = output.parent() instanceof AST_Import;
  1586. var definition = self.name.definition();
  1587. var names_are_different =
  1588. (definition && definition.mangled_name || self.name.name) !==
  1589. self.foreign_name.name;
  1590. if (names_are_different) {
  1591. if (is_import) {
  1592. output.print(self.foreign_name.name);
  1593. } else {
  1594. self.name.print(output);
  1595. }
  1596. output.space();
  1597. output.print("as");
  1598. output.space();
  1599. if (is_import) {
  1600. self.name.print(output);
  1601. } else {
  1602. output.print(self.foreign_name.name);
  1603. }
  1604. } else {
  1605. self.name.print(output);
  1606. }
  1607. });
  1608. DEFPRINT(AST_Export, function(self, output) {
  1609. output.print("export");
  1610. output.space();
  1611. if (self.is_default) {
  1612. output.print("default");
  1613. output.space();
  1614. }
  1615. if (self.exported_names) {
  1616. if (self.exported_names.length === 1 && self.exported_names[0].name.name === "*") {
  1617. self.exported_names[0].print(output);
  1618. } else {
  1619. output.print("{");
  1620. self.exported_names.forEach(function(name_export, i) {
  1621. output.space();
  1622. name_export.print(output);
  1623. if (i < self.exported_names.length - 1) {
  1624. output.print(",");
  1625. }
  1626. });
  1627. output.space();
  1628. output.print("}");
  1629. }
  1630. } else if (self.exported_value) {
  1631. self.exported_value.print(output);
  1632. } else if (self.exported_definition) {
  1633. self.exported_definition.print(output);
  1634. if (self.exported_definition instanceof AST_Definitions) return;
  1635. }
  1636. if (self.module_name) {
  1637. output.space();
  1638. output.print("from");
  1639. output.space();
  1640. self.module_name.print(output);
  1641. }
  1642. if (self.assert_clause) {
  1643. output.print("assert");
  1644. self.assert_clause.print(output);
  1645. }
  1646. if (self.exported_value
  1647. && !(self.exported_value instanceof AST_Defun ||
  1648. self.exported_value instanceof AST_Function ||
  1649. self.exported_value instanceof AST_Class)
  1650. || self.module_name
  1651. || self.exported_names
  1652. ) {
  1653. output.semicolon();
  1654. }
  1655. });
  1656. function parenthesize_for_noin(node, output, noin) {
  1657. var parens = false;
  1658. // need to take some precautions here:
  1659. // https://github.com/mishoo/UglifyJS2/issues/60
  1660. if (noin) {
  1661. parens = walk(node, node => {
  1662. // Don't go into scopes -- except arrow functions:
  1663. // https://github.com/terser/terser/issues/1019#issuecomment-877642607
  1664. if (node instanceof AST_Scope && !(node instanceof AST_Arrow)) {
  1665. return true;
  1666. }
  1667. if (
  1668. node instanceof AST_Binary && node.operator == "in"
  1669. || node instanceof AST_PrivateIn
  1670. ) {
  1671. return walk_abort; // makes walk() return true
  1672. }
  1673. });
  1674. }
  1675. node.print(output, parens);
  1676. }
  1677. DEFPRINT(AST_VarDef, function(self, output) {
  1678. self.name.print(output);
  1679. if (self.value) {
  1680. output.space();
  1681. output.print("=");
  1682. output.space();
  1683. var p = output.parent(1);
  1684. var noin = p instanceof AST_For || p instanceof AST_ForIn;
  1685. parenthesize_for_noin(self.value, output, noin);
  1686. }
  1687. });
  1688. /* -----[ other expressions ]----- */
  1689. DEFPRINT(AST_Call, function(self, output) {
  1690. self.expression.print(output);
  1691. if (self instanceof AST_New && self.args.length === 0)
  1692. return;
  1693. if (self.expression instanceof AST_Call || self.expression instanceof AST_Lambda) {
  1694. output.add_mapping(self.start);
  1695. }
  1696. if (self.optional) output.print("?.");
  1697. output.with_parens(function() {
  1698. self.args.forEach(function(expr, i) {
  1699. if (i) output.comma();
  1700. expr.print(output);
  1701. });
  1702. });
  1703. });
  1704. DEFPRINT(AST_New, function(self, output) {
  1705. output.print("new");
  1706. output.space();
  1707. AST_Call.prototype._codegen(self, output);
  1708. });
  1709. AST_Sequence.DEFMETHOD("_do_print", function(output) {
  1710. this.expressions.forEach(function(node, index) {
  1711. if (index > 0) {
  1712. output.comma();
  1713. if (output.should_break()) {
  1714. output.newline();
  1715. output.indent();
  1716. }
  1717. }
  1718. node.print(output);
  1719. });
  1720. });
  1721. DEFPRINT(AST_Sequence, function(self, output) {
  1722. self._do_print(output);
  1723. // var p = output.parent();
  1724. // if (p instanceof AST_Statement) {
  1725. // output.with_indent(output.next_indent(), function(){
  1726. // self._do_print(output);
  1727. // });
  1728. // } else {
  1729. // self._do_print(output);
  1730. // }
  1731. });
  1732. DEFPRINT(AST_Dot, function(self, output) {
  1733. var expr = self.expression;
  1734. expr.print(output);
  1735. var prop = self.property;
  1736. var print_computed = ALL_RESERVED_WORDS.has(prop)
  1737. ? output.option("ie8")
  1738. : !is_identifier_string(
  1739. prop,
  1740. output.option("ecma") >= 2015 || output.option("safari10")
  1741. );
  1742. if (self.optional) output.print("?.");
  1743. if (print_computed) {
  1744. output.print("[");
  1745. output.add_mapping(self.end);
  1746. output.print_string(prop);
  1747. output.print("]");
  1748. } else {
  1749. if (expr instanceof AST_Number && expr.getValue() >= 0) {
  1750. if (!/[xa-f.)]/i.test(output.last())) {
  1751. output.print(".");
  1752. }
  1753. }
  1754. if (!self.optional) output.print(".");
  1755. // the name after dot would be mapped about here.
  1756. output.add_mapping(self.end);
  1757. output.print_name(prop);
  1758. }
  1759. });
  1760. DEFPRINT(AST_DotHash, function(self, output) {
  1761. var expr = self.expression;
  1762. expr.print(output);
  1763. var prop = self.property;
  1764. if (self.optional) output.print("?");
  1765. output.print(".#");
  1766. output.add_mapping(self.end);
  1767. output.print_name(prop);
  1768. });
  1769. DEFPRINT(AST_Sub, function(self, output) {
  1770. self.expression.print(output);
  1771. if (self.optional) output.print("?.");
  1772. output.print("[");
  1773. self.property.print(output);
  1774. output.print("]");
  1775. });
  1776. DEFPRINT(AST_Chain, function(self, output) {
  1777. self.expression.print(output);
  1778. });
  1779. DEFPRINT(AST_UnaryPrefix, function(self, output) {
  1780. var op = self.operator;
  1781. output.print(op);
  1782. if (/^[a-z]/i.test(op)
  1783. || (/[+-]$/.test(op)
  1784. && self.expression instanceof AST_UnaryPrefix
  1785. && /^[+-]/.test(self.expression.operator))) {
  1786. output.space();
  1787. }
  1788. self.expression.print(output);
  1789. });
  1790. DEFPRINT(AST_UnaryPostfix, function(self, output) {
  1791. self.expression.print(output);
  1792. output.print(self.operator);
  1793. });
  1794. DEFPRINT(AST_Binary, function(self, output) {
  1795. var op = self.operator;
  1796. self.left.print(output);
  1797. if (op[0] == ">" /* ">>" ">>>" ">" ">=" */
  1798. && self.left instanceof AST_UnaryPostfix
  1799. && self.left.operator == "--") {
  1800. // space is mandatory to avoid outputting -->
  1801. output.print(" ");
  1802. } else {
  1803. // the space is optional depending on "beautify"
  1804. output.space();
  1805. }
  1806. output.print(op);
  1807. if ((op == "<" || op == "<<")
  1808. && self.right instanceof AST_UnaryPrefix
  1809. && self.right.operator == "!"
  1810. && self.right.expression instanceof AST_UnaryPrefix
  1811. && self.right.expression.operator == "--") {
  1812. // space is mandatory to avoid outputting <!--
  1813. output.print(" ");
  1814. } else {
  1815. // the space is optional depending on "beautify"
  1816. output.space();
  1817. }
  1818. self.right.print(output);
  1819. });
  1820. DEFPRINT(AST_Conditional, function(self, output) {
  1821. self.condition.print(output);
  1822. output.space();
  1823. output.print("?");
  1824. output.space();
  1825. self.consequent.print(output);
  1826. output.space();
  1827. output.colon();
  1828. self.alternative.print(output);
  1829. });
  1830. /* -----[ literals ]----- */
  1831. DEFPRINT(AST_Array, function(self, output) {
  1832. output.with_square(function() {
  1833. var a = self.elements, len = a.length;
  1834. if (len > 0) output.space();
  1835. a.forEach(function(exp, i) {
  1836. if (i) output.comma();
  1837. exp.print(output);
  1838. // If the final element is a hole, we need to make sure it
  1839. // doesn't look like a trailing comma, by inserting an actual
  1840. // trailing comma.
  1841. if (i === len - 1 && exp instanceof AST_Hole)
  1842. output.comma();
  1843. });
  1844. if (len > 0) output.space();
  1845. });
  1846. });
  1847. DEFPRINT(AST_Object, function(self, output) {
  1848. if (self.properties.length > 0) output.with_block(function() {
  1849. self.properties.forEach(function(prop, i) {
  1850. if (i) {
  1851. output.print(",");
  1852. output.newline();
  1853. }
  1854. output.indent();
  1855. prop.print(output);
  1856. });
  1857. output.newline();
  1858. });
  1859. else print_braced_empty(self, output);
  1860. });
  1861. DEFPRINT(AST_Class, function(self, output) {
  1862. output.print("class");
  1863. output.space();
  1864. if (self.name) {
  1865. self.name.print(output);
  1866. output.space();
  1867. }
  1868. if (self.extends) {
  1869. var parens = (
  1870. !(self.extends instanceof AST_SymbolRef)
  1871. && !(self.extends instanceof AST_PropAccess)
  1872. && !(self.extends instanceof AST_ClassExpression)
  1873. && !(self.extends instanceof AST_Function)
  1874. );
  1875. output.print("extends");
  1876. if (parens) {
  1877. output.print("(");
  1878. } else {
  1879. output.space();
  1880. }
  1881. self.extends.print(output);
  1882. if (parens) {
  1883. output.print(")");
  1884. } else {
  1885. output.space();
  1886. }
  1887. }
  1888. if (self.properties.length > 0) output.with_block(function() {
  1889. self.properties.forEach(function(prop, i) {
  1890. if (i) {
  1891. output.newline();
  1892. }
  1893. output.indent();
  1894. prop.print(output);
  1895. });
  1896. output.newline();
  1897. });
  1898. else output.print("{}");
  1899. });
  1900. DEFPRINT(AST_NewTarget, function(self, output) {
  1901. output.print("new.target");
  1902. });
  1903. function print_property_name(key, quote, output) {
  1904. if (output.option("quote_keys")) {
  1905. return output.print_string(key);
  1906. }
  1907. if ("" + +key == key && key >= 0) {
  1908. if (output.option("keep_numbers")) {
  1909. return output.print(key);
  1910. }
  1911. return output.print(make_num(key));
  1912. }
  1913. var print_string = ALL_RESERVED_WORDS.has(key)
  1914. ? output.option("ie8")
  1915. : (
  1916. output.option("ecma") < 2015 || output.option("safari10")
  1917. ? !is_basic_identifier_string(key)
  1918. : !is_identifier_string(key, true)
  1919. );
  1920. if (print_string || (quote && output.option("keep_quoted_props"))) {
  1921. return output.print_string(key, quote);
  1922. }
  1923. return output.print_name(key);
  1924. }
  1925. DEFPRINT(AST_ObjectKeyVal, function(self, output) {
  1926. function get_name(self) {
  1927. var def = self.definition();
  1928. return def ? def.mangled_name || def.name : self.name;
  1929. }
  1930. var allowShortHand = output.option("shorthand");
  1931. if (allowShortHand &&
  1932. self.value instanceof AST_Symbol &&
  1933. is_identifier_string(
  1934. self.key,
  1935. output.option("ecma") >= 2015 || output.option("safari10")
  1936. ) &&
  1937. get_name(self.value) === self.key &&
  1938. !ALL_RESERVED_WORDS.has(self.key)
  1939. ) {
  1940. print_property_name(self.key, self.quote, output);
  1941. } else if (allowShortHand &&
  1942. self.value instanceof AST_DefaultAssign &&
  1943. self.value.left instanceof AST_Symbol &&
  1944. is_identifier_string(
  1945. self.key,
  1946. output.option("ecma") >= 2015 || output.option("safari10")
  1947. ) &&
  1948. get_name(self.value.left) === self.key
  1949. ) {
  1950. print_property_name(self.key, self.quote, output);
  1951. output.space();
  1952. output.print("=");
  1953. output.space();
  1954. self.value.right.print(output);
  1955. } else {
  1956. if (!(self.key instanceof AST_Node)) {
  1957. print_property_name(self.key, self.quote, output);
  1958. } else {
  1959. output.with_square(function() {
  1960. self.key.print(output);
  1961. });
  1962. }
  1963. output.colon();
  1964. self.value.print(output);
  1965. }
  1966. });
  1967. DEFPRINT(AST_ClassPrivateProperty, (self, output) => {
  1968. if (self.static) {
  1969. output.print("static");
  1970. output.space();
  1971. }
  1972. output.print("#");
  1973. print_property_name(self.key.name, self.quote, output);
  1974. if (self.value) {
  1975. output.print("=");
  1976. self.value.print(output);
  1977. }
  1978. output.semicolon();
  1979. });
  1980. DEFPRINT(AST_ClassProperty, (self, output) => {
  1981. if (self.static) {
  1982. output.print("static");
  1983. output.space();
  1984. }
  1985. if (self.key instanceof AST_SymbolClassProperty) {
  1986. print_property_name(self.key.name, self.quote, output);
  1987. } else {
  1988. output.print("[");
  1989. self.key.print(output);
  1990. output.print("]");
  1991. }
  1992. if (self.value) {
  1993. output.print("=");
  1994. self.value.print(output);
  1995. }
  1996. output.semicolon();
  1997. });
  1998. AST_ObjectProperty.DEFMETHOD("_print_getter_setter", function(type, is_private, output) {
  1999. var self = this;
  2000. if (self.static) {
  2001. output.print("static");
  2002. output.space();
  2003. }
  2004. if (type) {
  2005. output.print(type);
  2006. output.space();
  2007. }
  2008. if (self.key instanceof AST_SymbolMethod) {
  2009. if (is_private) output.print("#");
  2010. print_property_name(self.key.name, self.quote, output);
  2011. } else {
  2012. output.with_square(function() {
  2013. self.key.print(output);
  2014. });
  2015. }
  2016. self.value._do_print(output, true);
  2017. });
  2018. DEFPRINT(AST_ObjectSetter, function(self, output) {
  2019. self._print_getter_setter("set", false, output);
  2020. });
  2021. DEFPRINT(AST_ObjectGetter, function(self, output) {
  2022. self._print_getter_setter("get", false, output);
  2023. });
  2024. DEFPRINT(AST_PrivateSetter, function(self, output) {
  2025. self._print_getter_setter("set", true, output);
  2026. });
  2027. DEFPRINT(AST_PrivateGetter, function(self, output) {
  2028. self._print_getter_setter("get", true, output);
  2029. });
  2030. DEFPRINT(AST_PrivateMethod, function(self, output) {
  2031. var type;
  2032. if (self.is_generator && self.async) {
  2033. type = "async*";
  2034. } else if (self.is_generator) {
  2035. type = "*";
  2036. } else if (self.async) {
  2037. type = "async";
  2038. }
  2039. self._print_getter_setter(type, true, output);
  2040. });
  2041. DEFPRINT(AST_PrivateIn, function(self, output) {
  2042. self.key.print(output);
  2043. output.space();
  2044. output.print("in");
  2045. output.space();
  2046. self.value.print(output);
  2047. });
  2048. DEFPRINT(AST_SymbolPrivateProperty, function(self, output) {
  2049. output.print("#" + self.name);
  2050. });
  2051. DEFPRINT(AST_ConciseMethod, function(self, output) {
  2052. var type;
  2053. if (self.is_generator && self.async) {
  2054. type = "async*";
  2055. } else if (self.is_generator) {
  2056. type = "*";
  2057. } else if (self.async) {
  2058. type = "async";
  2059. }
  2060. self._print_getter_setter(type, false, output);
  2061. });
  2062. DEFPRINT(AST_ClassStaticBlock, function (self, output) {
  2063. output.print("static");
  2064. output.space();
  2065. print_braced(self, output);
  2066. });
  2067. AST_Symbol.DEFMETHOD("_do_print", function(output) {
  2068. var def = this.definition();
  2069. output.print_name(def ? def.mangled_name || def.name : this.name);
  2070. });
  2071. DEFPRINT(AST_Symbol, function (self, output) {
  2072. self._do_print(output);
  2073. });
  2074. DEFPRINT(AST_Hole, noop);
  2075. DEFPRINT(AST_This, function(self, output) {
  2076. output.print("this");
  2077. });
  2078. DEFPRINT(AST_Super, function(self, output) {
  2079. output.print("super");
  2080. });
  2081. DEFPRINT(AST_Constant, function(self, output) {
  2082. output.print(self.getValue());
  2083. });
  2084. DEFPRINT(AST_String, function(self, output) {
  2085. output.print_string(self.getValue(), self.quote, output.in_directive);
  2086. });
  2087. DEFPRINT(AST_Number, function(self, output) {
  2088. if ((output.option("keep_numbers") || output.use_asm) && self.raw) {
  2089. output.print(self.raw);
  2090. } else {
  2091. output.print(make_num(self.getValue()));
  2092. }
  2093. });
  2094. DEFPRINT(AST_BigInt, function(self, output) {
  2095. output.print(self.getValue() + "n");
  2096. });
  2097. const r_slash_script = /(<\s*\/\s*script)/i;
  2098. const slash_script_replace = (_, $1) => $1.replace("/", "\\/");
  2099. DEFPRINT(AST_RegExp, function(self, output) {
  2100. let { source, flags } = self.getValue();
  2101. source = regexp_source_fix(source);
  2102. flags = flags ? sort_regexp_flags(flags) : "";
  2103. source = source.replace(r_slash_script, slash_script_replace);
  2104. output.print(output.to_utf8(`/${source}/${flags}`, false, true));
  2105. const parent = output.parent();
  2106. if (
  2107. parent instanceof AST_Binary
  2108. && /^\w/.test(parent.operator)
  2109. && parent.left === self
  2110. ) {
  2111. output.print(" ");
  2112. }
  2113. });
  2114. function force_statement(stat, output) {
  2115. if (output.option("braces")) {
  2116. make_block(stat, output);
  2117. } else {
  2118. if (!stat || stat instanceof AST_EmptyStatement)
  2119. output.force_semicolon();
  2120. else
  2121. stat.print(output);
  2122. }
  2123. }
  2124. function best_of(a) {
  2125. var best = a[0], len = best.length;
  2126. for (var i = 1; i < a.length; ++i) {
  2127. if (a[i].length < len) {
  2128. best = a[i];
  2129. len = best.length;
  2130. }
  2131. }
  2132. return best;
  2133. }
  2134. function make_num(num) {
  2135. var str = num.toString(10).replace(/^0\./, ".").replace("e+", "e");
  2136. var candidates = [ str ];
  2137. if (Math.floor(num) === num) {
  2138. if (num < 0) {
  2139. candidates.push("-0x" + (-num).toString(16).toLowerCase());
  2140. } else {
  2141. candidates.push("0x" + num.toString(16).toLowerCase());
  2142. }
  2143. }
  2144. var match, len, digits;
  2145. if (match = /^\.0+/.exec(str)) {
  2146. len = match[0].length;
  2147. digits = str.slice(len);
  2148. candidates.push(digits + "e-" + (digits.length + len - 1));
  2149. } else if (match = /0+$/.exec(str)) {
  2150. len = match[0].length;
  2151. candidates.push(str.slice(0, -len) + "e" + len);
  2152. } else if (match = /^(\d)\.(\d+)e(-?\d+)$/.exec(str)) {
  2153. candidates.push(match[1] + match[2] + "e" + (match[3] - match[2].length));
  2154. }
  2155. return best_of(candidates);
  2156. }
  2157. function make_block(stmt, output) {
  2158. if (!stmt || stmt instanceof AST_EmptyStatement)
  2159. output.print("{}");
  2160. else if (stmt instanceof AST_BlockStatement)
  2161. stmt.print(output);
  2162. else output.with_block(function() {
  2163. output.indent();
  2164. stmt.print(output);
  2165. output.newline();
  2166. });
  2167. }
  2168. /* -----[ source map generators ]----- */
  2169. function DEFMAP(nodetype, generator) {
  2170. nodetype.forEach(function(nodetype) {
  2171. nodetype.DEFMETHOD("add_source_map", generator);
  2172. });
  2173. }
  2174. DEFMAP([
  2175. // We could easily add info for ALL nodes, but it seems to me that
  2176. // would be quite wasteful, hence this noop in the base class.
  2177. AST_Node,
  2178. // since the label symbol will mark it
  2179. AST_LabeledStatement,
  2180. AST_Toplevel,
  2181. ], noop);
  2182. // XXX: I'm not exactly sure if we need it for all of these nodes,
  2183. // or if we should add even more.
  2184. DEFMAP([
  2185. AST_Array,
  2186. AST_BlockStatement,
  2187. AST_Catch,
  2188. AST_Class,
  2189. AST_Constant,
  2190. AST_Debugger,
  2191. AST_Definitions,
  2192. AST_Directive,
  2193. AST_Finally,
  2194. AST_Jump,
  2195. AST_Lambda,
  2196. AST_New,
  2197. AST_Object,
  2198. AST_StatementWithBody,
  2199. AST_Symbol,
  2200. AST_Switch,
  2201. AST_SwitchBranch,
  2202. AST_TemplateString,
  2203. AST_TemplateSegment,
  2204. AST_Try,
  2205. ], function(output) {
  2206. output.add_mapping(this.start);
  2207. });
  2208. DEFMAP([
  2209. AST_ObjectGetter,
  2210. AST_ObjectSetter,
  2211. AST_PrivateGetter,
  2212. AST_PrivateSetter,
  2213. ], function(output) {
  2214. output.add_mapping(this.key.end, this.key.name);
  2215. });
  2216. DEFMAP([ AST_ObjectProperty ], function(output) {
  2217. output.add_mapping(this.start, this.key);
  2218. });
  2219. })();
  2220. export {
  2221. OutputStream,
  2222. };