From db68a431299cd8862a2f9ec25468b2eb7a5ab6e9 Mon Sep 17 00:00:00 2001 From: SarthakDudhe Date: Mon, 4 May 2026 17:09:29 +0530 Subject: [PATCH] Fix: correctly restore statement mode for unary operators on new line (#1896) --- js/src/javascript/beautifier.js | 18 +++++++++++------- test/data/javascript/tests.js | 10 +++++++--- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/js/src/javascript/beautifier.js b/js/src/javascript/beautifier.js index 37350c225..3d8a8c02f 100644 --- a/js/src/javascript/beautifier.js +++ b/js/src/javascript/beautifier.js @@ -1159,7 +1159,17 @@ Beautifier.prototype.handle_operator = function(current_token) { // The conditional starts the statement if appropriate. } else { var preserve_statement_flags = !isGeneratorAsterisk; + var is_prefix_operator = current_token.newlines && in_array(current_token.text, ['--', '++', '~', '!']) && + !is_expression(this._flags.mode) && + (this._flags.last_token.type !== TOKEN.OPERATOR || (this._flags.last_token.text === '--' || this._flags.last_token.text === '++')) && + this._flags.last_token.type !== TOKEN.EQUALS; + if (is_prefix_operator) { + preserve_statement_flags = false; + } this.handle_whitespace_and_comments(current_token, preserve_statement_flags); + if (is_prefix_operator) { + this.print_newline(false, false); + } } // hack for actionscript's import .*; @@ -1294,13 +1304,7 @@ Beautifier.prototype.handle_operator = function(current_token) { // http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1 // if there is a newline between -- or ++ and anything else we should preserve it. - if (current_token.newlines && (current_token.text === '--' || current_token.text === '++' || current_token.text === '~')) { - var new_line_needed = reserved_array(this._flags.last_token, special_words) && current_token.newlines; - if (new_line_needed && (this._previous_flags.if_block || this._previous_flags.else_block)) { - this.restore_mode(); - } - this.print_newline(new_line_needed, true); - } + if (this._flags.last_token.text === ';' && is_expression(this._flags.mode)) { // for (;; ++i) diff --git a/test/data/javascript/tests.js b/test/data/javascript/tests.js index c37efdcb4..23e5c6fc0 100644 --- a/test/data/javascript/tests.js +++ b/test/data/javascript/tests.js @@ -5887,9 +5887,13 @@ exports.test_data = { { input: 'var a={bing:1},b=2,c=3;', output: 'var a = {\n bing: 1\n },\n b = 2,\n c = 3;' }, { - comment: 'Issue #1896: Handle newlines with bitwise ~ operator', - input: 'if (foo) {\nvar bar = 1;\n~bar ? 0 : 1\n }', - output: 'if (foo) {\n var bar = 1;\n ~bar ? 0 : 1\n}' + comment: 'Issue #1896: Handle newlines with bitwise ~ and ! operators', + input: 'if (foo) {\nvar bar = 1\n~bar ? 0 : 1\n }', + output: 'if (foo) {\n var bar = 1\n ~bar ? 0 : 1\n}' + }, + { + input: 'if (foo) {\nvar bar = 1\n!bar ? 0 : 1\n }', + output: 'if (foo) {\n var bar = 1\n !bar ? 0 : 1\n}' }, {