From f603ca4688b499a8ba8336502b07833d6cdb46ee Mon Sep 17 00:00:00 2001 From: Christopher Chedeau Date: Mon, 16 Jan 2017 09:54:39 -0800 Subject: [PATCH] Make sure empty for loops generate valid code (#224) ```js for (;;); function f() {} ``` The `;` was dropped meaning that the line right after was executed within the for loop which is not correct. I tried to return `;` but it looks like ```js for (;;) ; ``` which looks super weird so I ended up printing `{}` which looks like ```js for (;;) {} ``` --- src/printer.js | 8 +++++-- .../__snapshots__/jsfmt.spec.js.snap | 21 +++++++++++++++++++ tests/empty_statement/body.js | 7 +++++++ tests/empty_statement/jsfmt.spec.js | 1 + 4 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 tests/empty_statement/__snapshots__/jsfmt.spec.js.snap create mode 100644 tests/empty_statement/body.js create mode 100644 tests/empty_statement/jsfmt.spec.js diff --git a/src/printer.js b/src/printer.js index 62b5d7df..0bdd19e9 100644 --- a/src/printer.js +++ b/src/printer.js @@ -799,8 +799,8 @@ function genericPrintNoParens(path, options, print) { return concat([ "with (", path.call(print, "object"), - ") ", - path.call(print, "body") + ")", + adjustClause(path.call(print, "body"), options) ]); case "IfStatement": const con = adjustClause(path.call(print, "consequent"), options); @@ -2111,6 +2111,10 @@ function printJSXElement(path, options, print) { } function adjustClause(clause, options, forceSpace) { + if (clause === "") { + return ";"; + } + if (isCurlyBracket(clause) || forceSpace) { return concat([ " ", clause ]); } diff --git a/tests/empty_statement/__snapshots__/jsfmt.spec.js.snap b/tests/empty_statement/__snapshots__/jsfmt.spec.js.snap new file mode 100644 index 00000000..db47c9da --- /dev/null +++ b/tests/empty_statement/__snapshots__/jsfmt.spec.js.snap @@ -0,0 +1,21 @@ +exports[`test body.js 1`] = ` +"with (a); +if (1); else if (2); else; +for (;;); +while (1); +for (var i in o); +for (var i of o); +do; while(1); +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +with (a); +if (1); +else if (2); +else; +for (;;); +while (1); +for (var i in o); +for (var i of o); +do; +while (1); +" +`; diff --git a/tests/empty_statement/body.js b/tests/empty_statement/body.js new file mode 100644 index 00000000..85c9f5b7 --- /dev/null +++ b/tests/empty_statement/body.js @@ -0,0 +1,7 @@ +with (a); +if (1); else if (2); else; +for (;;); +while (1); +for (var i in o); +for (var i of o); +do; while(1); diff --git a/tests/empty_statement/jsfmt.spec.js b/tests/empty_statement/jsfmt.spec.js new file mode 100644 index 00000000..989047bc --- /dev/null +++ b/tests/empty_statement/jsfmt.spec.js @@ -0,0 +1 @@ +run_spec(__dirname);