Skip to content

Commit 5b3895d

Browse files
dlarocquestrager
authored andcommitted
feat: error on 'for await' in non-async function
Added diagnostic when a 'for await' statement is in a non-async function, since this statement can only be used in contexts where 'await' can be used. closes #1137
1 parent 4c2d145 commit 5b3895d

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/quick-lint-js/fe/parse-statement.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3999,6 +3999,15 @@ void Parser::parse_and_visit_for(Parse_Visitor_Base &v) {
39993999

40004000
bool is_for_await = this->peek().type == Token_Type::kw_await;
40014001
if (is_for_await) {
4002+
if (this->in_top_level_) {
4003+
// TODO: Emit a diagnostic if the top level await mode does not allow
4004+
// await operators (Parser_Top_Level_Await_Mode::no_await_operator).
4005+
} else {
4006+
if (!this->in_async_function_) {
4007+
this->diag_reporter_->report(
4008+
Diag_Await_Operator_Outside_Async{this->peek().span()});
4009+
}
4010+
}
40024011
this->skip();
40034012
}
40044013

test/test-parse-statement.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1307,6 +1307,23 @@ TEST_F(Test_Parse_Statement, if_body_with_semicolon_typescript) {
13071307
test_parse_and_visit_statement(u8"if (a) {} else;\n"_sv, no_diags,
13081308
typescript_options);
13091309
}
1310+
1311+
TEST_F(Test_Parse_Statement, disallow_for_await_in_non_async_function) {
1312+
Spy_Visitor p = test_parse_and_visit_statement(
1313+
u8"function f() { for await (let x of []) {} }"_sv, //
1314+
u8" ^^^^^ Diag_Await_Operator_Outside_Async"_diag);
1315+
EXPECT_THAT(p.visits, ElementsAreArray({
1316+
"visit_enter_function_scope", //
1317+
"visit_enter_function_scope_body", //
1318+
"visit_enter_for_scope", //
1319+
"visit_variable_declaration", // x
1320+
"visit_enter_block_scope", //
1321+
"visit_exit_block_scope", //
1322+
"visit_exit_for_scope", //
1323+
"visit_exit_function_scope", //
1324+
"visit_variable_declaration", //
1325+
}));
1326+
}
13101327
}
13111328
}
13121329

0 commit comments

Comments
 (0)