Skip to content

Commit

Permalink
fixing parsing and eval pure constant, writing a test for it
Browse files Browse the repository at this point in the history
  • Loading branch information
dzhibas committed Feb 16, 2024
1 parent 2d48c2c commit 489226e
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "bool_expr_parser_nom"
version = "0.2.3"
version = "0.2.4"
edition = "2021"
authors = ["Nikolajus Krauklis <[email protected]>"]

Expand Down
25 changes: 25 additions & 0 deletions src/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,19 @@ use crate::ast::{AstNode, Atom, ComparisonOp};
pub fn eval<'a>(expr: &AstNode, context: &HashMap<&str, Atom>) -> Result<bool, &'a str> {
let mut result = false;
result = match expr {
AstNode::Constant(var) => {
let mut result = false;
if let Atom::Boolean(v) = var {
result = *v;
}
if let Atom::Variable(v) = var {
let context_val = context.get(v.as_str());
if let Some(Atom::Boolean(inner)) = context_val {
result = *inner;
}
}
result
}
AstNode::Compare(var, op, val) => {
// check var in context
// compare with val
Expand Down Expand Up @@ -90,6 +103,18 @@ mod tests {
);
}

#[test]
fn simple_constant_eval_test() {
assert_eq!(
false,
eval(&parse("false").unwrap().1, &HashMap::from([])).unwrap()
);
assert_eq!(
true,
eval(&parse("TRUE").unwrap().1, &HashMap::from([])).unwrap()
);
}

#[test]
fn test_logic_expr_eval() {

Expand Down
8 changes: 8 additions & 0 deletions src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ fn parse_expr(input: &str) -> IResult<&str, AstNode> {
parse_parenthesized_expr,
parse_logic_expr,
parse_compare_or_array_expr,
parse_constant,
))(input)
.expect("parse failed");

Expand All @@ -232,6 +233,13 @@ pub fn parse(i: &str) -> IResult<&str, AstNode> {
mod tests {
use super::*;

#[test]
fn parse_constant_test() {
let res = parse("True");
assert_eq!(true, res.is_ok());
assert_eq!(AstNode::Constant(Atom::Boolean(true)), res.unwrap().1);
}

#[test]
fn test_parse_bool() {
let (_, v) = parse_boolean("True").unwrap();
Expand Down

0 comments on commit 489226e

Please sign in to comment.