Skip to content

Commit

Permalink
Fix once_cell version and refactor Boolean struct
Browse files Browse the repository at this point in the history
  • Loading branch information
DaviRain-Su committed Oct 10, 2023
1 parent b0f2c3d commit d9d5f76
Show file tree
Hide file tree
Showing 10 changed files with 53 additions and 41 deletions.
5 changes: 3 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ global = "0.4.3"
string-join = "0.1.2" # for String join
thiserror = "1.0.49"
nom = "7.1.3"
once_cell = "1.18.0"
39 changes: 15 additions & 24 deletions src/evaluator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,7 @@ pub fn eval(node: Node, env: &mut Environment) -> anyhow::Result<Object> {
Expression::IdentifierExpression(identifier) => {
eval_identifier(identifier.clone(), env)
}
Expression::BooleanExpression(boolean) => Ok(Boolean {
value: boolean.value(),
}
.into()),
Expression::BooleanExpression(boolean) => Ok(Boolean::new(boolean.value()).into()),
Expression::IfExpression(if_exp) => eval_if_expression(if_exp.clone(), env),
Expression::FunctionLiteral(function) => {
let params = function.parameters.clone();
Expand Down Expand Up @@ -236,10 +233,10 @@ fn eval_infix_expression(operator: String, left: Object, right: Object) -> anyho
eval_integer_infix_expression(operator, left_value, right_value)
}
(Object::Boolean(left_value), Object::Boolean(right_value)) if operator == "==" => Ok(
native_bool_to_boolean_object(left_value.value == right_value.value),
native_bool_to_boolean_object(left_value.value() == right_value.value()),
),
(Object::Boolean(left_value), Object::Boolean(right_value)) if operator == "!=" => Ok(
native_bool_to_boolean_object(left_value.value != right_value.value),
native_bool_to_boolean_object(left_value.value() != right_value.value()),
),
(Object::String(left), Object::String(right)) => {
eval_string_infix_expression(operator, left, right)
Expand Down Expand Up @@ -269,19 +266,13 @@ fn eval_string_infix_expression(
let left_val = left.value;
let right_val = right.value;

Ok(Boolean {
value: left_val == right_val,
}
.into())
Ok(Boolean::new(left_val == right_val).into())
}
"!=" => {
let left_val = left.value;
let right_val = right.value;

Ok(Boolean {
value: left_val != right_val,
}
.into())
Ok(Boolean::new(left_val != right_val).into())
}
_ => Err(Error::UnknownOperator {
left: left.r#type().to_string(),
Expand All @@ -296,21 +287,21 @@ fn eval_string_infix_expression(
fn eval_bang_operator_expression(right: Object) -> anyhow::Result<Object> {
match right {
Object::Boolean(value) => {
if value.value {
Ok(FALSE.into())
if value.value() {
Ok((*FALSE).into())
} else {
Ok(TRUE.into())
Ok((*TRUE).into())
}
}
Object::Integer(value) => {
if value.value != 0 {
Ok(FALSE.into())
Ok((*FALSE).into())
} else {
Ok(TRUE.into())
Ok((*TRUE).into())
}
}
Object::Null(_) => Ok(TRUE.into()),
_ => Ok(FALSE.into()),
Object::Null(_) => Ok((*TRUE).into()),
_ => Ok((*FALSE).into()),
}
}

Expand Down Expand Up @@ -401,9 +392,9 @@ fn eval_array_index_expression(left: Object, index: Object) -> anyhow::Result<Ob

fn native_bool_to_boolean_object(input: bool) -> Object {
if input {
TRUE.into()
(*TRUE).into()
} else {
FALSE.into()
(*FALSE).into()
}
}

Expand All @@ -422,7 +413,7 @@ fn eval_if_expression(ie: IfExpression, env: &mut Environment) -> anyhow::Result
fn is_truthy(obj: Object) -> anyhow::Result<bool> {
match obj {
Object::Boolean(boolean) => {
if boolean.value {
if boolean.value() {
Ok(true)
} else {
Ok(false)
Expand Down
17 changes: 9 additions & 8 deletions src/evaluator/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,10 +222,11 @@ fn test_boolean_object(obj: Object, expected: bool) -> anyhow::Result<bool> {
let value = Boolean::try_from(obj);
match value {
Ok(boolean) => {
if boolean.value != expected {
if boolean.value() != expected {
eprintln!(
"object has wrong value. got = {:?}, want = {:?}",
boolean.value, expected
boolean.value(),
expected
);
Ok(false)
} else {
Expand Down Expand Up @@ -639,10 +640,10 @@ fn test_string_not_equal() -> anyhow::Result<()> {
let evaluated = test_eval(input.to_string())?;
let bool_str = Boolean::try_from(evaluated)?;

if !bool_str.value {
if !bool_str.value() {
return Err(anyhow::anyhow!(format!(
"Boolean has wrong value. got = {}",
bool_str.value
bool_str.value()
)));
}

Expand All @@ -655,10 +656,10 @@ fn test_string_equal() -> anyhow::Result<()> {
let evaluated = test_eval(input.to_string())?;
let bool_str = Boolean::try_from(evaluated)?;

if !bool_str.value {
if !bool_str.value() {
return Err(anyhow::anyhow!(format!(
"Boolean has wrong value. got = {}",
bool_str.value
bool_str.value()
)));
}

Expand Down Expand Up @@ -878,8 +879,8 @@ let two = "two";
3,
);
expected.insert(Object::Integer(Integer { value: 4 }), 4);
expected.insert(Object::Boolean(TRUE), 5);
expected.insert(Object::Boolean(FALSE), 6);
expected.insert(Object::Boolean(TRUE.clone()), 5);
expected.insert(Object::Boolean(FALSE.clone()), 6);

if result.pairs.len() != expected.len() {
eprintln!("hash has wrong num of paris. got={}", result.pairs.len());
Expand Down
5 changes: 3 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#[macro_use]
extern crate lazy_static;
extern crate core;
use once_cell::sync::Lazy;

use std::io;

Expand All @@ -14,8 +15,8 @@ pub mod repl;
pub mod token;

static NULL: object::null::Null = object::null::Null;
static TRUE: object::boolean::Boolean = object::boolean::Boolean { value: true };
static FALSE: object::boolean::Boolean = object::boolean::Boolean { value: false };
static TRUE: Lazy<object::boolean::Boolean> = Lazy::new(|| object::boolean::Boolean::new(true));
static FALSE: Lazy<object::boolean::Boolean> = Lazy::new(|| object::boolean::Boolean::new(false));

fn main() -> anyhow::Result<()> {
env_logger::init();
Expand Down
2 changes: 1 addition & 1 deletion src/object/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ impl Display for Array {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut elements = vec![];
for e in self.elements.iter() {
elements.push(format!("{}", *e));
elements.push(e.to_string());
}

write!(f, "[{}]", ",".join(elements))
Expand Down
12 changes: 11 additions & 1 deletion src/object/boolean.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,17 @@ use std::fmt::{Display, Formatter};

#[derive(Debug, Clone, Copy, PartialOrd, PartialEq, Eq, Ord, Hash)]
pub struct Boolean {
pub value: bool,
value: bool,
}

impl Boolean {
pub fn new(value: bool) -> Self {
Self { value }
}

pub fn value(&self) -> bool {
self.value
}
}

impl ObjectInterface for Boolean {
Expand Down
2 changes: 1 addition & 1 deletion src/object/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl Display for Function {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut params = vec![];
for p in self.parameters.iter() {
params.push(format!("{p}"));
params.push(p.to_string());
}
write!(f, "fn")?;
write!(f, "(")?;
Expand Down
5 changes: 5 additions & 0 deletions src/object/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ impl From<Boolean> for Object {
}
}

impl From<once_cell::sync::Lazy<Boolean>> for Object {
fn from(value: once_cell::sync::Lazy<Boolean>) -> Self {
Self::Boolean(*value)
}
}
impl From<Integer> for Object {
fn from(integer: Integer) -> Self {
Self::Integer(integer)
Expand Down
6 changes: 4 additions & 2 deletions src/object/null.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ use std::fmt::{Display, Formatter};
#[derive(Debug, Clone, Copy, PartialOrd, PartialEq, Eq, Ord, Hash)]
pub struct Null;

const NULL: &str = "null";

impl Display for Null {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "null")
write!(f, "{}", NULL)
}
}

Expand All @@ -28,7 +30,7 @@ impl ObjectInterface for Null {
}

fn inspect(&self) -> String {
"null".to_string()
NULL.to_string()
}

fn as_any(&self) -> &dyn Any {
Expand Down

0 comments on commit d9d5f76

Please sign in to comment.