7ed4c96823b5bf2aca69eff3d4a8c25831e52a27421db30b93ebaa15d18aa5d15db2f25f4a0fcfc2549be337eabb5222c12649ea13d1af0d101ef50dbacc70 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455
  1. /*jshint node:true */
  2. /*
  3. The MIT License (MIT)
  4. Copyright (c) 2007-2018 Einar Lielmanis, Liam Newman, and contributors.
  5. Permission is hereby granted, free of charge, to any person
  6. obtaining a copy of this software and associated documentation files
  7. (the "Software"), to deal in the Software without restriction,
  8. including without limitation the rights to use, copy, modify, merge,
  9. publish, distribute, sublicense, and/or sell copies of the Software,
  10. and to permit persons to whom the Software is furnished to do so,
  11. subject to the following conditions:
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  18. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  19. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  20. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. SOFTWARE.
  22. */
  23. 'use strict';
  24. var Output = require('../core/output').Output;
  25. var Token = require('../core/token').Token;
  26. var acorn = require('./acorn');
  27. var Options = require('./options').Options;
  28. var Tokenizer = require('./tokenizer').Tokenizer;
  29. var line_starters = require('./tokenizer').line_starters;
  30. var positionable_operators = require('./tokenizer').positionable_operators;
  31. var TOKEN = require('./tokenizer').TOKEN;
  32. function in_array(what, arr) {
  33. return arr.indexOf(what) !== -1;
  34. }
  35. function ltrim(s) {
  36. return s.replace(/^\s+/g, '');
  37. }
  38. function generateMapFromStrings(list) {
  39. var result = {};
  40. for (var x = 0; x < list.length; x++) {
  41. // make the mapped names underscored instead of dash
  42. result[list[x].replace(/-/g, '_')] = list[x];
  43. }
  44. return result;
  45. }
  46. function reserved_word(token, word) {
  47. return token && token.type === TOKEN.RESERVED && token.text === word;
  48. }
  49. function reserved_array(token, words) {
  50. return token && token.type === TOKEN.RESERVED && in_array(token.text, words);
  51. }
  52. // Unsure of what they mean, but they work. Worth cleaning up in future.
  53. var special_words = ['case', 'return', 'do', 'if', 'throw', 'else', 'await', 'break', 'continue', 'async'];
  54. var validPositionValues = ['before-newline', 'after-newline', 'preserve-newline'];
  55. // Generate map from array
  56. var OPERATOR_POSITION = generateMapFromStrings(validPositionValues);
  57. var OPERATOR_POSITION_BEFORE_OR_PRESERVE = [OPERATOR_POSITION.before_newline, OPERATOR_POSITION.preserve_newline];
  58. var MODE = {
  59. BlockStatement: 'BlockStatement', // 'BLOCK'
  60. Statement: 'Statement', // 'STATEMENT'
  61. ObjectLiteral: 'ObjectLiteral', // 'OBJECT',
  62. ArrayLiteral: 'ArrayLiteral', //'[EXPRESSION]',
  63. ForInitializer: 'ForInitializer', //'(FOR-EXPRESSION)',
  64. Conditional: 'Conditional', //'(COND-EXPRESSION)',
  65. Expression: 'Expression' //'(EXPRESSION)'
  66. };
  67. function remove_redundant_indentation(output, frame) {
  68. // This implementation is effective but has some issues:
  69. // - can cause line wrap to happen too soon due to indent removal
  70. // after wrap points are calculated
  71. // These issues are minor compared to ugly indentation.
  72. if (frame.multiline_frame ||
  73. frame.mode === MODE.ForInitializer ||
  74. frame.mode === MODE.Conditional) {
  75. return;
  76. }
  77. // remove one indent from each line inside this section
  78. output.remove_indent(frame.start_line_index);
  79. }
  80. // we could use just string.split, but
  81. // IE doesn't like returning empty strings
  82. function split_linebreaks(s) {
  83. //return s.split(/\x0d\x0a|\x0a/);
  84. s = s.replace(acorn.allLineBreaks, '\n');
  85. var out = [],
  86. idx = s.indexOf("\n");
  87. while (idx !== -1) {
  88. out.push(s.substring(0, idx));
  89. s = s.substring(idx + 1);
  90. idx = s.indexOf("\n");
  91. }
  92. if (s.length) {
  93. out.push(s);
  94. }
  95. return out;
  96. }
  97. function is_array(mode) {
  98. return mode === MODE.ArrayLiteral;
  99. }
  100. function is_expression(mode) {
  101. return in_array(mode, [MODE.Expression, MODE.ForInitializer, MODE.Conditional]);
  102. }
  103. function all_lines_start_with(lines, c) {
  104. for (var i = 0; i < lines.length; i++) {
  105. var line = lines[i].trim();
  106. if (line.charAt(0) !== c) {
  107. return false;
  108. }
  109. }
  110. return true;
  111. }
  112. function each_line_matches_indent(lines, indent) {
  113. var i = 0,
  114. len = lines.length,
  115. line;
  116. for (; i < len; i++) {
  117. line = lines[i];
  118. // allow empty lines to pass through
  119. if (line && line.indexOf(indent) !== 0) {
  120. return false;
  121. }
  122. }
  123. return true;
  124. }
  125. function Beautifier(source_text, options) {
  126. options = options || {};
  127. this._source_text = source_text || '';
  128. this._output = null;
  129. this._tokens = null;
  130. this._last_last_text = null;
  131. this._flags = null;
  132. this._previous_flags = null;
  133. this._flag_store = null;
  134. this._options = new Options(options);
  135. }
  136. Beautifier.prototype.create_flags = function(flags_base, mode) {
  137. var next_indent_level = 0;
  138. if (flags_base) {
  139. next_indent_level = flags_base.indentation_level;
  140. if (!this._output.just_added_newline() &&
  141. flags_base.line_indent_level > next_indent_level) {
  142. next_indent_level = flags_base.line_indent_level;
  143. }
  144. }
  145. var next_flags = {
  146. mode: mode,
  147. parent: flags_base,
  148. last_token: flags_base ? flags_base.last_token : new Token(TOKEN.START_BLOCK, ''), // last token text
  149. last_word: flags_base ? flags_base.last_word : '', // last TOKEN.WORD passed
  150. declaration_statement: false,
  151. declaration_assignment: false,
  152. multiline_frame: false,
  153. inline_frame: false,
  154. if_block: false,
  155. else_block: false,
  156. do_block: false,
  157. do_while: false,
  158. import_block: false,
  159. in_case_statement: false, // switch(..){ INSIDE HERE }
  160. in_case: false, // we're on the exact line with "case 0:"
  161. case_body: false, // the indented case-action block
  162. indentation_level: next_indent_level,
  163. alignment: 0,
  164. line_indent_level: flags_base ? flags_base.line_indent_level : next_indent_level,
  165. start_line_index: this._output.get_line_number(),
  166. ternary_depth: 0
  167. };
  168. return next_flags;
  169. };
  170. Beautifier.prototype._reset = function(source_text) {
  171. var baseIndentString = source_text.match(/^[\t ]*/)[0];
  172. this._last_last_text = ''; // pre-last token text
  173. this._output = new Output(this._options, baseIndentString);
  174. // If testing the ignore directive, start with output disable set to true
  175. this._output.raw = this._options.test_output_raw;
  176. // Stack of parsing/formatting states, including MODE.
  177. // We tokenize, parse, and output in an almost purely a forward-only stream of token input
  178. // and formatted output. This makes the beautifier less accurate than full parsers
  179. // but also far more tolerant of syntax errors.
  180. //
  181. // For example, the default mode is MODE.BlockStatement. If we see a '{' we push a new frame of type
  182. // MODE.BlockStatement on the the stack, even though it could be object literal. If we later
  183. // encounter a ":", we'll switch to to MODE.ObjectLiteral. If we then see a ";",
  184. // most full parsers would die, but the beautifier gracefully falls back to
  185. // MODE.BlockStatement and continues on.
  186. this._flag_store = [];
  187. this.set_mode(MODE.BlockStatement);
  188. var tokenizer = new Tokenizer(source_text, this._options);
  189. this._tokens = tokenizer.tokenize();
  190. return source_text;
  191. };
  192. Beautifier.prototype.beautify = function() {
  193. // if disabled, return the input unchanged.
  194. if (this._options.disabled) {
  195. return this._source_text;
  196. }
  197. var sweet_code;
  198. var source_text = this._reset(this._source_text);
  199. var eol = this._options.eol;
  200. if (this._options.eol === 'auto') {
  201. eol = '\n';
  202. if (source_text && acorn.lineBreak.test(source_text || '')) {
  203. eol = source_text.match(acorn.lineBreak)[0];
  204. }
  205. }
  206. var current_token = this._tokens.next();
  207. while (current_token) {
  208. this.handle_token(current_token);
  209. this._last_last_text = this._flags.last_token.text;
  210. this._flags.last_token = current_token;
  211. current_token = this._tokens.next();
  212. }
  213. sweet_code = this._output.get_code(eol);
  214. return sweet_code;
  215. };
  216. Beautifier.prototype.handle_token = function(current_token, preserve_statement_flags) {
  217. if (current_token.type === TOKEN.START_EXPR) {
  218. this.handle_start_expr(current_token);
  219. } else if (current_token.type === TOKEN.END_EXPR) {
  220. this.handle_end_expr(current_token);
  221. } else if (current_token.type === TOKEN.START_BLOCK) {
  222. this.handle_start_block(current_token);
  223. } else if (current_token.type === TOKEN.END_BLOCK) {
  224. this.handle_end_block(current_token);
  225. } else if (current_token.type === TOKEN.WORD) {
  226. this.handle_word(current_token);
  227. } else if (current_token.type === TOKEN.RESERVED) {
  228. this.handle_word(current_token);
  229. } else if (current_token.type === TOKEN.SEMICOLON) {
  230. this.handle_semicolon(current_token);
  231. } else if (current_token.type === TOKEN.STRING) {
  232. this.handle_string(current_token);
  233. } else if (current_token.type === TOKEN.EQUALS) {
  234. this.handle_equals(current_token);
  235. } else if (current_token.type === TOKEN.OPERATOR) {
  236. this.handle_operator(current_token);
  237. } else if (current_token.type === TOKEN.COMMA) {
  238. this.handle_comma(current_token);
  239. } else if (current_token.type === TOKEN.BLOCK_COMMENT) {
  240. this.handle_block_comment(current_token, preserve_statement_flags);
  241. } else if (current_token.type === TOKEN.COMMENT) {
  242. this.handle_comment(current_token, preserve_statement_flags);
  243. } else if (current_token.type === TOKEN.DOT) {
  244. this.handle_dot(current_token);
  245. } else if (current_token.type === TOKEN.EOF) {
  246. this.handle_eof(current_token);
  247. } else if (current_token.type === TOKEN.UNKNOWN) {
  248. this.handle_unknown(current_token, preserve_statement_flags);
  249. } else {
  250. this.handle_unknown(current_token, preserve_statement_flags);
  251. }
  252. };
  253. Beautifier.prototype.handle_whitespace_and_comments = function(current_token, preserve_statement_flags) {
  254. var newlines = current_token.newlines;
  255. var keep_whitespace = this._options.keep_array_indentation && is_array(this._flags.mode);
  256. if (current_token.comments_before) {
  257. var comment_token = current_token.comments_before.next();
  258. while (comment_token) {
  259. // The cleanest handling of inline comments is to treat them as though they aren't there.
  260. // Just continue formatting and the behavior should be logical.
  261. // Also ignore unknown tokens. Again, this should result in better behavior.
  262. this.handle_whitespace_and_comments(comment_token, preserve_statement_flags);
  263. this.handle_token(comment_token, preserve_statement_flags);
  264. comment_token = current_token.comments_before.next();
  265. }
  266. }
  267. if (keep_whitespace) {
  268. for (var i = 0; i < newlines; i += 1) {
  269. this.print_newline(i > 0, preserve_statement_flags);
  270. }
  271. } else {
  272. if (this._options.max_preserve_newlines && newlines > this._options.max_preserve_newlines) {
  273. newlines = this._options.max_preserve_newlines;
  274. }
  275. if (this._options.preserve_newlines) {
  276. if (newlines > 1) {
  277. this.print_newline(false, preserve_statement_flags);
  278. for (var j = 1; j < newlines; j += 1) {
  279. this.print_newline(true, preserve_statement_flags);
  280. }
  281. }
  282. }
  283. }
  284. };
  285. var newline_restricted_tokens = ['async', 'break', 'continue', 'return', 'throw', 'yield'];
  286. Beautifier.prototype.allow_wrap_or_preserved_newline = function(current_token, force_linewrap) {
  287. force_linewrap = (force_linewrap === undefined) ? false : force_linewrap;
  288. // Never wrap the first token on a line
  289. if (this._output.just_added_newline()) {
  290. return;
  291. }
  292. var shouldPreserveOrForce = (this._options.preserve_newlines && current_token.newlines) || force_linewrap;
  293. var operatorLogicApplies = in_array(this._flags.last_token.text, positionable_operators) ||
  294. in_array(current_token.text, positionable_operators);
  295. if (operatorLogicApplies) {
  296. var shouldPrintOperatorNewline = (
  297. in_array(this._flags.last_token.text, positionable_operators) &&
  298. in_array(this._options.operator_position, OPERATOR_POSITION_BEFORE_OR_PRESERVE)
  299. ) ||
  300. in_array(current_token.text, positionable_operators);
  301. shouldPreserveOrForce = shouldPreserveOrForce && shouldPrintOperatorNewline;
  302. }
  303. if (shouldPreserveOrForce) {
  304. this.print_newline(false, true);
  305. } else if (this._options.wrap_line_length) {
  306. if (reserved_array(this._flags.last_token, newline_restricted_tokens)) {
  307. // These tokens should never have a newline inserted
  308. // between them and the following expression.
  309. return;
  310. }
  311. this._output.set_wrap_point();
  312. }
  313. };
  314. Beautifier.prototype.print_newline = function(force_newline, preserve_statement_flags) {
  315. if (!preserve_statement_flags) {
  316. if (this._flags.last_token.text !== ';' && this._flags.last_token.text !== ',' && this._flags.last_token.text !== '=' && (this._flags.last_token.type !== TOKEN.OPERATOR || this._flags.last_token.text === '--' || this._flags.last_token.text === '++')) {
  317. var next_token = this._tokens.peek();
  318. while (this._flags.mode === MODE.Statement &&
  319. !(this._flags.if_block && reserved_word(next_token, 'else')) &&
  320. !this._flags.do_block) {
  321. this.restore_mode();
  322. }
  323. }
  324. }
  325. if (this._output.add_new_line(force_newline)) {
  326. this._flags.multiline_frame = true;
  327. }
  328. };
  329. Beautifier.prototype.print_token_line_indentation = function(current_token) {
  330. if (this._output.just_added_newline()) {
  331. if (this._options.keep_array_indentation &&
  332. current_token.newlines &&
  333. (current_token.text === '[' || is_array(this._flags.mode))) {
  334. this._output.current_line.set_indent(-1);
  335. this._output.current_line.push(current_token.whitespace_before);
  336. this._output.space_before_token = false;
  337. } else if (this._output.set_indent(this._flags.indentation_level, this._flags.alignment)) {
  338. this._flags.line_indent_level = this._flags.indentation_level;
  339. }
  340. }
  341. };
  342. Beautifier.prototype.print_token = function(current_token) {
  343. if (this._output.raw) {
  344. this._output.add_raw_token(current_token);
  345. return;
  346. }
  347. if (this._options.comma_first && current_token.previous && current_token.previous.type === TOKEN.COMMA &&
  348. this._output.just_added_newline()) {
  349. if (this._output.previous_line.last() === ',') {
  350. var popped = this._output.previous_line.pop();
  351. // if the comma was already at the start of the line,
  352. // pull back onto that line and reprint the indentation
  353. if (this._output.previous_line.is_empty()) {
  354. this._output.previous_line.push(popped);
  355. this._output.trim(true);
  356. this._output.current_line.pop();
  357. this._output.trim();
  358. }
  359. // add the comma in front of the next token
  360. this.print_token_line_indentation(current_token);
  361. this._output.add_token(',');
  362. this._output.space_before_token = true;
  363. }
  364. }
  365. this.print_token_line_indentation(current_token);
  366. this._output.non_breaking_space = true;
  367. this._output.add_token(current_token.text);
  368. if (this._output.previous_token_wrapped) {
  369. this._flags.multiline_frame = true;
  370. }
  371. };
  372. Beautifier.prototype.indent = function() {
  373. this._flags.indentation_level += 1;
  374. this._output.set_indent(this._flags.indentation_level, this._flags.alignment);
  375. };
  376. Beautifier.prototype.deindent = function() {
  377. if (this._flags.indentation_level > 0 &&
  378. ((!this._flags.parent) || this._flags.indentation_level > this._flags.parent.indentation_level)) {
  379. this._flags.indentation_level -= 1;
  380. this._output.set_indent(this._flags.indentation_level, this._flags.alignment);
  381. }
  382. };
  383. Beautifier.prototype.set_mode = function(mode) {
  384. if (this._flags) {
  385. this._flag_store.push(this._flags);
  386. this._previous_flags = this._flags;
  387. } else {
  388. this._previous_flags = this.create_flags(null, mode);
  389. }
  390. this._flags = this.create_flags(this._previous_flags, mode);
  391. this._output.set_indent(this._flags.indentation_level, this._flags.alignment);
  392. };
  393. Beautifier.prototype.restore_mode = function() {
  394. if (this._flag_store.length > 0) {
  395. this._previous_flags = this._flags;
  396. this._flags = this._flag_store.pop();
  397. if (this._previous_flags.mode === MODE.Statement) {
  398. remove_redundant_indentation(this._output, this._previous_flags);
  399. }
  400. this._output.set_indent(this._flags.indentation_level, this._flags.alignment);
  401. }
  402. };
  403. Beautifier.prototype.start_of_object_property = function() {
  404. return this._flags.parent.mode === MODE.ObjectLiteral && this._flags.mode === MODE.Statement && (
  405. (this._flags.last_token.text === ':' && this._flags.ternary_depth === 0) || (reserved_array(this._flags.last_token, ['get', 'set'])));
  406. };
  407. Beautifier.prototype.start_of_statement = function(current_token) {
  408. var start = false;
  409. start = start || reserved_array(this._flags.last_token, ['var', 'let', 'const']) && current_token.type === TOKEN.WORD;
  410. start = start || reserved_word(this._flags.last_token, 'do');
  411. start = start || (!(this._flags.parent.mode === MODE.ObjectLiteral && this._flags.mode === MODE.Statement)) && reserved_array(this._flags.last_token, newline_restricted_tokens) && !current_token.newlines;
  412. start = start || reserved_word(this._flags.last_token, 'else') &&
  413. !(reserved_word(current_token, 'if') && !current_token.comments_before);
  414. start = start || (this._flags.last_token.type === TOKEN.END_EXPR && (this._previous_flags.mode === MODE.ForInitializer || this._previous_flags.mode === MODE.Conditional));
  415. start = start || (this._flags.last_token.type === TOKEN.WORD && this._flags.mode === MODE.BlockStatement &&
  416. !this._flags.in_case &&
  417. !(current_token.text === '--' || current_token.text === '++') &&
  418. this._last_last_text !== 'function' &&
  419. current_token.type !== TOKEN.WORD && current_token.type !== TOKEN.RESERVED);
  420. start = start || (this._flags.mode === MODE.ObjectLiteral && (
  421. (this._flags.last_token.text === ':' && this._flags.ternary_depth === 0) || reserved_array(this._flags.last_token, ['get', 'set'])));
  422. if (start) {
  423. this.set_mode(MODE.Statement);
  424. this.indent();
  425. this.handle_whitespace_and_comments(current_token, true);
  426. // Issue #276:
  427. // If starting a new statement with [if, for, while, do], push to a new line.
  428. // if (a) if (b) if(c) d(); else e(); else f();
  429. if (!this.start_of_object_property()) {
  430. this.allow_wrap_or_preserved_newline(current_token,
  431. reserved_array(current_token, ['do', 'for', 'if', 'while']));
  432. }
  433. return true;
  434. }
  435. return false;
  436. };
  437. Beautifier.prototype.handle_start_expr = function(current_token) {
  438. // The conditional starts the statement if appropriate.
  439. if (!this.start_of_statement(current_token)) {
  440. this.handle_whitespace_and_comments(current_token);
  441. }
  442. var next_mode = MODE.Expression;
  443. if (current_token.text === '[') {
  444. if (this._flags.last_token.type === TOKEN.WORD || this._flags.last_token.text === ')') {
  445. // this is array index specifier, break immediately
  446. // a[x], fn()[x]
  447. if (reserved_array(this._flags.last_token, line_starters)) {
  448. this._output.space_before_token = true;
  449. }
  450. this.print_token(current_token);
  451. this.set_mode(next_mode);
  452. this.indent();
  453. if (this._options.space_in_paren) {
  454. this._output.space_before_token = true;
  455. }
  456. return;
  457. }
  458. next_mode = MODE.ArrayLiteral;
  459. if (is_array(this._flags.mode)) {
  460. if (this._flags.last_token.text === '[' ||
  461. (this._flags.last_token.text === ',' && (this._last_last_text === ']' || this._last_last_text === '}'))) {
  462. // ], [ goes to new line
  463. // }, [ goes to new line
  464. if (!this._options.keep_array_indentation) {
  465. this.print_newline();
  466. }
  467. }
  468. }
  469. if (!in_array(this._flags.last_token.type, [TOKEN.START_EXPR, TOKEN.END_EXPR, TOKEN.WORD, TOKEN.OPERATOR])) {
  470. this._output.space_before_token = true;
  471. }
  472. } else {
  473. if (this._flags.last_token.type === TOKEN.RESERVED) {
  474. if (this._flags.last_token.text === 'for') {
  475. this._output.space_before_token = this._options.space_before_conditional;
  476. next_mode = MODE.ForInitializer;
  477. } else if (in_array(this._flags.last_token.text, ['if', 'while'])) {
  478. this._output.space_before_token = this._options.space_before_conditional;
  479. next_mode = MODE.Conditional;
  480. } else if (in_array(this._flags.last_word, ['await', 'async'])) {
  481. // Should be a space between await and an IIFE, or async and an arrow function
  482. this._output.space_before_token = true;
  483. } else if (this._flags.last_token.text === 'import' && current_token.whitespace_before === '') {
  484. this._output.space_before_token = false;
  485. } else if (in_array(this._flags.last_token.text, line_starters) || this._flags.last_token.text === 'catch') {
  486. this._output.space_before_token = true;
  487. }
  488. } else if (this._flags.last_token.type === TOKEN.EQUALS || this._flags.last_token.type === TOKEN.OPERATOR) {
  489. // Support of this kind of newline preservation.
  490. // a = (b &&
  491. // (c || d));
  492. if (!this.start_of_object_property()) {
  493. this.allow_wrap_or_preserved_newline(current_token);
  494. }
  495. } else if (this._flags.last_token.type === TOKEN.WORD) {
  496. this._output.space_before_token = false;
  497. // function name() vs function name ()
  498. // function* name() vs function* name ()
  499. // async name() vs async name ()
  500. // In ES6, you can also define the method properties of an object
  501. // var obj = {a: function() {}}
  502. // It can be abbreviated
  503. // var obj = {a() {}}
  504. // var obj = { a() {}} vs var obj = { a () {}}
  505. // var obj = { * a() {}} vs var obj = { * a () {}}
  506. var peek_back_two = this._tokens.peek(-3);
  507. if (this._options.space_after_named_function && peek_back_two) {
  508. // peek starts at next character so -1 is current token
  509. var peek_back_three = this._tokens.peek(-4);
  510. if (reserved_array(peek_back_two, ['async', 'function']) ||
  511. (peek_back_two.text === '*' && reserved_array(peek_back_three, ['async', 'function']))) {
  512. this._output.space_before_token = true;
  513. } else if (this._flags.mode === MODE.ObjectLiteral) {
  514. if ((peek_back_two.text === '{' || peek_back_two.text === ',') ||
  515. (peek_back_two.text === '*' && (peek_back_three.text === '{' || peek_back_three.text === ','))) {
  516. this._output.space_before_token = true;
  517. }
  518. }
  519. }
  520. } else {
  521. // Support preserving wrapped arrow function expressions
  522. // a.b('c',
  523. // () => d.e
  524. // )
  525. this.allow_wrap_or_preserved_newline(current_token);
  526. }
  527. // function() vs function ()
  528. // yield*() vs yield* ()
  529. // function*() vs function* ()
  530. if ((this._flags.last_token.type === TOKEN.RESERVED && (this._flags.last_word === 'function' || this._flags.last_word === 'typeof')) ||
  531. (this._flags.last_token.text === '*' &&
  532. (in_array(this._last_last_text, ['function', 'yield']) ||
  533. (this._flags.mode === MODE.ObjectLiteral && in_array(this._last_last_text, ['{', ',']))))) {
  534. this._output.space_before_token = this._options.space_after_anon_function;
  535. }
  536. }
  537. if (this._flags.last_token.text === ';' || this._flags.last_token.type === TOKEN.START_BLOCK) {
  538. this.print_newline();
  539. } else if (this._flags.last_token.type === TOKEN.END_EXPR || this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.END_BLOCK || this._flags.last_token.text === '.' || this._flags.last_token.type === TOKEN.COMMA) {
  540. // do nothing on (( and )( and ][ and ]( and .(
  541. // TODO: Consider whether forcing this is required. Review failing tests when removed.
  542. this.allow_wrap_or_preserved_newline(current_token, current_token.newlines);
  543. }
  544. this.print_token(current_token);
  545. this.set_mode(next_mode);
  546. if (this._options.space_in_paren) {
  547. this._output.space_before_token = true;
  548. }
  549. // In all cases, if we newline while inside an expression it should be indented.
  550. this.indent();
  551. };
  552. Beautifier.prototype.handle_end_expr = function(current_token) {
  553. // statements inside expressions are not valid syntax, but...
  554. // statements must all be closed when their container closes
  555. while (this._flags.mode === MODE.Statement) {
  556. this.restore_mode();
  557. }
  558. this.handle_whitespace_and_comments(current_token);
  559. if (this._flags.multiline_frame) {
  560. this.allow_wrap_or_preserved_newline(current_token,
  561. current_token.text === ']' && is_array(this._flags.mode) && !this._options.keep_array_indentation);
  562. }
  563. if (this._options.space_in_paren) {
  564. if (this._flags.last_token.type === TOKEN.START_EXPR && !this._options.space_in_empty_paren) {
  565. // () [] no inner space in empty parens like these, ever, ref #320
  566. this._output.trim();
  567. this._output.space_before_token = false;
  568. } else {
  569. this._output.space_before_token = true;
  570. }
  571. }
  572. this.deindent();
  573. this.print_token(current_token);
  574. this.restore_mode();
  575. remove_redundant_indentation(this._output, this._previous_flags);
  576. // do {} while () // no statement required after
  577. if (this._flags.do_while && this._previous_flags.mode === MODE.Conditional) {
  578. this._previous_flags.mode = MODE.Expression;
  579. this._flags.do_block = false;
  580. this._flags.do_while = false;
  581. }
  582. };
  583. Beautifier.prototype.handle_start_block = function(current_token) {
  584. this.handle_whitespace_and_comments(current_token);
  585. // Check if this is should be treated as a ObjectLiteral
  586. var next_token = this._tokens.peek();
  587. var second_token = this._tokens.peek(1);
  588. if (this._flags.last_word === 'switch' && this._flags.last_token.type === TOKEN.END_EXPR) {
  589. this.set_mode(MODE.BlockStatement);
  590. this._flags.in_case_statement = true;
  591. } else if (this._flags.case_body) {
  592. this.set_mode(MODE.BlockStatement);
  593. } else if (second_token && (
  594. (in_array(second_token.text, [':', ',']) && in_array(next_token.type, [TOKEN.STRING, TOKEN.WORD, TOKEN.RESERVED])) ||
  595. (in_array(next_token.text, ['get', 'set', '...']) && in_array(second_token.type, [TOKEN.WORD, TOKEN.RESERVED]))
  596. )) {
  597. // We don't support TypeScript,but we didn't break it for a very long time.
  598. // We'll try to keep not breaking it.
  599. if (!in_array(this._last_last_text, ['class', 'interface'])) {
  600. this.set_mode(MODE.ObjectLiteral);
  601. } else {
  602. this.set_mode(MODE.BlockStatement);
  603. }
  604. } else if (this._flags.last_token.type === TOKEN.OPERATOR && this._flags.last_token.text === '=>') {
  605. // arrow function: (param1, paramN) => { statements }
  606. this.set_mode(MODE.BlockStatement);
  607. } else if (in_array(this._flags.last_token.type, [TOKEN.EQUALS, TOKEN.START_EXPR, TOKEN.COMMA, TOKEN.OPERATOR]) ||
  608. reserved_array(this._flags.last_token, ['return', 'throw', 'import', 'default'])
  609. ) {
  610. // Detecting shorthand function syntax is difficult by scanning forward,
  611. // so check the surrounding context.
  612. // If the block is being returned, imported, export default, passed as arg,
  613. // assigned with = or assigned in a nested object, treat as an ObjectLiteral.
  614. this.set_mode(MODE.ObjectLiteral);
  615. } else {
  616. this.set_mode(MODE.BlockStatement);
  617. }
  618. var empty_braces = !next_token.comments_before && next_token.text === '}';
  619. var empty_anonymous_function = empty_braces && this._flags.last_word === 'function' &&
  620. this._flags.last_token.type === TOKEN.END_EXPR;
  621. if (this._options.brace_preserve_inline) // check for inline, set inline_frame if so
  622. {
  623. // search forward for a newline wanted inside this block
  624. var index = 0;
  625. var check_token = null;
  626. this._flags.inline_frame = true;
  627. do {
  628. index += 1;
  629. check_token = this._tokens.peek(index - 1);
  630. if (check_token.newlines) {
  631. this._flags.inline_frame = false;
  632. break;
  633. }
  634. } while (check_token.type !== TOKEN.EOF &&
  635. !(check_token.type === TOKEN.END_BLOCK && check_token.opened === current_token));
  636. }
  637. if ((this._options.brace_style === "expand" ||
  638. (this._options.brace_style === "none" && current_token.newlines)) &&
  639. !this._flags.inline_frame) {
  640. if (this._flags.last_token.type !== TOKEN.OPERATOR &&
  641. (empty_anonymous_function ||
  642. this._flags.last_token.type === TOKEN.EQUALS ||
  643. (reserved_array(this._flags.last_token, special_words) && this._flags.last_token.text !== 'else'))) {
  644. this._output.space_before_token = true;
  645. } else {
  646. this.print_newline(false, true);
  647. }
  648. } else { // collapse || inline_frame
  649. if (is_array(this._previous_flags.mode) && (this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.COMMA)) {
  650. if (this._flags.last_token.type === TOKEN.COMMA || this._options.space_in_paren) {
  651. this._output.space_before_token = true;
  652. }
  653. if (this._flags.last_token.type === TOKEN.COMMA || (this._flags.last_token.type === TOKEN.START_EXPR && this._flags.inline_frame)) {
  654. this.allow_wrap_or_preserved_newline(current_token);
  655. this._previous_flags.multiline_frame = this._previous_flags.multiline_frame || this._flags.multiline_frame;
  656. this._flags.multiline_frame = false;
  657. }
  658. }
  659. if (this._flags.last_token.type !== TOKEN.OPERATOR && this._flags.last_token.type !== TOKEN.START_EXPR) {
  660. if (this._flags.last_token.type === TOKEN.START_BLOCK && !this._flags.inline_frame) {
  661. this.print_newline();
  662. } else {
  663. this._output.space_before_token = true;
  664. }
  665. }
  666. }
  667. this.print_token(current_token);
  668. this.indent();
  669. // Except for specific cases, open braces are followed by a new line.
  670. if (!empty_braces && !(this._options.brace_preserve_inline && this._flags.inline_frame)) {
  671. this.print_newline();
  672. }
  673. };
  674. Beautifier.prototype.handle_end_block = function(current_token) {
  675. // statements must all be closed when their container closes
  676. this.handle_whitespace_and_comments(current_token);
  677. while (this._flags.mode === MODE.Statement) {
  678. this.restore_mode();
  679. }
  680. var empty_braces = this._flags.last_token.type === TOKEN.START_BLOCK;
  681. if (this._flags.inline_frame && !empty_braces) { // try inline_frame (only set if this._options.braces-preserve-inline) first
  682. this._output.space_before_token = true;
  683. } else if (this._options.brace_style === "expand") {
  684. if (!empty_braces) {
  685. this.print_newline();
  686. }
  687. } else {
  688. // skip {}
  689. if (!empty_braces) {
  690. if (is_array(this._flags.mode) && this._options.keep_array_indentation) {
  691. // we REALLY need a newline here, but newliner would skip that
  692. this._options.keep_array_indentation = false;
  693. this.print_newline();
  694. this._options.keep_array_indentation = true;
  695. } else {
  696. this.print_newline();
  697. }
  698. }
  699. }
  700. this.restore_mode();
  701. this.print_token(current_token);
  702. };
  703. Beautifier.prototype.handle_word = function(current_token) {
  704. if (current_token.type === TOKEN.RESERVED) {
  705. if (in_array(current_token.text, ['set', 'get']) && this._flags.mode !== MODE.ObjectLiteral) {
  706. current_token.type = TOKEN.WORD;
  707. } else if (current_token.text === 'import' && this._tokens.peek().text === '(') {
  708. current_token.type = TOKEN.WORD;
  709. } else if (in_array(current_token.text, ['as', 'from']) && !this._flags.import_block) {
  710. current_token.type = TOKEN.WORD;
  711. } else if (this._flags.mode === MODE.ObjectLiteral) {
  712. var next_token = this._tokens.peek();
  713. if (next_token.text === ':') {
  714. current_token.type = TOKEN.WORD;
  715. }
  716. }
  717. }
  718. if (this.start_of_statement(current_token)) {
  719. // The conditional starts the statement if appropriate.
  720. if (reserved_array(this._flags.last_token, ['var', 'let', 'const']) && current_token.type === TOKEN.WORD) {
  721. this._flags.declaration_statement = true;
  722. }
  723. } else if (current_token.newlines && !is_expression(this._flags.mode) &&
  724. (this._flags.last_token.type !== TOKEN.OPERATOR || (this._flags.last_token.text === '--' || this._flags.last_token.text === '++')) &&
  725. this._flags.last_token.type !== TOKEN.EQUALS &&
  726. (this._options.preserve_newlines || !reserved_array(this._flags.last_token, ['var', 'let', 'const', 'set', 'get']))) {
  727. this.handle_whitespace_and_comments(current_token);
  728. this.print_newline();
  729. } else {
  730. this.handle_whitespace_and_comments(current_token);
  731. }
  732. if (this._flags.do_block && !this._flags.do_while) {
  733. if (reserved_word(current_token, 'while')) {
  734. // do {} ## while ()
  735. this._output.space_before_token = true;
  736. this.print_token(current_token);
  737. this._output.space_before_token = true;
  738. this._flags.do_while = true;
  739. return;
  740. } else {
  741. // do {} should always have while as the next word.
  742. // if we don't see the expected while, recover
  743. this.print_newline();
  744. this._flags.do_block = false;
  745. }
  746. }
  747. // if may be followed by else, or not
  748. // Bare/inline ifs are tricky
  749. // Need to unwind the modes correctly: if (a) if (b) c(); else d(); else e();
  750. if (this._flags.if_block) {
  751. if (!this._flags.else_block && reserved_word(current_token, 'else')) {
  752. this._flags.else_block = true;
  753. } else {
  754. while (this._flags.mode === MODE.Statement) {
  755. this.restore_mode();
  756. }
  757. this._flags.if_block = false;
  758. this._flags.else_block = false;
  759. }
  760. }
  761. if (this._flags.in_case_statement && reserved_array(current_token, ['case', 'default'])) {
  762. this.print_newline();
  763. if (this._flags.last_token.type !== TOKEN.END_BLOCK && (this._flags.case_body || this._options.jslint_happy)) {
  764. // switch cases following one another
  765. this.deindent();
  766. }
  767. this._flags.case_body = false;
  768. this.print_token(current_token);
  769. this._flags.in_case = true;
  770. return;
  771. }
  772. if (this._flags.last_token.type === TOKEN.COMMA || this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.EQUALS || this._flags.last_token.type === TOKEN.OPERATOR) {
  773. if (!this.start_of_object_property()) {
  774. this.allow_wrap_or_preserved_newline(current_token);
  775. }
  776. }
  777. if (reserved_word(current_token, 'function')) {
  778. if (in_array(this._flags.last_token.text, ['}', ';']) ||
  779. (this._output.just_added_newline() && !(in_array(this._flags.last_token.text, ['(', '[', '{', ':', '=', ',']) || this._flags.last_token.type === TOKEN.OPERATOR))) {
  780. // make sure there is a nice clean space of at least one blank line
  781. // before a new function definition
  782. if (!this._output.just_added_blankline() && !current_token.comments_before) {
  783. this.print_newline();
  784. this.print_newline(true);
  785. }
  786. }
  787. if (this._flags.last_token.type === TOKEN.RESERVED || this._flags.last_token.type === TOKEN.WORD) {
  788. if (reserved_array(this._flags.last_token, ['get', 'set', 'new', 'export']) ||
  789. reserved_array(this._flags.last_token, newline_restricted_tokens)) {
  790. this._output.space_before_token = true;
  791. } else if (reserved_word(this._flags.last_token, 'default') && this._last_last_text === 'export') {
  792. this._output.space_before_token = true;
  793. } else if (this._flags.last_token.text === 'declare') {
  794. // accomodates Typescript declare function formatting
  795. this._output.space_before_token = true;
  796. } else {
  797. this.print_newline();
  798. }
  799. } else if (this._flags.last_token.type === TOKEN.OPERATOR || this._flags.last_token.text === '=') {
  800. // foo = function
  801. this._output.space_before_token = true;
  802. } else if (!this._flags.multiline_frame && (is_expression(this._flags.mode) || is_array(this._flags.mode))) {
  803. // (function
  804. } else {
  805. this.print_newline();
  806. }
  807. this.print_token(current_token);
  808. this._flags.last_word = current_token.text;
  809. return;
  810. }
  811. var prefix = 'NONE';
  812. if (this._flags.last_token.type === TOKEN.END_BLOCK) {
  813. if (this._previous_flags.inline_frame) {
  814. prefix = 'SPACE';
  815. } else if (!reserved_array(current_token, ['else', 'catch', 'finally', 'from'])) {
  816. prefix = 'NEWLINE';
  817. } else {
  818. if (this._options.brace_style === "expand" ||
  819. this._options.brace_style === "end-expand" ||
  820. (this._options.brace_style === "none" && current_token.newlines)) {
  821. prefix = 'NEWLINE';
  822. } else {
  823. prefix = 'SPACE';
  824. this._output.space_before_token = true;
  825. }
  826. }
  827. } else if (this._flags.last_token.type === TOKEN.SEMICOLON && this._flags.mode === MODE.BlockStatement) {
  828. // TODO: Should this be for STATEMENT as well?
  829. prefix = 'NEWLINE';
  830. } else if (this._flags.last_token.type === TOKEN.SEMICOLON && is_expression(this._flags.mode)) {
  831. prefix = 'SPACE';
  832. } else if (this._flags.last_token.type === TOKEN.STRING) {
  833. prefix = 'NEWLINE';
  834. } else if (this._flags.last_token.type === TOKEN.RESERVED || this._flags.last_token.type === TOKEN.WORD ||
  835. (this._flags.last_token.text === '*' &&
  836. (in_array(this._last_last_text, ['function', 'yield']) ||
  837. (this._flags.mode === MODE.ObjectLiteral && in_array(this._last_last_text, ['{', ',']))))) {
  838. prefix = 'SPACE';
  839. } else if (this._flags.last_token.type === TOKEN.START_BLOCK) {
  840. if (this._flags.inline_frame) {
  841. prefix = 'SPACE';
  842. } else {
  843. prefix = 'NEWLINE';
  844. }
  845. } else if (this._flags.last_token.type === TOKEN.END_EXPR) {
  846. this._output.space_before_token = true;
  847. prefix = 'NEWLINE';
  848. }
  849. if (reserved_array(current_token, line_starters) && this._flags.last_token.text !== ')') {
  850. if (this._flags.inline_frame || this._flags.last_token.text === 'else' || this._flags.last_token.text === 'export') {
  851. prefix = 'SPACE';
  852. } else {
  853. prefix = 'NEWLINE';
  854. }
  855. }
  856. if (reserved_array(current_token, ['else', 'catch', 'finally'])) {
  857. if ((!(this._flags.last_token.type === TOKEN.END_BLOCK && this._previous_flags.mode === MODE.BlockStatement) ||
  858. this._options.brace_style === "expand" ||
  859. this._options.brace_style === "end-expand" ||
  860. (this._options.brace_style === "none" && current_token.newlines)) &&
  861. !this._flags.inline_frame) {
  862. this.print_newline();
  863. } else {
  864. this._output.trim(true);
  865. var line = this._output.current_line;
  866. // If we trimmed and there's something other than a close block before us
  867. // put a newline back in. Handles '} // comment' scenario.
  868. if (line.last() !== '}') {
  869. this.print_newline();
  870. }
  871. this._output.space_before_token = true;
  872. }
  873. } else if (prefix === 'NEWLINE') {
  874. if (reserved_array(this._flags.last_token, special_words)) {
  875. // no newline between 'return nnn'
  876. this._output.space_before_token = true;
  877. } else if (this._flags.last_token.text === 'declare' && reserved_array(current_token, ['var', 'let', 'const'])) {
  878. // accomodates Typescript declare formatting
  879. this._output.space_before_token = true;
  880. } else if (this._flags.last_token.type !== TOKEN.END_EXPR) {
  881. if ((this._flags.last_token.type !== TOKEN.START_EXPR || !reserved_array(current_token, ['var', 'let', 'const'])) && this._flags.last_token.text !== ':') {
  882. // no need to force newline on 'var': for (var x = 0...)
  883. if (reserved_word(current_token, 'if') && reserved_word(current_token.previous, 'else')) {
  884. // no newline for } else if {
  885. this._output.space_before_token = true;
  886. } else {
  887. this.print_newline();
  888. }
  889. }
  890. } else if (reserved_array(current_token, line_starters) && this._flags.last_token.text !== ')') {
  891. this.print_newline();
  892. }
  893. } else if (this._flags.multiline_frame && is_array(this._flags.mode) && this._flags.last_token.text === ',' && this._last_last_text === '}') {
  894. this.print_newline(); // }, in lists get a newline treatment
  895. } else if (prefix === 'SPACE') {
  896. this._output.space_before_token = true;
  897. }
  898. if (current_token.previous && (current_token.previous.type === TOKEN.WORD || current_token.previous.type === TOKEN.RESERVED)) {
  899. this._output.space_before_token = true;
  900. }
  901. this.print_token(current_token);
  902. this._flags.last_word = current_token.text;
  903. if (current_token.type === TOKEN.RESERVED) {
  904. if (current_token.text === 'do') {
  905. this._flags.do_block = true;
  906. } else if (current_token.text === 'if') {
  907. this._flags.if_block = true;
  908. } else if (current_token.text === 'import') {
  909. this._flags.import_block = true;
  910. } else if (this._flags.import_block && reserved_word(current_token, 'from')) {
  911. this._flags.import_block = false;
  912. }
  913. }
  914. };
  915. Beautifier.prototype.handle_semicolon = function(current_token) {
  916. if (this.start_of_statement(current_token)) {
  917. // The conditional starts the statement if appropriate.
  918. // Semicolon can be the start (and end) of a statement
  919. this._output.space_before_token = false;
  920. } else {
  921. this.handle_whitespace_and_comments(current_token);
  922. }
  923. var next_token = this._tokens.peek();
  924. while (this._flags.mode === MODE.Statement &&
  925. !(this._flags.if_block && reserved_word(next_token, 'else')) &&
  926. !this._flags.do_block) {
  927. this.restore_mode();
  928. }
  929. // hacky but effective for the moment
  930. if (this._flags.import_block) {
  931. this._flags.import_block = false;
  932. }
  933. this.print_token(current_token);
  934. };
  935. Beautifier.prototype.handle_string = function(current_token) {
  936. if (this.start_of_statement(current_token)) {
  937. // The conditional starts the statement if appropriate.
  938. // One difference - strings want at least a space before
  939. this._output.space_before_token = true;
  940. } else {
  941. this.handle_whitespace_and_comments(current_token);
  942. if (this._flags.last_token.type === TOKEN.RESERVED || this._flags.last_token.type === TOKEN.WORD || this._flags.inline_frame) {
  943. this._output.space_before_token = true;
  944. } else if (this._flags.last_token.type === TOKEN.COMMA || this._flags.last_token.type === TOKEN.START_EXPR || this._flags.last_token.type === TOKEN.EQUALS || this._flags.last_token.type === TOKEN.OPERATOR) {
  945. if (!this.start_of_object_property()) {
  946. this.allow_wrap_or_preserved_newline(current_token);
  947. }
  948. } else {
  949. this.print_newline();
  950. }
  951. }
  952. this.print_token(current_token);
  953. };
  954. Beautifier.prototype.handle_equals = function(current_token) {
  955. if (this.start_of_statement(current_token)) {
  956. // The conditional starts the statement if appropriate.
  957. } else {
  958. this.handle_whitespace_and_comments(current_token);
  959. }
  960. if (this._flags.declaration_statement) {
  961. // just got an '=' in a var-line, different formatting/line-breaking, etc will now be done
  962. this._flags.declaration_assignment = true;
  963. }
  964. this._output.space_before_token = true;
  965. this.print_token(current_token);
  966. this._output.space_before_token = true;
  967. };
  968. Beautifier.prototype.handle_comma = function(current_token) {
  969. this.handle_whitespace_and_comments(current_token, true);
  970. this.print_token(current_token);
  971. this._output.space_before_token = true;
  972. if (this._flags.declaration_statement) {
  973. if (is_expression(this._flags.parent.mode)) {
  974. // do not break on comma, for(var a = 1, b = 2)
  975. this._flags.declaration_assignment = false;
  976. }
  977. if (this._flags.declaration_assignment) {
  978. this._flags.declaration_assignment = false;
  979. this.print_newline(false, true);
  980. } else if (this._options.comma_first) {
  981. // for comma-first, we want to allow a newline before the comma
  982. // to turn into a newline after the comma, which we will fixup later
  983. this.allow_wrap_or_preserved_newline(current_token);
  984. }
  985. } else if (this._flags.mode === MODE.ObjectLiteral ||
  986. (this._flags.mode === MODE.Statement && this._flags.parent.mode === MODE.ObjectLiteral)) {
  987. if (this._flags.mode === MODE.Statement) {
  988. this.restore_mode();
  989. }
  990. if (!this._flags.inline_frame) {
  991. this.print_newline();
  992. }
  993. } else if (this._options.comma_first) {
  994. // EXPR or DO_BLOCK
  995. // for comma-first, we want to allow a newline before the comma
  996. // to turn into a newline after the comma, which we will fixup later
  997. this.allow_wrap_or_preserved_newline(current_token);
  998. }
  999. };
  1000. Beautifier.prototype.handle_operator = function(current_token) {
  1001. var isGeneratorAsterisk = current_token.text === '*' &&
  1002. (reserved_array(this._flags.last_token, ['function', 'yield']) ||
  1003. (in_array(this._flags.last_token.type, [TOKEN.START_BLOCK, TOKEN.COMMA, TOKEN.END_BLOCK, TOKEN.SEMICOLON]))
  1004. );
  1005. var isUnary = in_array(current_token.text, ['-', '+']) && (
  1006. in_array(this._flags.last_token.type, [TOKEN.START_BLOCK, TOKEN.START_EXPR, TOKEN.EQUALS, TOKEN.OPERATOR]) ||
  1007. in_array(this._flags.last_token.text, line_starters) ||
  1008. this._flags.last_token.text === ','
  1009. );
  1010. if (this.start_of_statement(current_token)) {
  1011. // The conditional starts the statement if appropriate.
  1012. } else {
  1013. var preserve_statement_flags = !isGeneratorAsterisk;
  1014. this.handle_whitespace_and_comments(current_token, preserve_statement_flags);
  1015. }
  1016. if (reserved_array(this._flags.last_token, special_words)) {
  1017. // "return" had a special handling in TK_WORD. Now we need to return the favor
  1018. this._output.space_before_token = true;
  1019. this.print_token(current_token);
  1020. return;
  1021. }
  1022. // hack for actionscript's import .*;
  1023. if (current_token.text === '*' && this._flags.last_token.type === TOKEN.DOT) {
  1024. this.print_token(current_token);
  1025. return;
  1026. }
  1027. if (current_token.text === '::') {
  1028. // no spaces around exotic namespacing syntax operator
  1029. this.print_token(current_token);
  1030. return;
  1031. }
  1032. // Allow line wrapping between operators when operator_position is
  1033. // set to before or preserve
  1034. if (this._flags.last_token.type === TOKEN.OPERATOR && in_array(this._options.operator_position, OPERATOR_POSITION_BEFORE_OR_PRESERVE)) {
  1035. this.allow_wrap_or_preserved_newline(current_token);
  1036. }
  1037. if (current_token.text === ':' && this._flags.in_case) {
  1038. this.print_token(current_token);
  1039. this._flags.in_case = false;
  1040. this._flags.case_body = true;
  1041. if (this._tokens.peek().type !== TOKEN.START_BLOCK) {
  1042. this.indent();
  1043. this.print_newline();
  1044. } else {
  1045. this._output.space_before_token = true;
  1046. }
  1047. return;
  1048. }
  1049. var space_before = true;
  1050. var space_after = true;
  1051. var in_ternary = false;
  1052. if (current_token.text === ':') {
  1053. if (this._flags.ternary_depth === 0) {
  1054. // Colon is invalid javascript outside of ternary and object, but do our best to guess what was meant.
  1055. space_before = false;
  1056. } else {
  1057. this._flags.ternary_depth -= 1;
  1058. in_ternary = true;
  1059. }
  1060. } else if (current_token.text === '?') {
  1061. this._flags.ternary_depth += 1;
  1062. }
  1063. // let's handle the operator_position option prior to any conflicting logic
  1064. if (!isUnary && !isGeneratorAsterisk && this._options.preserve_newlines && in_array(current_token.text, positionable_operators)) {
  1065. var isColon = current_token.text === ':';
  1066. var isTernaryColon = (isColon && in_ternary);
  1067. var isOtherColon = (isColon && !in_ternary);
  1068. switch (this._options.operator_position) {
  1069. case OPERATOR_POSITION.before_newline:
  1070. // if the current token is : and it's not a ternary statement then we set space_before to false
  1071. this._output.space_before_token = !isOtherColon;
  1072. this.print_token(current_token);
  1073. if (!isColon || isTernaryColon) {
  1074. this.allow_wrap_or_preserved_newline(current_token);
  1075. }
  1076. this._output.space_before_token = true;
  1077. return;
  1078. case OPERATOR_POSITION.after_newline:
  1079. // if the current token is anything but colon, or (via deduction) it's a colon and in a ternary statement,
  1080. // then print a newline.
  1081. this._output.space_before_token = true;
  1082. if (!isColon || isTernaryColon) {
  1083. if (this._tokens.peek().newlines) {
  1084. this.print_newline(false, true);
  1085. } else {
  1086. this.allow_wrap_or_preserved_newline(current_token);
  1087. }
  1088. } else {
  1089. this._output.space_before_token = false;
  1090. }
  1091. this.print_token(current_token);
  1092. this._output.space_before_token = true;
  1093. return;
  1094. case OPERATOR_POSITION.preserve_newline:
  1095. if (!isOtherColon) {
  1096. this.allow_wrap_or_preserved_newline(current_token);
  1097. }
  1098. // if we just added a newline, or the current token is : and it's not a ternary statement,
  1099. // then we set space_before to false
  1100. space_before = !(this._output.just_added_newline() || isOtherColon);
  1101. this._output.space_before_token = space_before;
  1102. this.print_token(current_token);
  1103. this._output.space_before_token = true;
  1104. return;
  1105. }
  1106. }
  1107. if (isGeneratorAsterisk) {
  1108. this.allow_wrap_or_preserved_newline(current_token);
  1109. space_before = false;
  1110. var next_token = this._tokens.peek();
  1111. space_after = next_token && in_array(next_token.type, [TOKEN.WORD, TOKEN.RESERVED]);
  1112. } else if (current_token.text === '...') {
  1113. this.allow_wrap_or_preserved_newline(current_token);
  1114. space_before = this._flags.last_token.type === TOKEN.START_BLOCK;
  1115. space_after = false;
  1116. } else if (in_array(current_token.text, ['--', '++', '!', '~']) || isUnary) {
  1117. // unary operators (and binary +/- pretending to be unary) special cases
  1118. if (this._flags.last_token.type === TOKEN.COMMA || this._flags.last_token.type === TOKEN.START_EXPR) {
  1119. this.allow_wrap_or_preserved_newline(current_token);
  1120. }
  1121. space_before = false;
  1122. space_after = false;
  1123. // http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1
  1124. // if there is a newline between -- or ++ and anything else we should preserve it.
  1125. if (current_token.newlines && (current_token.text === '--' || current_token.text === '++')) {
  1126. this.print_newline(false, true);
  1127. }
  1128. if (this._flags.last_token.text === ';' && is_expression(this._flags.mode)) {
  1129. // for (;; ++i)
  1130. // ^^^
  1131. space_before = true;
  1132. }
  1133. if (this._flags.last_token.type === TOKEN.RESERVED) {
  1134. space_before = true;
  1135. } else if (this._flags.last_token.type === TOKEN.END_EXPR) {
  1136. space_before = !(this._flags.last_token.text === ']' && (current_token.text === '--' || current_token.text === '++'));
  1137. } else if (this._flags.last_token.type === TOKEN.OPERATOR) {
  1138. // a++ + ++b;
  1139. // a - -b
  1140. space_before = in_array(current_token.text, ['--', '-', '++', '+']) && in_array(this._flags.last_token.text, ['--', '-', '++', '+']);
  1141. // + and - are not unary when preceeded by -- or ++ operator
  1142. // a-- + b
  1143. // a * +b
  1144. // a - -b
  1145. if (in_array(current_token.text, ['+', '-']) && in_array(this._flags.last_token.text, ['--', '++'])) {
  1146. space_after = true;
  1147. }
  1148. }
  1149. if (((this._flags.mode === MODE.BlockStatement && !this._flags.inline_frame) || this._flags.mode === MODE.Statement) &&
  1150. (this._flags.last_token.text === '{' || this._flags.last_token.text === ';')) {
  1151. // { foo; --i }
  1152. // foo(); --bar;
  1153. this.print_newline();
  1154. }
  1155. }
  1156. this._output.space_before_token = this._output.space_before_token || space_before;
  1157. this.print_token(current_token);
  1158. this._output.space_before_token = space_after;
  1159. };
  1160. Beautifier.prototype.handle_block_comment = function(current_token, preserve_statement_flags) {
  1161. if (this._output.raw) {
  1162. this._output.add_raw_token(current_token);
  1163. if (current_token.directives && current_token.directives.preserve === 'end') {
  1164. // If we're testing the raw output behavior, do not allow a directive to turn it off.
  1165. this._output.raw = this._options.test_output_raw;
  1166. }
  1167. return;
  1168. }
  1169. if (current_token.directives) {
  1170. this.print_newline(false, preserve_statement_flags);
  1171. this.print_token(current_token);
  1172. if (current_token.directives.preserve === 'start') {
  1173. this._output.raw = true;
  1174. }
  1175. this.print_newline(false, true);
  1176. return;
  1177. }
  1178. // inline block
  1179. if (!acorn.newline.test(current_token.text) && !current_token.newlines) {
  1180. this._output.space_before_token = true;
  1181. this.print_token(current_token);
  1182. this._output.space_before_token = true;
  1183. return;
  1184. } else {
  1185. this.print_block_commment(current_token, preserve_statement_flags);
  1186. }
  1187. };
  1188. Beautifier.prototype.print_block_commment = function(current_token, preserve_statement_flags) {
  1189. var lines = split_linebreaks(current_token.text);
  1190. var j; // iterator for this case
  1191. var javadoc = false;
  1192. var starless = false;
  1193. var lastIndent = current_token.whitespace_before;
  1194. var lastIndentLength = lastIndent.length;
  1195. // block comment starts with a new line
  1196. this.print_newline(false, preserve_statement_flags);
  1197. // first line always indented
  1198. this.print_token_line_indentation(current_token);
  1199. this._output.add_token(lines[0]);
  1200. this.print_newline(false, preserve_statement_flags);
  1201. if (lines.length > 1) {
  1202. lines = lines.slice(1);
  1203. javadoc = all_lines_start_with(lines, '*');
  1204. starless = each_line_matches_indent(lines, lastIndent);
  1205. if (javadoc) {
  1206. this._flags.alignment = 1;
  1207. }
  1208. for (j = 0; j < lines.length; j++) {
  1209. if (javadoc) {
  1210. // javadoc: reformat and re-indent
  1211. this.print_token_line_indentation(current_token);
  1212. this._output.add_token(ltrim(lines[j]));
  1213. } else if (starless && lines[j]) {
  1214. // starless: re-indent non-empty content, avoiding trim
  1215. this.print_token_line_indentation(current_token);
  1216. this._output.add_token(lines[j].substring(lastIndentLength));
  1217. } else {
  1218. // normal comments output raw
  1219. this._output.current_line.set_indent(-1);
  1220. this._output.add_token(lines[j]);
  1221. }
  1222. // for comments on their own line or more than one line, make sure there's a new line after
  1223. this.print_newline(false, preserve_statement_flags);
  1224. }
  1225. this._flags.alignment = 0;
  1226. }
  1227. };
  1228. Beautifier.prototype.handle_comment = function(current_token, preserve_statement_flags) {
  1229. if (current_token.newlines) {
  1230. this.print_newline(false, preserve_statement_flags);
  1231. } else {
  1232. this._output.trim(true);
  1233. }
  1234. this._output.space_before_token = true;
  1235. this.print_token(current_token);
  1236. this.print_newline(false, preserve_statement_flags);
  1237. };
  1238. Beautifier.prototype.handle_dot = function(current_token) {
  1239. if (this.start_of_statement(current_token)) {
  1240. // The conditional starts the statement if appropriate.
  1241. } else {
  1242. this.handle_whitespace_and_comments(current_token, true);
  1243. }
  1244. if (reserved_array(this._flags.last_token, special_words)) {
  1245. this._output.space_before_token = false;
  1246. } else {
  1247. // allow preserved newlines before dots in general
  1248. // force newlines on dots after close paren when break_chained - for bar().baz()
  1249. this.allow_wrap_or_preserved_newline(current_token,
  1250. this._flags.last_token.text === ')' && this._options.break_chained_methods);
  1251. }
  1252. // Only unindent chained method dot if this dot starts a new line.
  1253. // Otherwise the automatic extra indentation removal will handle the over indent
  1254. if (this._options.unindent_chained_methods && this._output.just_added_newline()) {
  1255. this.deindent();
  1256. }
  1257. this.print_token(current_token);
  1258. };
  1259. Beautifier.prototype.handle_unknown = function(current_token, preserve_statement_flags) {
  1260. this.print_token(current_token);
  1261. if (current_token.text[current_token.text.length - 1] === '\n') {
  1262. this.print_newline(false, preserve_statement_flags);
  1263. }
  1264. };
  1265. Beautifier.prototype.handle_eof = function(current_token) {
  1266. // Unwind any open statements
  1267. while (this._flags.mode === MODE.Statement) {
  1268. this.restore_mode();
  1269. }
  1270. this.handle_whitespace_and_comments(current_token);
  1271. };
  1272. module.exports.Beautifier = Beautifier;