@@ -3,9 +3,11 @@ use rulog_core::{
3
3
types:: ast:: { Clause , Directive , OperatorDefinition , Predicate , Query } ,
4
4
} ;
5
5
6
- use std:: collections:: HashMap ;
6
+ use std:: io:: { self , Write } ;
7
+ use std:: { cell:: RefCell , collections:: HashMap } ;
7
8
8
9
use crate :: {
10
+ environment:: Environment ,
9
11
resolver:: { QuerySolution , QuerySolver } ,
10
12
types:: InterpretingError ,
11
13
} ;
@@ -60,7 +62,7 @@ impl Interpreter {
60
62
handler : Option < & dyn SolutionHandler > ,
61
63
) -> Result < ( ) , InterpretingError > {
62
64
log:: trace!( "handle query: {:?}" , query) ;
63
- let handler = handler. unwrap_or ( & PrintSolutionHandler ) ;
65
+ let handler = handler. unwrap_or ( & ConsoleSolutionHandler ) ;
64
66
let query_solver = QuerySolver :: new ( self . clauses . clone ( ) , query) ;
65
67
66
68
let mut has_solution = false ;
@@ -94,13 +96,54 @@ impl Interpreter {
94
96
Ok ( ( ) )
95
97
}
96
98
}
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
+ }
97
139
98
- pub struct PrintSolutionHandler ;
140
+ pub struct ConsoleSolutionHandler ;
99
141
100
- impl SolutionHandler for PrintSolutionHandler {
142
+ impl SolutionHandler for ConsoleSolutionHandler {
101
143
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)
104
147
}
105
148
}
106
149
0 commit comments