Skip to content
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

Definition and reading of variables #22

Merged
merged 1 commit into from
Feb 25, 2024
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
10 changes: 8 additions & 2 deletions src/ast/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,14 @@ pub enum ExprType {
Variable(Name),
}

#[derive(Debug)]
pub struct Name(pub String);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Name(String);

impl Name {
pub fn new(s: String) -> Self {
Name(s)
}
}

impl Display for Name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Expand Down
2 changes: 1 addition & 1 deletion src/ast/stmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ impl Stmt {
src: Arc<NamedSource<String>>,
) -> Self {
Stmt {
stmt_type: StmtType::Var(Name(name), expr),
stmt_type: StmtType::Var(Name::new(name), expr),
src,
location,
}
Expand Down
49 changes: 49 additions & 0 deletions src/interpreter/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,53 @@ impl Environment {
values: HashMap::new(),
}
}

pub fn define(&mut self, key: Name, value: Value) {
self.values.insert(key, value);
}

pub fn get(&self, key: &Name) -> Option<Value> {
self.values.get(key).cloned()
}

pub fn assign(&mut self, key: Name, value: Value)-> Option<()> {
self.values.get_mut(&key).map(|old| *old = value)
}
}

#[cfg(test)]
mod environment_tests {
use crate::{ast::expr::Name, value::Value};

use super::Environment;

#[test]
fn define_get() {
let mut env = Environment::new();
let name = Name::new("x".to_string());
env.define(name.clone(), Value::Boolean(true));
let returned = env.get(&name);
assert_eq!(returned, Some(Value::Boolean(true)))
}

#[test]
fn define_assign_get() {
let mut env = Environment::new();
let name = Name::new("x".to_string());
env.define(name.clone(), Value::Boolean(true));
let assigned = env.assign(name.clone(), Value::Boolean(false));
assert_eq!(assigned, Some(()));
let returned = env.get(&name);
assert_eq!(returned, Some(Value::Boolean(false)))
}

#[test]
fn assign_unasigned() {
let mut env = Environment::new();
let name = Name::new("x".to_string());
let assigned = env.assign(name.clone(), Value::Boolean(false));
assert_eq!(assigned, None);
let returned = env.get(&name);
assert_eq!(returned, None)
}
}
54 changes: 37 additions & 17 deletions src/interpreter/expression.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,35 @@
use crate::{
ast::expr::{Expr, ExprType},
ast::token::{Token, TokenType},
ast::{
expr::{Expr, ExprType, Name},
token::{Token, TokenType},
},
types::Type,
value::Value,
};

use super::{literal::LiteralInterpreter, runtime_error::RuntimeError::*};
use super::{Interpreter, Result};
pub trait ExprInterpreter {
fn interpret_expr(&mut self, expr: &Expr) -> Result<Value>;
}

impl ExprInterpreter for Interpreter {
fn interpret_expr(&mut self, expr: &Expr) -> Result<Value> {
impl Interpreter {
pub fn interpret_expr(&mut self, expr: &Expr) -> Result<Value> {
match &expr.expr_type {
ExprType::Binary(left, token, right) => self.interpret_binary(left, token, right),
ExprType::Grouping(expr) => self.interpret_expr(expr),
ExprType::Literal(l) => l.interpret(),
ExprType::Unary(token, expr) => self.interpret_unary(token, expr),
ExprType::Variable(name) => todo!(),
ExprType::Variable(name) => self.read_variable(name, expr),
}
}
}

impl Interpreter {
fn read_variable(&self, name: &Name, expr: &Expr) -> Result<Value> {
let val = self.environment.get(name);
val.ok_or(UndefinedVariable {
name: name.clone(),
src: expr.src.clone(),
location: expr.location,
})
}

fn is_truthy(value: Value) -> bool {
match value {
Value::Boolean(bool) => bool,
Expand Down Expand Up @@ -151,9 +157,11 @@ mod value_interpreter_tests {
ast::{
expr::{Expr, Literal},
token::{Token, TokenType},
}, interpreter::{
expression::ExprInterpreter, runtime_error::RuntimeError::*, Interpreter,
}, printer::vec_printer::VecPrinter, types::Type, value::Value
},
interpreter::{runtime_error::RuntimeError::*, Interpreter},
printer::vec_printer::VecPrinter,
types::Type,
value::Value,
};

#[test]
Expand All @@ -174,21 +182,30 @@ mod value_interpreter_tests {
let expr = literal(1.0.into());
let expr = Expr::unary(token(TokenType::Bang), expr);
let mut under_test = Interpreter::new(Box::new(VecPrinter::new()));
assert_matches!(under_test.interpret_expr(&expr).unwrap(), Value::Boolean(false));
assert_matches!(
under_test.interpret_expr(&expr).unwrap(),
Value::Boolean(false)
);
}
#[test]
fn bang_false() {
let expr = literal(Literal::Boolean(false));
let expr = Expr::unary(token(TokenType::Bang), expr);
let mut under_test = Interpreter::new(Box::new(VecPrinter::new()));
assert_matches!(under_test.interpret_expr(&expr).unwrap(), Value::Boolean(true));
assert_matches!(
under_test.interpret_expr(&expr).unwrap(),
Value::Boolean(true)
);
}
#[test]
fn bang_nil() {
let expr = literal(Literal::Nil);
let expr = Expr::unary(token(TokenType::Bang), expr);
let mut under_test = Interpreter::new(Box::new(VecPrinter::new()));
assert_matches!(under_test.interpret_expr(&expr).unwrap(), Value::Boolean(true));
assert_matches!(
under_test.interpret_expr(&expr).unwrap(),
Value::Boolean(true)
);
}
#[test]
fn five_minus_one() {
Expand Down Expand Up @@ -222,7 +239,10 @@ mod value_interpreter_tests {
let operator = token(TokenType::EqualEqual);
let expr = Expr::binary(left, operator, right);
let mut under_test = Interpreter::new(Box::new(VecPrinter::new()));
assert_matches!(under_test.interpret_expr(&expr).unwrap(), Value::Boolean(false));
assert_matches!(
under_test.interpret_expr(&expr).unwrap(),
Value::Boolean(false)
);
}
#[test]
fn string_minus_one() {
Expand Down
2 changes: 1 addition & 1 deletion src/interpreter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ mod statement;

use crate::{ast::stmt::Stmt, printer::Printer};

use self::{environment::Environment, runtime_error::RuntimeError, statement::StmtInterpreter};
use self::{environment::Environment, runtime_error::RuntimeError};

type Result<T> = std::result::Result<T, RuntimeError>;
pub struct Interpreter {
Expand Down
11 changes: 10 additions & 1 deletion src/interpreter/runtime_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::sync::Arc;

use miette::{Diagnostic, NamedSource, SourceSpan};

use crate::types::Type;
use crate::{ast::expr::Name, types::Type};

#[derive(thiserror::Error, Debug, Diagnostic)]
pub enum RuntimeError {
Expand Down Expand Up @@ -49,4 +49,13 @@ pub enum RuntimeError {
#[label("{actual_rhs}")]
rhs: SourceSpan,
},

#[error("Undefined variable '{name}'")]
UndefinedVariable {
name: Name,
#[source_code]
src: Arc<NamedSource<String>>,
#[label("here")]
location: SourceSpan,
},
}
23 changes: 12 additions & 11 deletions src/interpreter/statement.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
use crate::ast::stmt::{Stmt, StmtType};
use crate::{ast::{expr::{Expr, Name}, stmt::{Stmt, StmtType}}, value::Value};

use super::expression::ExprInterpreter;
use super::{Interpreter, Result};

pub trait StmtInterpreter {
fn interpret_stmt(&mut self, statement: Stmt) -> Result<()>;
}

impl StmtInterpreter for Interpreter {
fn interpret_stmt(&mut self, statement: Stmt) -> Result<()> {
impl Interpreter {
pub fn interpret_stmt(&mut self, statement: Stmt) -> Result<()> {
match statement.stmt_type {
StmtType::Expression(expr) => self.interpret_expr(&expr).map(|_| ()),
StmtType::Print(expr) => self
.interpret_expr(&expr)
.map(|value| self.printer.print(value)),
StmtType::Var(_, _) => todo!(),
StmtType::Var(key, initializer) => self.define_var(key, initializer),
}
}

fn define_var(&mut self, key: Name, initializer: Option<Expr>) -> Result<()> {
let initializer = initializer.map_or(Ok(Value::Nil),|expr| self.interpret_expr(&expr))?;
self.environment.define(key, initializer);
Ok(())
}
}
#[cfg(test)]
mod stmt_interpreter_tests {
Expand All @@ -25,11 +26,11 @@ mod stmt_interpreter_tests {

use crate::{
ast::{
expr::{Expr, Literal},
expr::{Expr, Literal, Name},
stmt::Stmt,
token::{Token, TokenType},
},
interpreter::{statement::StmtInterpreter, Interpreter},
interpreter::Interpreter,
printer::vec_printer::VecPrinter,
};

Expand Down
11 changes: 11 additions & 0 deletions src/lox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,15 @@ mod lox_tests {
lox.run_stdin(r#"print "string";"#.to_string()).unwrap();
assert_eq!(printer.get_lines(), vec!["string".to_string().into()])
}

#[test]
fn print_variable() {
let printer = VecPrinter::new();
let mut lox = Lox::new(Box::new(printer.clone()));
lox.run_stdin(r#"
var x = "string";
print "x=" + x;
"#.to_string()).unwrap();
assert_eq!(printer.get_lines(), vec!["x=string".to_string().into()])
}
}
Loading