compile_single checks last expr out of loop

This commit is contained in:
Jeong Yunwon 2022-05-02 01:51:30 +09:00
parent b53f647e57
commit 753c0337bc

View file

@ -337,31 +337,30 @@ impl Compiler {
) -> CompileResult<()> { ) -> CompileResult<()> {
self.symbol_table_stack.push(symbol_table); self.symbol_table_stack.push(symbol_table);
let mut emitted_return = false; let (last, body) = if let Some(splited) = body.split_last() {
splited
for (i, statement) in body.iter().enumerate() { } else {
let is_last = i == body.len() - 1; return Ok(());
};
for statement in body {
if let ast::StmtKind::Expr { value } = &statement.node { if let ast::StmtKind::Expr { value } = &statement.node {
self.compile_expression(value)?; self.compile_expression(value)?;
self.emit(Instruction::PrintExpr);
if is_last {
self.emit(Instruction::Duplicate);
self.emit(Instruction::PrintExpr);
self.emit(Instruction::ReturnValue);
emitted_return = true;
} else {
self.emit(Instruction::PrintExpr);
}
} else { } else {
self.compile_statement(statement)?; self.compile_statement(statement)?;
} }
} }
if !emitted_return { if let ast::StmtKind::Expr { value } = &last.node {
self.compile_expression(value)?;
self.emit(Instruction::Duplicate);
self.emit(Instruction::PrintExpr);
} else {
self.compile_statement(last)?;
self.emit_constant(ConstantData::None); self.emit_constant(ConstantData::None);
self.emit(Instruction::ReturnValue);
} }
self.emit(Instruction::ReturnValue);
Ok(()) Ok(())
} }