Skip to content

Commit

Permalink
feat: error on 'for await' in non-async function
Browse files Browse the repository at this point in the history
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
  • Loading branch information
dlarocque committed Jan 5, 2024
1 parent 2343088 commit cae93d8
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
6 changes: 6 additions & 0 deletions src/quick-lint-js/fe/parse-statement.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3998,6 +3998,12 @@ void Parser::parse_and_visit_for(Parse_Visitor_Base &v) {

bool is_for_await = this->peek().type == Token_Type::kw_await;
if (is_for_await) {
Source_Code_Span await_token_span = this->peek().span();
if (!this->in_async_function_) {
this->diag_reporter_->report(Diag_Await_Operator_Outside_Async{
await_token_span
});
}
this->skip();
}

Expand Down
3 changes: 2 additions & 1 deletion test/test-parse-loop.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -893,7 +893,8 @@ TEST_F(Test_Parse_Loop, for_of_loop) {

{
Spy_Visitor p = test_parse_and_visit_statement(
u8"for await (let x of xs) { body; }"_sv, no_diags, javascript_options);
u8"for await (let x of xs) { body; }"_sv, //
u8" ^^^^^ Diag_Await_Operator_Outside_Async"_diag);
EXPECT_THAT(p.visits, ElementsAreArray({
"visit_enter_for_scope", //
"visit_variable_use", //
Expand Down
18 changes: 18 additions & 0 deletions test/test-parse-statement.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1312,6 +1312,24 @@ TEST_F(Test_Parse_Statement, if_body_with_semicolon_typescript) {
EXPECT_THAT(p.errors, IsEmpty());
}
}

TEST_F(Test_Parse_Statement,
disallow_for_await_in_non_async_function) {
Spy_Visitor p = test_parse_and_visit_statement(
u8"function f() { for await (let x of []) {} }"_sv, //
u8" ^^^^^ Diag_Await_Operator_Outside_Async"_diag);
EXPECT_THAT(p.visits, ElementsAreArray({
"visit_enter_function_scope", //
"visit_enter_function_scope_body", //
"visit_enter_for_scope", //
"visit_variable_declaration", // x
"visit_enter_block_scope", //
"visit_exit_block_scope", //
"visit_exit_for_scope", //
"visit_exit_function_scope", //
"visit_variable_declaration", //
}));
}
}
}

Expand Down

0 comments on commit cae93d8

Please sign in to comment.