From cf0f4fc0b91edf81c8c8d046a57c7b4122aac858 Mon Sep 17 00:00:00 2001 From: Teascade Date: Wed, 24 Jun 2020 17:37:53 +0300 Subject: [PATCH] Made some neatment updates --- src/compiler.rs | 6 +----- src/errors.rs | 1 + src/vm.rs | 35 ++++++++++++++++++++++++++++++++--- 3 files changed, 34 insertions(+), 8 deletions(-) diff --git a/src/compiler.rs b/src/compiler.rs index 8592efe..9738544 100644 --- a/src/compiler.rs +++ b/src/compiler.rs @@ -2,6 +2,7 @@ use std::collections::HashMap; use super::errors::CompilerError; use super::parser::{Expression, LiteralPattern, ParsedReid, Pattern, Position, Statement}; +use super::vm::VariableType; type Variable = (HeapID, VariableType); pub type HeapID = usize; @@ -19,11 +20,6 @@ pub enum Command { StringLit(String), // Bring String Literal to Stack } -#[derive(Debug, Copy, Clone)] -pub enum VariableType { - TypeString, -} - pub struct Compiler { parsed: ParsedReid, root_scope: Scope, diff --git a/src/errors.rs b/src/errors.rs index c4d6da1..2008982 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -108,4 +108,5 @@ pub enum RuntimePanic { RegistryNotDefined, InvalidHeapAddress, ValueNotInitialized, + InvalidTypeAssign, } diff --git a/src/vm.rs b/src/vm.rs index 4dbbfef..689082d 100644 --- a/src/vm.rs +++ b/src/vm.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; -use super::compiler::{Command, CompiledReid, HeapID, VariableType}; +use super::compiler::{Command, CompiledReid, HeapID}; use super::errors::RuntimePanic; pub struct VirtualMachine { @@ -103,7 +103,7 @@ impl VirtualMachine { Command::AssignVariable(heapid, regid) => { if let Some(reg) = &self.registry[regid] { if let Some(var) = self.heap.get_mut(&heapid) { - var.1 = Some(reg.clone()); + var.try_set(Some(reg.clone()))?; dbg!("Variable assigned", heapid, regid, &self.heap); Ok(()) } else { @@ -142,7 +142,36 @@ impl VirtualMachine { #[derive(Clone, Debug)] struct AllocatedVar(VariableType, Option); -#[derive(Clone, Debug)] +impl AllocatedVar { + fn try_set(&mut self, new_val: Option) -> Result<(), RuntimePanic> { + if let Some(val) = new_val { + if val.get_type() == self.0 { + self.1 = Some(val); + Ok(()) + } else { + Err(RuntimePanic::InvalidTypeAssign) + } + } else { + self.1 = None; + Ok(()) + } + } +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub enum VariableType { + TypeString, +} + +#[derive(Clone, Debug, PartialEq, Eq)] enum Value { StringVal(String), } + +impl Value { + fn get_type(&self) -> VariableType { + match self { + Value::StringVal(_) => VariableType::TypeString, + } + } +}