Skip to content

Commit

Permalink
optimize code execution by not cloning instructions
Browse files Browse the repository at this point in the history
 - convert instructions into a reference counted object
 - fix disassembly formatting
  • Loading branch information
binoyjayan committed Sep 30, 2023
1 parent 9393952 commit 6d39f42
Show file tree
Hide file tree
Showing 5 changed files with 9 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/code/definitions.rs
Expand Up @@ -167,7 +167,7 @@ impl Instructions {
#[allow(dead_code)]
pub fn disassemble(&self) {
println!(
"--------- Instructions [len: {:<4} --------------------",
"--------- Instructions [len: {:<4}] -------------------",
self.len(),
);
print!("{}", self);
Expand Down
4 changes: 2 additions & 2 deletions src/common/object.rs
Expand Up @@ -302,15 +302,15 @@ impl Eq for HMap {}
// OpReturn is similar to OpReturnValue except that it returns Nil.
#[derive(Debug, Clone, Default)]
pub struct CompiledFunction {
pub instructions: Instructions,
pub instructions: Rc<Instructions>,
pub num_locals: usize,
pub num_params: usize,
}

impl CompiledFunction {
pub fn new(instructions: Instructions, num_locals: usize, num_params: usize) -> Self {
Self {
instructions,
instructions: Rc::new(instructions),
num_locals,
num_params,
}
Expand Down
2 changes: 1 addition & 1 deletion src/compiler/mod.rs
Expand Up @@ -122,7 +122,7 @@ impl Compiler {
fn print_constants(&self) {
let constants = self.constants.clone();
println!(
"----------- Constants [len: {:<4} ---------------------",
"----------- Constants [len: {:<4}] --------------------",
constants.len(),
);

Expand Down
5 changes: 4 additions & 1 deletion src/compiler/tests.rs
Expand Up @@ -92,7 +92,10 @@ fn test_string_object(actual: &Object, expected: &str) {
#[cfg(test)]
fn test_function_object(actual_obj: &Object, expected: &CompiledFunction) {
if let Object::CompiledFunc(actual) = actual_obj {
test_instructions(&vec![expected.instructions.clone()], &actual.instructions);
test_instructions(
&vec![(&*expected.instructions).clone()],
&actual.instructions,
);
} else {
panic!("object is not a compiled function. got={:?}", actual_obj);
}
Expand Down
2 changes: 1 addition & 1 deletion src/vm/frame.rs
Expand Up @@ -15,7 +15,7 @@ impl Frame {
Frame { closure, ip: 0, bp }
}

pub fn instructions(&self) -> &Instructions {
pub fn instructions(&self) -> &Rc<Instructions> {
&self.closure.func.instructions
}
}

0 comments on commit 6d39f42

Please sign in to comment.