Skip to content

fix invalid break continue return yield #542

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Feb 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
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
35 changes: 28 additions & 7 deletions vm/src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ struct Compiler {
source_path: Option<String>,
current_source_location: ast::Location,
in_loop: bool,
in_function_def: bool,
}

/// Compile a given sourcecode into a bytecode object.
Expand Down Expand Up @@ -75,6 +76,7 @@ impl Compiler {
source_path: None,
current_source_location: ast::Location::default(),
in_loop: false,
in_function_def: false,
}
}

Expand Down Expand Up @@ -232,9 +234,10 @@ impl Compiler {

self.compile_test(test, None, Some(else_label), EvalContext::Statement)?;

let was_in_loop = self.in_loop;
self.in_loop = true;
self.compile_statements(body)?;
self.in_loop = false;
self.in_loop = was_in_loop;
self.emit(Instruction::Jump {
target: start_label,
});
Expand Down Expand Up @@ -295,10 +298,10 @@ impl Compiler {
// Start of loop iteration, set targets:
self.compile_store(target)?;

// Body of loop:
let was_in_loop = self.in_loop;
self.in_loop = true;
self.compile_statements(body)?;
self.in_loop = false;
self.in_loop = was_in_loop;

self.emit(Instruction::Jump {
target: start_label,
Expand Down Expand Up @@ -431,6 +434,11 @@ impl Compiler {
decorator_list,
} => {
// Create bytecode for this function:
// remember to restore self.in_loop to the original after the function is compiled
let was_in_loop = self.in_loop;
let was_in_function_def = self.in_function_def;
self.in_loop = false;
self.in_function_def = true;
let flags = self.enter_function(name, args)?;
self.compile_statements(body)?;

Expand Down Expand Up @@ -458,6 +466,8 @@ impl Compiler {
self.emit(Instruction::StoreName {
name: name.to_string(),
});
self.in_loop = was_in_loop;
self.in_function_def = was_in_function_def;
}
ast::Statement::ClassDef {
name,
Expand All @@ -466,6 +476,8 @@ impl Compiler {
keywords,
decorator_list,
} => {
let was_in_loop = self.in_loop;
self.in_loop = false;
self.prepare_decorators(decorator_list)?;
self.emit(Instruction::LoadBuildClass);
let line_number = self.get_source_line_number();
Expand Down Expand Up @@ -546,6 +558,7 @@ impl Compiler {
self.emit(Instruction::StoreName {
name: name.to_string(),
});
self.in_loop = was_in_loop;
}
ast::Statement::Assert { test, msg } => {
// TODO: if some flag, ignore all assert statements!
Expand Down Expand Up @@ -584,6 +597,9 @@ impl Compiler {
self.emit(Instruction::Continue);
}
ast::Statement::Return { value } => {
if !self.in_function_def {
return Err(CompileError::InvalidReturn);
}
match value {
Some(e) => {
let size = e.len();
Expand Down Expand Up @@ -663,7 +679,6 @@ impl Compiler {
name: &str,
args: &ast::Parameters,
) -> Result<bytecode::FunctionOpArg, CompileError> {
self.in_loop = false;
let have_kwargs = !args.defaults.is_empty();
if have_kwargs {
// Construct a tuple:
Expand Down Expand Up @@ -971,6 +986,9 @@ impl Compiler {
self.emit(Instruction::BuildSlice { size });
}
ast::Expression::Yield { value } => {
if !self.in_function_def {
return Err(CompileError::InvalidYield);
}
self.mark_generator();
match value {
Some(expression) => self.compile_expression(expression)?,
Expand Down Expand Up @@ -1021,6 +1039,7 @@ impl Compiler {
}
ast::Expression::Lambda { args, body } => {
let name = "<lambda>".to_string();
// no need to worry about the self.loop_depth because there are no loops in lambda expressions
let flags = self.enter_function(&name, args)?;
self.compile_expression(body)?;
self.emit(Instruction::ReturnValue);
Expand Down Expand Up @@ -1362,10 +1381,11 @@ impl Compiler {

// Low level helper functions:
fn emit(&mut self, instruction: Instruction) {
self.current_code_object().instructions.push(instruction);
// TODO: insert source filename
let location = self.current_source_location.clone();
self.current_code_object().locations.push(location);
let mut cur_code_obj = self.current_code_object();
cur_code_obj.instructions.push(instruction);
cur_code_obj.locations.push(location);
// TODO: insert source filename
}

fn current_code_object(&mut self) -> &mut CodeObject {
Expand Down Expand Up @@ -1406,6 +1426,7 @@ mod tests {
use crate::bytecode::Constant::*;
use crate::bytecode::Instruction::*;
use rustpython_parser::parser;

fn compile_exec(source: &str) -> CodeObject {
let mut compiler = Compiler::new();
compiler.source_path = Some("source_path".to_string());
Expand Down
8 changes: 6 additions & 2 deletions vm/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ pub enum CompileError {
InvalidBreak,
/// Continue statement outside of loop.
InvalidContinue,
InvalidReturn,
InvalidYield,
}

impl fmt::Display for CompileError {
Expand All @@ -29,8 +31,10 @@ impl fmt::Display for CompileError {
CompileError::ExpectExpr => write!(f, "Expecting expression, got statement"),
CompileError::Parse(err) => write!(f, "{}", err),
CompileError::StarArgs => write!(f, "Two starred expressions in assignment"),
CompileError::InvalidBreak => write!(f, "break outside loop"),
CompileError::InvalidContinue => write!(f, "continue outside loop"),
CompileError::InvalidBreak => write!(f, "'break' outside loop"),
CompileError::InvalidContinue => write!(f, "'continue' outside loop"),
CompileError::InvalidReturn => write!(f, "'return' outside function"),
CompileError::InvalidYield => write!(f, "'yield' outside function"),
}
}
}
Expand Down