From 12e74be43bc3e07fa47692bb9f1d45581b8d3789 Mon Sep 17 00:00:00 2001 From: Mradul Singh Date: Fri, 13 Nov 2026 06:41:52 +0530 Subject: [PATCH] JS: a semicolon after a newline still ends the statement parseStmt only consumed a trailing `;` when no line terminator came before it, so in `if (a) b\n; else c` and `do a()\n; while (b)` the `;` became an empty statement and the `else` / `while` failed to parse. ASI only inserts a semicolon when the next token is not allowed, so for statements that end with a semicolon (expression, var, return, break, continue, throw, debugger, do-while) the `;` is their terminator. Blocks and other statements keep the old behaviour (`{}\n;` is still a block and an empty statement). --- js/ast_test.go | 9 +++++++++ js/parse.go | 11 ++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/js/ast_test.go b/js/ast_test.go index b756b70..a88fb3e 100644 --- a/js/ast_test.go +++ b/js/ast_test.go @@ -120,6 +120,15 @@ func TestJS(t *testing.T) { {"async\n()", "async();"}, {"{};;", "{} ;"}, {"{}\n;", "{} ;"}, + {"if(a)b\n;else c", "if (a) b; else c;"}, + {"if(a)var b=1\n;else c", "if (a) var b = 1; else c;"}, + {"if(a)debugger\n;else c", "if (a) debugger; else c;"}, + {"if(a)throw b\n;else c", "if (a) throw b; else c;"}, + {"for(;;)if(a)break\n;else continue\n;", "for ( ; ; ) { if (a) break; else continue; }"}, + {"function f(){if(a)return\n;else c}", "function f() { if (a) return; else c; }"}, + {"do a()\n;while(b)", "do a(); while (b);"}, + {"if(a)do;while(b)\n;else c", "if (a) do; while (b); else c;"}, + {"a\n;\n;", "a; ;"}, {"- - --3", "- - --3;"}, {"([,,])=>P", "([,,]) => { return P; };"}, {"(t)=>{//!\n}", "(t) => { //! };"}, // space after //! is newline diff --git a/js/parse.go b/js/parse.go index 01e2eca..215a2ca 100644 --- a/js/parse.go +++ b/js/parse.go @@ -646,13 +646,22 @@ func (p *Parser) parseStmt(allowDeclaration bool) (stmt IStmt) { } } } - if !p.prevLT && p.tt == SemicolonToken { + if p.tt == SemicolonToken && (!p.prevLT || endsWithSemicolon(stmt)) { p.next() } p.stmtLevel-- return } +// endsWithSemicolon returns true for statements that are terminated by a semicolon. ASI only inserts a semicolon when the next token is not allowed, so a semicolon after a line terminator still ends these statements and is not an empty statement. +func endsWithSemicolon(stmt IStmt) bool { + switch stmt.(type) { + case *ExprStmt, *VarDecl, *DoWhileStmt, *BranchStmt, *ReturnStmt, *ThrowStmt, *DebuggerStmt, *DirectivePrologueStmt: + return true + } + return false +} + func (p *Parser) parseStmtList(in string) (list []IStmt) { comments := len(p.comments) if !p.consume(in, OpenBraceToken) {