rust_rule_engine/backward/
query.rs1use super::goal::Goal;
4use super::search::Solution;
5use crate::types::Value;
6use std::collections::HashMap;
7
8#[derive(Debug, Clone)]
10pub struct QueryResult {
11 pub provable: bool,
13
14 pub bindings: HashMap<String, Value>,
16
17 pub proof_trace: ProofTrace,
19
20 pub missing_facts: Vec<String>,
22
23 pub stats: QueryStats,
25
26 pub solutions: Vec<Solution>,
28}
29
30#[derive(Debug, Clone)]
32pub struct ProofTrace {
33 pub goal: String,
35
36 pub steps: Vec<ProofStep>,
38}
39
40#[derive(Debug, Clone)]
42pub struct ProofStep {
43 pub rule_name: String,
45
46 pub goal: String,
48
49 pub sub_steps: Vec<ProofStep>,
51
52 pub depth: usize,
54}
55
56#[derive(Debug, Clone, Default)]
58pub struct QueryStats {
59 pub goals_explored: usize,
61
62 pub rules_evaluated: usize,
64
65 pub max_depth: usize,
67
68 pub duration_ms: Option<u64>,
70}
71
72impl QueryResult {
73 pub fn success(bindings: HashMap<String, Value>, proof: ProofTrace, stats: QueryStats) -> Self {
75 Self {
76 provable: true,
77 bindings,
78 proof_trace: proof,
79 missing_facts: Vec::new(),
80 stats,
81 solutions: Vec::new(),
82 }
83 }
84
85 pub fn success_with_solutions(
87 bindings: HashMap<String, Value>,
88 proof: ProofTrace,
89 stats: QueryStats,
90 solutions: Vec<Solution>,
91 ) -> Self {
92 Self {
93 provable: true,
94 bindings,
95 proof_trace: proof,
96 missing_facts: Vec::new(),
97 stats,
98 solutions,
99 }
100 }
101
102 pub fn failure(missing: Vec<String>, stats: QueryStats) -> Self {
104 Self {
105 provable: false,
106 bindings: HashMap::new(),
107 proof_trace: ProofTrace::empty(),
108 missing_facts: missing,
109 stats,
110 solutions: Vec::new(),
111 }
112 }
113}
114
115impl ProofTrace {
116 pub fn empty() -> Self {
118 Self {
119 goal: String::new(),
120 steps: Vec::new(),
121 }
122 }
123
124 pub fn new(goal: String) -> Self {
126 Self {
127 goal,
128 steps: Vec::new(),
129 }
130 }
131
132 pub fn add_step(&mut self, step: ProofStep) {
134 self.steps.push(step);
135 }
136
137 pub fn from_goal(goal: &Goal) -> Self {
139 let mut trace = Self::new(goal.pattern.clone());
140
141 for (i, rule_name) in goal.candidate_rules.iter().enumerate() {
142 let step = ProofStep {
143 rule_name: rule_name.clone(),
144 goal: goal.pattern.clone(),
145 sub_steps: goal.sub_goals.iter()
146 .map(|sg| ProofStep::from_goal(sg, i + 1))
147 .collect(),
148 depth: goal.depth,
149 };
150 trace.add_step(step);
151 }
152
153 trace
154 }
155
156 pub fn print(&self) {
158 println!("Proof for goal: {}", self.goal);
159 for step in &self.steps {
160 step.print(0);
161 }
162 }
163}
164
165impl ProofStep {
166 fn from_goal(goal: &Goal, depth: usize) -> Self {
168 Self {
169 rule_name: goal.candidate_rules.first()
170 .cloned()
171 .unwrap_or_else(|| "unknown".to_string()),
172 goal: goal.pattern.clone(),
173 sub_steps: goal.sub_goals.iter()
174 .map(|sg| Self::from_goal(sg, depth + 1))
175 .collect(),
176 depth,
177 }
178 }
179
180 fn print(&self, indent: usize) {
182 let prefix = " ".repeat(indent);
183 println!("{}→ [{}] {}", prefix, self.rule_name, self.goal);
184 for sub in &self.sub_steps {
185 sub.print(indent + 1);
186 }
187 }
188}
189
190pub struct QueryParser;
192
193impl QueryParser {
194 pub fn parse(query: &str) -> Result<Goal, String> {
201 use super::expression::ExpressionParser;
202
203 if query.is_empty() {
205 return Err("Empty query".to_string());
206 }
207
208 match ExpressionParser::parse(query) {
210 Ok(expr) => {
211 Ok(Goal::with_expression(query.to_string(), expr))
212 }
213 Err(e) => {
214 Err(format!("Failed to parse query: {}", e))
215 }
216 }
217 }
218
219 pub fn validate(query: &str) -> Result<(), String> {
221 if query.is_empty() {
222 return Err("Query cannot be empty".to_string());
223 }
224
225 Self::parse(query).map(|_| ())
227 }
228}
229
230#[cfg(test)]
231mod tests {
232 use super::*;
233
234 #[test]
235 fn test_query_result_creation() {
236 let stats = QueryStats::default();
237
238 let success = QueryResult::success(
239 HashMap::new(),
240 ProofTrace::empty(),
241 stats.clone(),
242 );
243 assert!(success.provable);
244
245 let failure = QueryResult::failure(vec!["fact".to_string()], stats);
246 assert!(!failure.provable);
247 assert_eq!(failure.missing_facts.len(), 1);
248 }
249
250 #[test]
251 fn test_proof_trace() {
252 let mut trace = ProofTrace::new("User.IsVIP == true".to_string());
253 assert_eq!(trace.goal, "User.IsVIP == true");
254 assert!(trace.steps.is_empty());
255
256 let step = ProofStep {
257 rule_name: "VIPRule".to_string(),
258 goal: "User.IsVIP == true".to_string(),
259 sub_steps: Vec::new(),
260 depth: 0,
261 };
262
263 trace.add_step(step);
264 assert_eq!(trace.steps.len(), 1);
265 }
266
267 #[test]
268 fn test_proof_step() {
269 let step = ProofStep {
270 rule_name: "TestRule".to_string(),
271 goal: "test".to_string(),
272 sub_steps: Vec::new(),
273 depth: 0,
274 };
275
276 assert_eq!(step.rule_name, "TestRule");
277 assert_eq!(step.depth, 0);
278 }
279
280 #[test]
281 fn test_query_parser() {
282 let result = QueryParser::parse("User.IsVIP == true");
283 assert!(result.is_ok());
284
285 let empty = QueryParser::parse("");
286 assert!(empty.is_err());
287 }
288
289 #[test]
290 fn test_query_validation() {
291 assert!(QueryParser::validate("User.Age > 18").is_ok());
292 assert!(QueryParser::validate("User.IsVIP == true").is_ok());
293 assert!(QueryParser::validate("").is_err());
294 assert!(QueryParser::validate("(unclosed").is_err());
297 }
298
299 #[test]
300 fn test_query_stats() {
301 let stats = QueryStats {
302 goals_explored: 5,
303 rules_evaluated: 3,
304 max_depth: 2,
305 duration_ms: Some(100),
306 };
307
308 assert_eq!(stats.goals_explored, 5);
309 assert_eq!(stats.duration_ms, Some(100));
310 }
311
312 #[test]
313 fn test_query_stats_default() {
314 let stats = QueryStats::default();
315 assert_eq!(stats.goals_explored, 0);
316 assert_eq!(stats.rules_evaluated, 0);
317 assert_eq!(stats.max_depth, 0);
318 assert_eq!(stats.duration_ms, None);
319 }
320
321 #[test]
322 fn test_query_result_with_bindings() {
323 let mut bindings = HashMap::new();
324 bindings.insert("X".to_string(), Value::String("VIP".to_string()));
325 bindings.insert("Y".to_string(), Value::Number(1000.0));
326
327 let stats = QueryStats::default();
328 let result = QueryResult::success(bindings, ProofTrace::empty(), stats);
329
330 assert!(result.provable);
331 assert_eq!(result.bindings.len(), 2);
332 assert_eq!(result.bindings.get("X"), Some(&Value::String("VIP".to_string())));
333 assert_eq!(result.bindings.get("Y"), Some(&Value::Number(1000.0)));
334 }
335
336 #[test]
337 fn test_query_result_failure_with_missing_facts() {
338 let missing = vec![
339 "User.IsVIP".to_string(),
340 "Order.Total".to_string(),
341 ];
342
343 let stats = QueryStats::default();
344 let result = QueryResult::failure(missing, stats);
345
346 assert!(!result.provable);
347 assert_eq!(result.missing_facts.len(), 2);
348 assert!(result.bindings.is_empty());
349 }
350
351 #[test]
352 fn test_proof_trace_from_goal() {
353 let mut goal = Goal::new("User.IsVIP == true".to_string());
354 goal.depth = 1;
355 goal.add_candidate_rule("VIPRule".to_string());
356
357 let mut subgoal = Goal::new("User.Points > 1000".to_string());
358 subgoal.depth = 2;
359 subgoal.add_candidate_rule("PointsRule".to_string());
360
361 goal.add_subgoal(subgoal);
362
363 let trace = ProofTrace::from_goal(&goal);
364
365 assert_eq!(trace.goal, "User.IsVIP == true");
366 assert_eq!(trace.steps.len(), 1);
367 assert_eq!(trace.steps[0].rule_name, "VIPRule");
368 assert_eq!(trace.steps[0].sub_steps.len(), 1);
369 }
370
371 #[test]
372 fn test_proof_step_nested() {
373 let sub_step = ProofStep {
374 rule_name: "SubRule".to_string(),
375 goal: "subgoal".to_string(),
376 sub_steps: Vec::new(),
377 depth: 2,
378 };
379
380 let step = ProofStep {
381 rule_name: "MainRule".to_string(),
382 goal: "main".to_string(),
383 sub_steps: vec![sub_step],
384 depth: 1,
385 };
386
387 assert_eq!(step.sub_steps.len(), 1);
388 assert_eq!(step.sub_steps[0].rule_name, "SubRule");
389 assert_eq!(step.sub_steps[0].depth, 2);
390 }
391
392 #[test]
393 fn test_query_parser_complex_expressions() {
394 let and_result = QueryParser::parse("User.IsVIP == true && Order.Total > 1000");
396 assert!(and_result.is_ok());
397
398 let or_result = QueryParser::parse("User.Points > 500 || User.IsVIP == true");
400 assert!(or_result.is_ok());
401
402 let not_result = QueryParser::parse("!(User.IsBanned == true)");
404 assert!(not_result.is_ok());
405 }
406
407 #[test]
408 fn test_query_parser_invalid_syntax() {
409 assert!(QueryParser::parse("").is_err());
411
412 assert!(QueryParser::parse("(User.IsVIP == true").is_err());
414
415 assert!(QueryParser::parse("User.IsVIP == == true").is_err());
417 }
418
419 #[test]
420 fn test_proof_trace_empty() {
421 let trace = ProofTrace::empty();
422 assert!(trace.goal.is_empty());
423 assert!(trace.steps.is_empty());
424 }
425}