From 93a074bda91ab704e7a1de8299d84c275eb938e7 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Fri, 19 Aug 2022 14:57:13 -0700 Subject: [PATCH] 14.5.3 --- rust/src/chunk.rs | 25 +++++++++++++++++++------ rust/src/main.rs | 6 +++++- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/rust/src/chunk.rs b/rust/src/chunk.rs index 44d1e9f..df29583 100644 --- a/rust/src/chunk.rs +++ b/rust/src/chunk.rs @@ -1,12 +1,13 @@ #[repr(u8)] pub enum OpCode { + Constant, Return, } type Value = f32; pub struct Chunk { - code: Vec, + code: Vec, constants: Vec, } @@ -19,13 +20,16 @@ impl Chunk { } // https://doc.rust-lang.org/nomicon/vec/vec-push-pop.html - pub fn write(&mut self, op_code: OpCode) { - self.code.push(op_code); + pub fn write(&mut self, byte: u8) { + self.code.push(byte); } - pub fn add_constant(&mut self, value: Value) -> usize{ + pub fn add_constant(&mut self, value: Value) -> u8 { self.constants.push(value); - self.constants.len() - 1 + + assert!(self.constants.len() <= u8::MAX.into(), "Too many constants"); + + (self.constants.len() - 1) as u8 } pub fn disassemble(&self, name: &str) { @@ -41,7 +45,9 @@ impl Chunk { print!("{:04} ", offset); match self.code[offset] { - OpCode::Return => self.simple_instruction("OP_RETURN", offset), + 0 => self.constant_instruction("OP_CONSTANT", offset), + 1 => self.simple_instruction("OP_RETURN", offset), + _ => unreachable!(), } } @@ -49,6 +55,13 @@ impl Chunk { println!("{}", name); offset + 1 } + + fn constant_instruction(&self, name: &str, offset: usize) -> usize { + let constant_index = self.code[offset+1]; + let value = self.constants[constant_index as usize]; + println!("{:<16} {:04} '{}'", name, constant_index, value); + offset + 2 + } } impl Default for Chunk { diff --git a/rust/src/main.rs b/rust/src/main.rs index f1a76d2..fe15590 100644 --- a/rust/src/main.rs +++ b/rust/src/main.rs @@ -5,7 +5,11 @@ pub mod vec; fn main() { let mut chunk = Chunk::default(); - chunk.write(OpCode::Return); + chunk.write(OpCode::Return as u8); + + let constant = chunk.add_constant(1.2); + chunk.write(OpCode::Constant as u8); + chunk.write(constant); chunk.disassemble("test chunk"); }