Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
await in list comprehension
  • Loading branch information
hydrogen602 committed May 21, 2024
commit 461a5112754b76b9c62b691f0386e743d1d68a8a
19 changes: 15 additions & 4 deletions compiler/codegen/src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2746,7 +2746,8 @@ impl Compiler {
compile_element: &dyn Fn(&mut Self) -> CompileResult<()>,
) -> CompileResult<()> {
let prev_ctx = self.ctx;
let is_async = generators.iter().any(|g| g.is_async);
let is_async_gen = generators.iter().any(|g| g.is_async);
let is_async = is_async_gen || prev_ctx.func == FunctionContext::AsyncFunction;

self.ctx = CompileContext {
loop_data: None,
Expand Down Expand Up @@ -2838,7 +2839,7 @@ impl Compiler {

// End of for loop:
self.switch_to_block(after_block);
if is_async {
if is_async_gen {
emit!(self, Instruction::EndAsyncFor);
}
}
Expand Down Expand Up @@ -2877,19 +2878,29 @@ impl Compiler {
self.compile_expression(&generators[0].iter)?;

// Get iterator / turn item into an iterator
if is_async {
if is_async_gen {
emit!(self, Instruction::GetAIter);
} else {
emit!(self, Instruction::GetIter);
};

// Call just created <listcomp> function:
emit!(self, Instruction::CallFunctionPositional { nargs: 1 });
if is_async {
if is_async_gen {
emit!(self, Instruction::GetAwaitable);
self.emit_load_const(ConstantData::None);
emit!(self, Instruction::YieldFrom);
}

if !is_async_gen && is_async {
// async, but not a generator
// in this case, we end up with an awaitable
// that evaluates to the list, so here we add an await
emit!(self, Instruction::GetAwaitable);
self.emit_load_const(ConstantData::None);
emit!(self, Instruction::YieldFrom);
}

Ok(())
}

Expand Down
16 changes: 16 additions & 0 deletions extra_tests/snippets/async_list_comprehension.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import asyncio

def echo(value):
return value

async def async_echo(value):
return value

async def async_in_async():
return [await async_echo(a) for a in range(5)]

async def sync_in_async():
return [echo(a) for a in range(5)]

assert asyncio.run(async_in_async()) == [0, 1, 2, 3, 4]
assert asyncio.run(sync_in_async()) == [0, 1, 2, 3, 4]