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

refactor: implement Display for Term, add environment methods, and enhance solution handlers #5

Merged
merged 4 commits into from
Nov 22, 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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[workspace]

resolver = "2"
members = [
"rulog_core",
"rulog_cli",
Expand Down
32 changes: 32 additions & 0 deletions rulog_core/src/types/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,38 @@ pub enum Term {
Structure(String, Vec<Term>),
}

impl std::fmt::Display for Term {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Term::Atom(s) => write!(f, "{}", s),
Term::Variable(s) => write!(f, "{}", s),
Term::Integer(i) => write!(f, "{}", i),
Term::Float(Float(val)) => write!(f, "{}", val),
Term::String(s) => write!(f, "\"{}\"", s),
Term::List(terms) => {
write!(f, "[")?;
for (i, term) in terms.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{}", term)?;
}
write!(f, "]")
}
Term::Structure(name, terms) => {
write!(f, "{}(", name)?;
for (i, term) in terms.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
write!(f, "{}", term)?;
}
write!(f, ")")
}
}
}
}

#[derive(Debug, PartialEq, Clone)]
pub struct Float(pub f64);

Expand Down
8 changes: 8 additions & 0 deletions rulog_vm/src/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ impl Environment {
self.bind(var, term);
self
}

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

pub fn iter(&self) -> std::collections::hash_map::Iter<String, Term> {
self.bindings.iter()
}
}

impl FromIterator<(std::string::String, Term)> for Environment {
Expand Down
55 changes: 49 additions & 6 deletions rulog_vm/src/interpreter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ use rulog_core::{
types::ast::{Clause, Directive, OperatorDefinition, Predicate, Query},
};

use std::collections::HashMap;
use std::io::{self, Write};
use std::{cell::RefCell, collections::HashMap};

use crate::{
environment::Environment,
resolver::{QuerySolution, QuerySolver},
types::InterpretingError,
};
Expand Down Expand Up @@ -60,7 +62,7 @@ impl Interpreter {
handler: Option<&dyn SolutionHandler>,
) -> Result<(), InterpretingError> {
log::trace!("handle query: {:?}", query);
let handler = handler.unwrap_or(&PrintSolutionHandler);
let handler = handler.unwrap_or(&ConsoleSolutionHandler);
let query_solver = QuerySolver::new(self.clauses.clone(), query);

let mut has_solution = false;
Expand Down Expand Up @@ -94,13 +96,54 @@ impl Interpreter {
Ok(())
}
}
pub struct WriteSolutionHandler<'a, W: Write> {
writer: RefCell<&'a mut W>,
}

impl<'a, W: Write> WriteSolutionHandler<'a, W> {
pub fn new(writer: &'a mut W) -> Self {
WriteSolutionHandler {
writer: RefCell::new(writer),
}
}

fn print_solution(&self, solution: Option<&QuerySolution>) -> io::Result<()> {
let mut writer = self.writer.borrow_mut();
if let Some(solution) = solution {
if solution.env.is_empty() {
writeln!(writer, "true.")?;
} else {
self.print_env(&mut writer, &solution.env)?;
}
} else {
writeln!(writer, "false.")?;
}
Ok(())
}

fn print_env(&self, writer: &mut W, env: &Environment) -> io::Result<()> {
let mut env_str = String::new();
for (var, term) in env.iter() {
env_str.push_str(&format!("{} = {}, ", var, term));
}
writeln!(writer, "{{{}}}.", env_str.trim_end_matches(", "))?;
Ok(())
}
}

impl<'a, W: Write> SolutionHandler for WriteSolutionHandler<'a, W> {
fn handle_solution(&self, solution: Option<&QuerySolution>) -> bool {
self.print_solution(solution).is_ok()
}
}

pub struct PrintSolutionHandler;
pub struct ConsoleSolutionHandler;

impl SolutionHandler for PrintSolutionHandler {
impl SolutionHandler for ConsoleSolutionHandler {
fn handle_solution(&self, solution: Option<&QuerySolution>) -> bool {
println!("solution: {:?}", solution);
true // Continue processing
let mut writer = io::stdout();
let handler = WriteSolutionHandler::new(&mut writer);
handler.handle_solution(solution)
}
}

Expand Down
Loading