Skip to content

Commit 62b2be9

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 f1cc68e commit 62b2be9

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
@@ -11121,14 +11121,16 @@ impl<'warnings> Compiler<'warnings> {
1112111121
// Genexpr creation has already left the acquired iterator on the stack.
1112211122
if comprehension_type != ComprehensionType::Generator {
1112311123
emit!(self, Instruction::LoadFast { var_num: arg0 });
11124+
// BUILD_LIST_FROM_ARG keeps the iterable on top, under which
11125+
// GET_ITER pushes the iterator and its index slot.
11126+
if use_build_list_from_arg {
11127+
emit!(self, Instruction::BuildListFromArg);
11128+
}
1112411129
if generator.is_async {
1112511130
emit!(self, Instruction::GetAiter);
1112611131
} else {
1112711132
emit!(self, Instruction::GetIter { mode: 0 });
1112811133
}
11129-
if use_build_list_from_arg {
11130-
emit!(self, Instruction::BuildListFromArg);
11131-
}
1113211134
}
1113311135
} else {
1113411136
// Evaluate iterated item:
@@ -18025,6 +18027,34 @@ def f(self):
1802518027
] {
1802618028
assert_eq!(has(source, true), (false, true), "source={source:?}");
1802718029
}
18030+
18031+
// Non-inlined path: a type alias in a class body can see class scope,
18032+
// so the list comprehension is compiled as its own code object.
18033+
let code = compile_exec_with_options(
18034+
"\
18035+
class C:
18036+
type A = [i for i in range(3)]
18037+
",
18038+
CompileOpts {
18039+
build_list_from_arg: true,
18040+
..CompileOpts::default()
18041+
},
18042+
);
18043+
let listcomp = find_code(&code, "<listcomp>").expect("missing non-inlined listcomp");
18044+
let build_idx = listcomp
18045+
.instructions
18046+
.iter()
18047+
.position(|unit| matches!(unit.op, Instruction::BuildListFromArg))
18048+
.expect("missing BUILD_LIST_FROM_ARG");
18049+
let next = listcomp.instructions[build_idx + 1..]
18050+
.iter()
18051+
.find(|unit| !matches!(unit.op, Instruction::Cache))
18052+
.expect("missing instruction after BUILD_LIST_FROM_ARG");
18053+
assert!(
18054+
matches!(next.op, Instruction::GetIter { .. }),
18055+
"BUILD_LIST_FROM_ARG must precede GET_ITER, got instructions={:?}",
18056+
listcomp.instructions
18057+
);
1802818058
}
1802918059

1803018060
#[test]

0 commit comments

Comments
 (0)