output.js 75 KB

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