Skip to content

Commit 37a7e6d

Browse files
committed
Parse 'return' correctly if followed by newline
The following snippet should be interpreted as two statements, but quick-lint-js interprets them as one: return x; Fix quick-lint-js to respec da rules.
1 parent 0db79c9 commit 37a7e6d

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

src/quick-lint-js/parse.h

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -394,8 +394,12 @@ class parser {
394394
break;
395395

396396
default:
397-
this->parse_and_visit_expression(v);
398-
parse_expression_end();
397+
if (this->peek().has_leading_newline) {
398+
// Insert a semicolon, then consume it.
399+
} else {
400+
this->parse_and_visit_expression(v);
401+
parse_expression_end();
402+
}
399403
break;
400404
}
401405
break;

test/test-parse-statement.cpp

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,35 @@ TEST(test_parse, return_statement) {
8686
}
8787
}
8888

89+
TEST(test_parse, return_statement_disallows_newline) {
90+
{
91+
padded_string code(u8"return\nx"_sv);
92+
spy_visitor v;
93+
parser p(&code, &v);
94+
95+
// Parse 'return'.
96+
EXPECT_TRUE(p.parse_and_visit_statement(v));
97+
EXPECT_THAT(v.variable_uses, IsEmpty());
98+
99+
// Parse 'x' (separate statement from 'return')
100+
EXPECT_TRUE(p.parse_and_visit_statement(v));
101+
EXPECT_THAT(v.variable_uses,
102+
ElementsAre(spy_visitor::visited_variable_use{u8"x"}));
103+
104+
EXPECT_THAT(v.errors, IsEmpty());
105+
}
106+
107+
{
108+
spy_visitor v = parse_and_visit_module(u8"for (let x of []) return\nx"_sv);
109+
EXPECT_THAT(v.visits,
110+
ElementsAre("visit_enter_for_scope", //
111+
"visit_variable_declaration", // x
112+
"visit_exit_for_scope", //
113+
"visit_variable_use", // x
114+
"visit_end_of_module"));
115+
}
116+
}
117+
89118
TEST(test_parse, throw_statement) {
90119
{
91120
spy_visitor v = parse_and_visit_statement(u8"throw new Error('ouch');"_sv);

0 commit comments

Comments
 (0)