Skip to content

Commit 04f3ae6

Browse files
committed
Emit BUILD_LIST_FROM_ARG before GET_ITER in a non-inlined list comprehension
GET_ITER pushes the iterator and an index slot, so BUILD_LIST_FROM_ARG after it took the index slot. The non-inlined path now emits LOAD_FAST .0; BUILD_LIST_FROM_ARG; GET_ITER, leaving [list, iterator, index] as the inlined path does. listcomp_build_list_from_arg_option covers the non-inlined case. Assisted-by: Grok Assisted-by: Claude
1 parent 9f6a743 commit 04f3ae6

1 file changed

Lines changed: 33 additions & 3 deletions

File tree

‎crates/codegen/src/compile.rs‎

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11117,14 +11117,16 @@ impl<'warnings> Compiler<'warnings> {
1111711117
// Genexpr creation has already left the acquired iterator on the stack.
1111811118
if comprehension_type != ComprehensionType::Generator {
1111911119
emit!(self, Instruction::LoadFast { var_num: arg0 });
11120+
// BUILD_LIST_FROM_ARG keeps the iterable on top, under which
11121+
// GET_ITER pushes the iterator and its index slot.
11122+
if use_build_list_from_arg {
11123+
emit!(self, Instruction::BuildListFromArg);
11124+
}
1112011125
if generator.is_async {
1112111126
emit!(self, Instruction::GetAiter);
1112211127
} else {
1112311128
emit!(self, Instruction::GetIter { mode: 0 });
1112411129
}
11125-
if use_build_list_from_arg {
11126-
emit!(self, Instruction::BuildListFromArg);
11127-
}
1112811130
}
1112911131
} else {
1113011132
// Evaluate iterated item:
@@ -18021,6 +18023,34 @@ def f(self):
1802118023
] {
1802218024
assert_eq!(has(source, true), (false, true), "source={source:?}");
1802318025
}
18026+
18027+
// Non-inlined path: a type alias in a class body can see class scope,
18028+
// so the list comprehension is compiled as its own code object.
18029+
let code = compile_exec_with_options(
18030+
"\
18031+
class C:
18032+
type A = [i for i in range(3)]
18033+
",
18034+
CompileOpts {
18035+
build_list_from_arg: true,
18036+
..CompileOpts::default()
18037+
},
18038+
);
18039+
let listcomp = find_code(&code, "<listcomp>").expect("missing non-inlined listcomp");
18040+
let build_idx = listcomp
18041+
.instructions
18042+
.iter()
18043+
.position(|unit| matches!(unit.op, Instruction::BuildListFromArg))
18044+
.expect("missing BUILD_LIST_FROM_ARG");
18045+
let next = listcomp.instructions[build_idx + 1..]
18046+
.iter()
18047+
.find(|unit| !matches!(unit.op, Instruction::Cache))
18048+
.expect("missing instruction after BUILD_LIST_FROM_ARG");
18049+
assert!(
18050+
matches!(next.op, Instruction::GetIter { .. }),
18051+
"BUILD_LIST_FROM_ARG must precede GET_ITER, got instructions={:?}",
18052+
listcomp.instructions
18053+
);
1802418054
}
1802518055

1802618056
#[test]

0 commit comments

Comments
 (0)