Skip to content

Commit

Permalink
refactor: in the interpreter module, SolutionHandler output. Updated …
Browse files Browse the repository at this point in the history
…ConsoleSolutionHandler to use the new handler for printing solutions.
  • Loading branch information
pluveto committed Nov 22, 2024
1 parent 09fe249 commit 477ad88
Showing 1 changed file with 49 additions and 6 deletions.
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

0 comments on commit 477ad88

Please sign in to comment.