Skip to content

Commit 862830d

Browse files
committed
compile: Give a proper error on 'async with'/'async for' outside 'async def'
A simple reproducer is: async for x in():x
1 parent 511c180 commit 862830d

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

py/compile.c

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1711,6 +1711,16 @@ STATIC void compile_yield_from(compiler_t *comp) {
17111711
}
17121712

17131713
#if MICROPY_PY_ASYNC_AWAIT
1714+
STATIC bool compile_require_async_context(compiler_t *comp, mp_parse_node_struct_t *pns) {
1715+
int scope_flags = comp->scope_cur->scope_flags;
1716+
if(scope_flags & MP_SCOPE_FLAG_GENERATOR) {
1717+
return true;
1718+
}
1719+
compile_syntax_error(comp, (mp_parse_node_t)pns,
1720+
translate("'async for' or 'async with' outside async function"));
1721+
return false;
1722+
}
1723+
17141724
STATIC void compile_await_object_method(compiler_t *comp, qstr method) {
17151725
EMIT_ARG(load_method, method, false);
17161726
EMIT_ARG(call_method, 0, 0, 0);
@@ -1720,6 +1730,10 @@ STATIC void compile_await_object_method(compiler_t *comp, qstr method) {
17201730
STATIC void compile_async_for_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
17211731
// comp->break_label |= MP_EMIT_BREAK_FROM_FOR;
17221732

1733+
if(!compile_require_async_context(comp, pns)) {
1734+
return;
1735+
}
1736+
17231737
qstr context = MP_PARSE_NODE_LEAF_ARG(pns->nodes[1]);
17241738
uint while_else_label = comp_next_label(comp);
17251739
uint try_exception_label = comp_next_label(comp);
@@ -1857,6 +1871,9 @@ STATIC void compile_async_with_stmt_helper(compiler_t *comp, int n, mp_parse_nod
18571871
}
18581872

18591873
STATIC void compile_async_with_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
1874+
if(!compile_require_async_context(comp, pns)) {
1875+
return;
1876+
}
18601877
// get the nodes for the pre-bit of the with (the a as b, c as d, ... bit)
18611878
mp_parse_node_t *nodes;
18621879
int n = mp_parse_node_extract_list(&pns->nodes[0], PN_with_stmt_list, &nodes);

0 commit comments

Comments
 (0)