Skip to content

Commit

Permalink
supports executing var decl
Browse files Browse the repository at this point in the history
  • Loading branch information
xffxff committed Sep 24, 2023
1 parent 87a9f29 commit 31f96f7
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 4 deletions.
15 changes: 13 additions & 2 deletions components/lox-execute/src/vm.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::HashMap;

use lox_ir::bytecode;

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -118,6 +120,9 @@ pub struct VM {
ip: usize,

pub stack: Vec<Value>,

// global variables
globals: HashMap<String, Value>,
}

impl VM {
Expand All @@ -126,6 +131,7 @@ impl VM {
chunk,
ip: 0,
stack: Vec::new(),
globals: HashMap::new(),
}
}

Expand Down Expand Up @@ -217,8 +223,13 @@ impl VM {
// FIXME: This should be a call to a intrinsic function.
println!("{:?}", value);
},
bytecode::Code::VarDeclaration(_) => todo!(),
bytecode::Code::Nil => todo!(),
bytecode::Code::VarDeclaration(name) => {
let value = self.pop();
self.globals.insert(name, value);
},
bytecode::Code::Nil => {
self.push(Value::Nil);
},
}
if let Some(step_inspect) = &mut step_inspect {
step_inspect(instruction, self);
Expand Down
3 changes: 2 additions & 1 deletion lox_tests/var.lox
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
var a = 1;
var a = 1;
var b;
4 changes: 4 additions & 0 deletions lox_tests/var/bytecode
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,9 @@ Chunk {
VarDeclaration(
"a",
),
Nil,
VarDeclaration(
"b",
),
],
}
26 changes: 26 additions & 0 deletions lox_tests/var/execute
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
execute: Constant(
F64(
1.0,
),
)
stack: [
Number(
1.0,
),
]

execute: VarDeclaration(
"a",
)
stack: []

execute: Nil
stack: [
Nil,
]

execute: VarDeclaration(
"b",
)
stack: []

4 changes: 4 additions & 0 deletions lox_tests/var/syntax
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,7 @@ Var {
NumberLiteral(1),
),
}
Var {
name: "b",
initializer: None,
}
7 changes: 6 additions & 1 deletion lox_tests/var/token
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
TokenTree {
source text: "var a = 1;",
source text: "var a = 1;\nvar b;",
tokens: [
Alphabetic(var),
Whitespace(' '),
Expand All @@ -9,5 +9,10 @@ TokenTree {
Whitespace(' '),
Number(1),
Semicolon,
Whitespace('\n'),
Alphabetic(var),
Whitespace(' '),
Alphabetic(b),
Semicolon,
],
}

0 comments on commit 31f96f7

Please sign in to comment.