Skip to content

Commit 477ad88

Browse files
committed
refactor: in the interpreter module, SolutionHandler output. Updated ConsoleSolutionHandler to use the new handler for printing solutions.
1 parent 09fe249 commit 477ad88

File tree

1 file changed

+49
-6
lines changed

1 file changed

+49
-6
lines changed

rulog_vm/src/interpreter.rs

+49-6
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@ use rulog_core::{
33
types::ast::{Clause, Directive, OperatorDefinition, Predicate, Query},
44
};
55

6-
use std::collections::HashMap;
6+
use std::io::{self, Write};
7+
use std::{cell::RefCell, collections::HashMap};
78

89
use crate::{
10+
environment::Environment,
911
resolver::{QuerySolution, QuerySolver},
1012
types::InterpretingError,
1113
};
@@ -60,7 +62,7 @@ impl Interpreter {
6062
handler: Option<&dyn SolutionHandler>,
6163
) -> Result<(), InterpretingError> {
6264
log::trace!("handle query: {:?}", query);
63-
let handler = handler.unwrap_or(&PrintSolutionHandler);
65+
let handler = handler.unwrap_or(&ConsoleSolutionHandler);
6466
let query_solver = QuerySolver::new(self.clauses.clone(), query);
6567

6668
let mut has_solution = false;
@@ -94,13 +96,54 @@ impl Interpreter {
9496
Ok(())
9597
}
9698
}
99+
pub struct WriteSolutionHandler<'a, W: Write> {
100+
writer: RefCell<&'a mut W>,
101+
}
102+
103+
impl<'a, W: Write> WriteSolutionHandler<'a, W> {
104+
pub fn new(writer: &'a mut W) -> Self {
105+
WriteSolutionHandler {
106+
writer: RefCell::new(writer),
107+
}
108+
}
109+
110+
fn print_solution(&self, solution: Option<&QuerySolution>) -> io::Result<()> {
111+
let mut writer = self.writer.borrow_mut();
112+
if let Some(solution) = solution {
113+
if solution.env.is_empty() {
114+
writeln!(writer, "true.")?;
115+
} else {
116+
self.print_env(&mut writer, &solution.env)?;
117+
}
118+
} else {
119+
writeln!(writer, "false.")?;
120+
}
121+
Ok(())
122+
}
123+
124+
fn print_env(&self, writer: &mut W, env: &Environment) -> io::Result<()> {
125+
let mut env_str = String::new();
126+
for (var, term) in env.iter() {
127+
env_str.push_str(&format!("{} = {}, ", var, term));
128+
}
129+
writeln!(writer, "{{{}}}.", env_str.trim_end_matches(", "))?;
130+
Ok(())
131+
}
132+
}
133+
134+
impl<'a, W: Write> SolutionHandler for WriteSolutionHandler<'a, W> {
135+
fn handle_solution(&self, solution: Option<&QuerySolution>) -> bool {
136+
self.print_solution(solution).is_ok()
137+
}
138+
}
97139

98-
pub struct PrintSolutionHandler;
140+
pub struct ConsoleSolutionHandler;
99141

100-
impl SolutionHandler for PrintSolutionHandler {
142+
impl SolutionHandler for ConsoleSolutionHandler {
101143
fn handle_solution(&self, solution: Option<&QuerySolution>) -> bool {
102-
println!("solution: {:?}", solution);
103-
true // Continue processing
144+
let mut writer = io::stdout();
145+
let handler = WriteSolutionHandler::new(&mut writer);
146+
handler.handle_solution(solution)
104147
}
105148
}
106149

0 commit comments

Comments
 (0)