diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index cef312459fa..81349c2f078 100644 --- a/crates/codegen/src/compile.rs +++ b/crates/codegen/src/compile.rs @@ -2499,8 +2499,12 @@ impl Compiler { if let Some(last_statement) = body.last() { match last_statement { - ast::Stmt::Expr(_) => { - self.current_block().instructions.pop(); // pop Instruction::PopTop + ast::Stmt::Expr(ast::StmtExpr { value, .. }) => { + if !self.interactive && Self::is_const_expression(value) { + self.compile_expression(value)?; + } else { + self.current_block().instructions.pop(); // pop Instruction::PopTop + } } ast::Stmt::FunctionDef(_) | ast::Stmt::ClassDef(_) => { let pop_instructions = self.current_block().instructions.pop(); diff --git a/crates/vm/src/vm/python_run.rs b/crates/vm/src/vm/python_run.rs index 26000b5e11f..126bac4fd06 100644 --- a/crates/vm/src/vm/python_run.rs +++ b/crates/vm/src/vm/python_run.rs @@ -174,3 +174,35 @@ mod file_run { Ok(crate::import::check_pyc_magic_number_bytes(&buf)) } } + +#[cfg(test)] +mod tests { + use rustpython_vm::Interpreter; + + fn interpreter() -> Interpreter { + Interpreter::without_stdlib(Default::default()) + } + + #[test] + fn test_block_expr_return_const() { + interpreter().enter(|vm| { + let scope = vm.new_scope_with_builtins(); + let value = vm.unwrap_pyresult(vm.run_block_expr(scope, "1")); + let value = vm.unwrap_pyresult(value.try_int(vm)); + let value: u32 = vm.unwrap_pyresult(value.try_to_primitive(vm)); + assert_eq!(value, 1); + }) + } + + #[test] + fn test_block_expr_return_nonconst() { + interpreter().enter(|vm| { + let scope = vm.new_scope_with_builtins(); + vm.unwrap_pyresult(scope.globals.set_item("x", vm.new_pyobj(3), vm)); + let value = vm.unwrap_pyresult(vm.run_block_expr(scope, "2 + x")); + let value = vm.unwrap_pyresult(value.try_int(vm)); + let value: u32 = vm.unwrap_pyresult(value.try_to_primitive(vm)); + assert_eq!(value, 5); + }) + } +}