rust_rule_engine/backward/
grl_query.rs

1//! GRL Query Syntax Implementation
2//!
3//! This module provides parsing and execution of backward chaining queries defined in GRL
4//! (Goal-driven Rule Language) syntax. GRL queries allow you to define goal-driven reasoning
5//! tasks with configurable search strategies and action handlers.
6//!
7//! # Features
8//!
9//! - **Declarative query syntax** - Define queries in a readable, structured format
10//! - **Multiple search strategies** - Choose between depth-first, breadth-first, or iterative deepening
11//! - **Action handlers** - Execute actions on query success, failure, or missing facts
12//! - **Conditional execution** - Use `when` clauses to conditionally execute queries
13//! - **Parameterized queries** - Support for query parameters (future enhancement)
14//!
15//! # GRL Query Syntax
16//!
17//! ```grl
18//! query "QueryName" {
19//!     goal: <expression>                    // Required: Goal to prove
20//!     strategy: <depth-first|breadth-first|iterative>  // Optional: Search strategy
21//!     max-depth: <number>                   // Optional: Maximum search depth
22//!     max-solutions: <number>               // Optional: Maximum solutions to find
23//!     enable-memoization: <true|false>      // Optional: Enable result caching
24//!
25//!     when: <condition>                     // Optional: Only execute if condition is true
26//!
27//!     on-success: {                         // Optional: Actions on successful proof
28//!         <variable> = <value>;
29//!         <FunctionName>(<args>);
30//!     }
31//!
32//!     on-failure: {                         // Optional: Actions on proof failure
33//!         <actions>
34//!     }
35//!
36//!     on-missing: {                         // Optional: Actions when facts are missing
37//!         <actions>
38//!     }
39//! }
40//! ```
41//!
42//! # Example
43//!
44//! ```rust
45//! use rust_rule_engine::backward::grl_query::{GRLQueryParser, GRLQueryExecutor};
46//! use rust_rule_engine::backward::BackwardEngine;
47//! use rust_rule_engine::{KnowledgeBase, Facts, Value};
48//!
49//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
50//! let query_str = r#"
51//! query "CheckVIPStatus" {
52//!     goal: User.IsVIP == true
53//!     strategy: depth-first
54//!     max-depth: 10
55//!     on-success: {
56//!         User.DiscountRate = 0.2;
57//!         LogMessage("VIP confirmed");
58//!     }
59//!     on-failure: {
60//!         LogMessage("Not a VIP user");
61//!     }
62//! }
63//! "#;
64//!
65//! let query = GRLQueryParser::parse(query_str)?;
66//! let mut bc_engine = BackwardEngine::new(KnowledgeBase::new("kb"));
67//! let mut facts = Facts::new();
68//! facts.set("User.LoyaltyPoints", Value::Number(1500.0));
69//!
70//! let result = GRLQueryExecutor::execute(&query, &mut bc_engine, &mut facts)?;
71//!
72//! if result.provable {
73//!     println!("Goal proven!");
74//! }
75//! # Ok(())
76//! # }
77//! ```
78//!
79//! # Supported Functions in Actions
80//!
81//! - `LogMessage(message)` - Print a log message
82//! - `Request(message)` - Send a request message
83//! - `Print(message)` - Print output
84//! - `Debug(message)` - Print debug output to stderr
85
86use super::backward_engine::{BackwardConfig, BackwardEngine};
87use super::query::{ProofTrace, QueryResult, QueryStats};
88use super::search::SearchStrategy;
89use crate::errors::RuleEngineError;
90use crate::{Facts, Value};
91
92use std::collections::HashMap;
93
94/// Search strategy option for queries
95#[derive(Debug, Clone, PartialEq, Default)]
96pub enum GRLSearchStrategy {
97    #[default]
98    DepthFirst,
99    BreadthFirst,
100    Iterative,
101}
102
103/// Action to execute based on query result
104#[derive(Debug, Clone)]
105pub struct QueryAction {
106    /// Assignment: Variable = Value (as string to be parsed)
107    pub assignments: Vec<(String, String)>,
108    /// Function/method calls
109    pub calls: Vec<String>,
110}
111
112impl Default for QueryAction {
113    fn default() -> Self {
114        Self::new()
115    }
116}
117
118impl QueryAction {
119    pub fn new() -> Self {
120        QueryAction {
121            assignments: Vec::new(),
122            calls: Vec::new(),
123        }
124    }
125
126    /// Execute the action on the given facts
127    pub fn execute(&self, facts: &mut Facts) -> Result<(), RuleEngineError> {
128        // Execute assignments - for now just log them
129        for (var_name, value_str) in &self.assignments {
130            // Simple value parsing
131            let value = if value_str == "true" {
132                Value::Boolean(true)
133            } else if value_str == "false" {
134                Value::Boolean(false)
135            } else if let Ok(n) = value_str.parse::<f64>() {
136                Value::Number(n)
137            } else {
138                // Remove quotes if present
139                let cleaned = value_str.trim_matches('"');
140                Value::String(cleaned.to_string())
141            };
142
143            facts.set(var_name, value);
144        }
145
146        // Execute function calls
147        for call in &self.calls {
148            self.execute_function_call(call)?;
149        }
150
151        Ok(())
152    }
153
154    /// Execute a single function call
155    fn execute_function_call(&self, call: &str) -> Result<(), RuleEngineError> {
156        let call = call.trim();
157
158        // Parse function name and arguments
159        if let Some(open_paren) = call.find('(') {
160            let func_name = call[..open_paren].trim();
161
162            // Extract arguments (everything between first ( and last ))
163            if let Some(close_paren) = call.rfind(')') {
164                let args_str = &call[open_paren + 1..close_paren];
165
166                match func_name {
167                    "LogMessage" => {
168                        // Parse string argument (remove quotes if present)
169                        let message = args_str.trim().trim_matches('"').trim_matches('\'');
170                        println!("[LOG] {}", message);
171                    }
172                    "Request" => {
173                        // Parse request call
174                        let message = args_str.trim().trim_matches('"').trim_matches('\'');
175                        println!("[REQUEST] {}", message);
176                    }
177                    "Print" => {
178                        // Generic print function
179                        let message = args_str.trim().trim_matches('"').trim_matches('\'');
180                        println!("{}", message);
181                    }
182                    "Debug" => {
183                        // Debug output
184                        let message = args_str.trim().trim_matches('"').trim_matches('\'');
185                        eprintln!("[DEBUG] {}", message);
186                    }
187                    other => {
188                        // Unknown function - log warning but don't fail
189                        eprintln!(
190                            "[WARNING] Unknown function call in query action: {}({})",
191                            other, args_str
192                        );
193                    }
194                }
195            } else {
196                return Err(RuleEngineError::ParseError {
197                    message: format!("Malformed function call (missing closing paren): {}", call),
198                });
199            }
200        } else {
201            return Err(RuleEngineError::ParseError {
202                message: format!("Malformed function call (missing opening paren): {}", call),
203            });
204        }
205
206        Ok(())
207    }
208}
209
210/// A GRL Query definition
211#[derive(Debug, Clone)]
212pub struct GRLQuery {
213    /// Query name
214    pub name: String,
215
216    /// Goal pattern to prove (as string expression)
217    pub goal: String,
218
219    /// Search strategy
220    pub strategy: GRLSearchStrategy,
221
222    /// Maximum search depth
223    pub max_depth: usize,
224
225    /// Maximum number of solutions
226    pub max_solutions: usize,
227
228    /// Enable memoization
229    pub enable_memoization: bool,
230
231    /// Enable query optimization (goal reordering, etc.)
232    pub enable_optimization: bool,
233
234    /// Action on success
235    pub on_success: Option<QueryAction>,
236
237    /// Action on failure
238    pub on_failure: Option<QueryAction>,
239
240    /// Action on missing facts
241    pub on_missing: Option<QueryAction>,
242
243    /// Parameters for parameterized queries
244    pub params: HashMap<String, String>, // param_name -> type
245
246    /// Conditional execution (as string condition)
247    pub when_condition: Option<String>,
248}
249
250impl GRLQuery {
251    /// Create a new query with defaults
252    pub fn new(name: String, goal: String) -> Self {
253        GRLQuery {
254            name,
255            goal,
256            strategy: GRLSearchStrategy::default(),
257            max_depth: 10,
258            max_solutions: 1,
259            enable_memoization: true,
260            enable_optimization: true,
261            on_success: None,
262            on_failure: None,
263            on_missing: None,
264            params: HashMap::new(),
265            when_condition: None,
266        }
267    }
268
269    /// Set search strategy
270    pub fn with_strategy(mut self, strategy: GRLSearchStrategy) -> Self {
271        self.strategy = strategy;
272        self
273    }
274
275    /// Set max depth
276    pub fn with_max_depth(mut self, max_depth: usize) -> Self {
277        self.max_depth = max_depth;
278        self
279    }
280
281    /// Set max solutions
282    pub fn with_max_solutions(mut self, max_solutions: usize) -> Self {
283        self.max_solutions = max_solutions;
284        self
285    }
286
287    /// Set memoization
288    pub fn with_memoization(mut self, enable: bool) -> Self {
289        self.enable_memoization = enable;
290        self
291    }
292
293    /// Set query optimization
294    pub fn with_optimization(mut self, enable: bool) -> Self {
295        self.enable_optimization = enable;
296        self
297    }
298
299    /// Add success action
300    pub fn with_on_success(mut self, action: QueryAction) -> Self {
301        self.on_success = Some(action);
302        self
303    }
304
305    /// Add failure action
306    pub fn with_on_failure(mut self, action: QueryAction) -> Self {
307        self.on_failure = Some(action);
308        self
309    }
310
311    /// Add missing facts action
312    pub fn with_on_missing(mut self, action: QueryAction) -> Self {
313        self.on_missing = Some(action);
314        self
315    }
316
317    /// Add parameter
318    pub fn with_param(mut self, name: String, type_name: String) -> Self {
319        self.params.insert(name, type_name);
320        self
321    }
322
323    /// Set conditional execution
324    pub fn with_when(mut self, condition: String) -> Self {
325        self.when_condition = Some(condition);
326        self
327    }
328
329    /// Check if query should execute based on when condition
330    pub fn should_execute(&self, _facts: &Facts) -> Result<bool, RuleEngineError> {
331        // If there's no when condition, execute by default
332        if self.when_condition.is_none() {
333            return Ok(true);
334        }
335
336        // Parse and evaluate the when condition expression against the current facts
337        if let Some(ref cond_str) = self.when_condition {
338            use crate::backward::expression::ExpressionParser;
339
340            match ExpressionParser::parse(cond_str) {
341                Ok(expr) => Ok(expr.is_satisfied(_facts)),
342                Err(e) => Err(e),
343            }
344        } else {
345            Ok(true)
346        }
347    }
348
349    /// Execute success actions
350    pub fn execute_success_actions(&self, facts: &mut Facts) -> Result<(), RuleEngineError> {
351        if let Some(ref action) = self.on_success {
352            action.execute(facts)?;
353        }
354        Ok(())
355    }
356
357    /// Execute failure actions
358    pub fn execute_failure_actions(&self, facts: &mut Facts) -> Result<(), RuleEngineError> {
359        if let Some(ref action) = self.on_failure {
360            action.execute(facts)?;
361        }
362        Ok(())
363    }
364
365    /// Execute missing facts actions
366    pub fn execute_missing_actions(&self, facts: &mut Facts) -> Result<(), RuleEngineError> {
367        if let Some(ref action) = self.on_missing {
368            action.execute(facts)?;
369        }
370        Ok(())
371    }
372
373    /// Convert to BackwardConfig
374    pub fn to_config(&self) -> BackwardConfig {
375        let search_strategy = match self.strategy {
376            GRLSearchStrategy::DepthFirst => SearchStrategy::DepthFirst,
377            GRLSearchStrategy::BreadthFirst => SearchStrategy::BreadthFirst,
378            GRLSearchStrategy::Iterative => SearchStrategy::Iterative,
379        };
380
381        BackwardConfig {
382            strategy: search_strategy,
383            max_depth: self.max_depth,
384            enable_memoization: self.enable_memoization,
385            max_solutions: self.max_solutions,
386        }
387    }
388}
389
390/// Parser for GRL Query syntax
391pub struct GRLQueryParser;
392
393impl GRLQueryParser {
394    /// Parse a query from string
395    ///
396    /// # Example
397    /// ```
398    /// let query_str = r#"
399    /// query "CheckVIP" {
400    ///     goal: User.IsVIP == true
401    ///     strategy: depth-first
402    /// }
403    /// "#;
404    /// let query = rust_rule_engine::backward::GRLQueryParser::parse(query_str).unwrap();
405    /// ```
406    pub fn parse(input: &str) -> Result<GRLQuery, RuleEngineError> {
407        let input = input.trim();
408
409        // Extract query name
410        let name = Self::extract_query_name(input)?;
411
412        // Extract goal
413        let goal = Self::extract_goal(input)?;
414
415        // Create base query
416        let mut query = GRLQuery::new(name, goal);
417
418        // Parse optional attributes
419        if let Some(strategy) = Self::extract_strategy(input) {
420            query.strategy = strategy;
421        }
422
423        if let Some(max_depth) = Self::extract_max_depth(input) {
424            query.max_depth = max_depth;
425        }
426
427        if let Some(max_solutions) = Self::extract_max_solutions(input) {
428            query.max_solutions = max_solutions;
429        }
430
431        if let Some(enable_memo) = Self::extract_memoization(input) {
432            query.enable_memoization = enable_memo;
433        }
434
435        if let Some(enable_opt) = Self::extract_optimization(input) {
436            query.enable_optimization = enable_opt;
437        }
438
439        // Parse actions
440        if let Some(action) = Self::extract_on_success(input)? {
441            query.on_success = Some(action);
442        }
443
444        if let Some(action) = Self::extract_on_failure(input)? {
445            query.on_failure = Some(action);
446        }
447
448        if let Some(action) = Self::extract_on_missing(input)? {
449            query.on_missing = Some(action);
450        }
451
452        // Parse when condition
453        if let Some(condition) = Self::extract_when_condition(input)? {
454            query.when_condition = Some(condition);
455        }
456
457        Ok(query)
458    }
459
460    fn extract_query_name(input: &str) -> Result<String, RuleEngineError> {
461        let re = regex::Regex::new(r#"query\s+"([^"]+)"\s*\{"#).unwrap();
462        if let Some(caps) = re.captures(input) {
463            Ok(caps[1].to_string())
464        } else {
465            Err(RuleEngineError::ParseError {
466                message: "Invalid query syntax: missing query name".to_string(),
467            })
468        }
469    }
470
471    fn extract_goal(input: &str) -> Result<String, RuleEngineError> {
472        // Find goal: line
473        if let Some(goal_start) = input.find("goal:") {
474            let after_goal = &input[goal_start + 5..]; // Skip "goal:"
475
476            // Find the end of the goal line (newline or end of attributes section)
477            // Goal ends at newline, but we need to handle parentheses carefully
478            let goal_end = Self::find_goal_end(after_goal)?;
479            let goal_str = after_goal[..goal_end].trim().to_string();
480
481            if goal_str.is_empty() {
482                return Err(RuleEngineError::ParseError {
483                    message: "Invalid query syntax: empty goal".to_string(),
484                });
485            }
486
487            Ok(goal_str)
488        } else {
489            Err(RuleEngineError::ParseError {
490                message: "Invalid query syntax: missing goal".to_string(),
491            })
492        }
493    }
494
495    fn find_goal_end(input: &str) -> Result<usize, RuleEngineError> {
496        let mut paren_depth = 0;
497        let mut in_string = false;
498        let mut escape_next = false;
499
500        for (i, ch) in input.chars().enumerate() {
501            if escape_next {
502                escape_next = false;
503                continue;
504            }
505
506            match ch {
507                '\\' if in_string => escape_next = true,
508                '"' => in_string = !in_string,
509                '(' if !in_string => paren_depth += 1,
510                ')' if !in_string => {
511                    if paren_depth == 0 {
512                        return Err(RuleEngineError::ParseError {
513                            message: format!(
514                                "Parse error: Unexpected closing parenthesis at position {}",
515                                i
516                            ),
517                        });
518                    }
519                    paren_depth -= 1;
520                }
521                '\n' if !in_string && paren_depth == 0 => return Ok(i),
522                _ => {}
523            }
524        }
525
526        if in_string {
527            return Err(RuleEngineError::ParseError {
528                message: "Parse error: Unclosed string in goal".to_string(),
529            });
530        }
531
532        if paren_depth > 0 {
533            return Err(RuleEngineError::ParseError {
534                message: format!("Parse error: {} unclosed parentheses in goal", paren_depth),
535            });
536        }
537
538        // If we reach here, goal extends to end of input
539        Ok(input.len())
540    }
541
542    fn extract_strategy(input: &str) -> Option<GRLSearchStrategy> {
543        let re = regex::Regex::new(r"strategy:\s*([a-z-]+)").unwrap();
544        re.captures(input).and_then(|caps| match caps[1].trim() {
545            "depth-first" => Some(GRLSearchStrategy::DepthFirst),
546            "breadth-first" => Some(GRLSearchStrategy::BreadthFirst),
547            "iterative" => Some(GRLSearchStrategy::Iterative),
548            _ => None,
549        })
550    }
551
552    fn extract_max_depth(input: &str) -> Option<usize> {
553        let re = regex::Regex::new(r"max-depth:\s*(\d+)").unwrap();
554        re.captures(input).and_then(|caps| caps[1].parse().ok())
555    }
556
557    fn extract_max_solutions(input: &str) -> Option<usize> {
558        let re = regex::Regex::new(r"max-solutions:\s*(\d+)").unwrap();
559        re.captures(input).and_then(|caps| caps[1].parse().ok())
560    }
561
562    fn extract_memoization(input: &str) -> Option<bool> {
563        let re = regex::Regex::new(r"enable-memoization:\s*(true|false)").unwrap();
564        re.captures(input).and_then(|caps| match caps[1].trim() {
565            "true" => Some(true),
566            "false" => Some(false),
567            _ => None,
568        })
569    }
570
571    fn extract_optimization(input: &str) -> Option<bool> {
572        let re = regex::Regex::new(r"enable-optimization:\s*(true|false)").unwrap();
573        re.captures(input).and_then(|caps| match caps[1].trim() {
574            "true" => Some(true),
575            "false" => Some(false),
576            _ => None,
577        })
578    }
579
580    fn extract_on_success(input: &str) -> Result<Option<QueryAction>, RuleEngineError> {
581        Self::extract_action_block(input, "on-success")
582    }
583
584    fn extract_on_failure(input: &str) -> Result<Option<QueryAction>, RuleEngineError> {
585        Self::extract_action_block(input, "on-failure")
586    }
587
588    fn extract_on_missing(input: &str) -> Result<Option<QueryAction>, RuleEngineError> {
589        Self::extract_action_block(input, "on-missing")
590    }
591
592    fn extract_action_block(
593        input: &str,
594        action_name: &str,
595    ) -> Result<Option<QueryAction>, RuleEngineError> {
596        let pattern = format!(r"{}:\s*\{{([^}}]+)\}}", action_name);
597        let re = regex::Regex::new(&pattern).unwrap();
598
599        if let Some(caps) = re.captures(input) {
600            let block = caps[1].trim();
601            let mut action = QueryAction::new();
602
603            // Parse assignments: Variable = Value
604            let assign_re = regex::Regex::new(r"([A-Za-z_][A-Za-z0-9_.]*)\s*=\s*([^;]+);").unwrap();
605            for caps in assign_re.captures_iter(block) {
606                let var_name = caps[1].trim().to_string();
607                let value_str = caps[2].trim().to_string();
608                action.assignments.push((var_name, value_str));
609            }
610
611            // Parse function calls: Function(...)
612            let call_re = regex::Regex::new(r"([A-Za-z_][A-Za-z0-9_]*\([^)]*\));").unwrap();
613            for caps in call_re.captures_iter(block) {
614                action.calls.push(caps[1].trim().to_string());
615            }
616
617            Ok(Some(action))
618        } else {
619            Ok(None)
620        }
621    }
622
623    fn extract_when_condition(input: &str) -> Result<Option<String>, RuleEngineError> {
624        let re = regex::Regex::new(r"when:\s*([^\n}]+)").unwrap();
625        if let Some(caps) = re.captures(input) {
626            let condition_str = caps[1].trim().to_string();
627            Ok(Some(condition_str))
628        } else {
629            Ok(None)
630        }
631    }
632
633    /// Parse multiple queries from a file
634    pub fn parse_queries(input: &str) -> Result<Vec<GRLQuery>, RuleEngineError> {
635        let mut queries = Vec::new();
636
637        // Find all query blocks - use simpler approach
638        // Split by "query" keyword and process each block
639        let parts: Vec<&str> = input.split("query").collect();
640
641        for part in parts.iter().skip(1) {
642            // Skip first empty part
643            let query_str = format!("query{}", part);
644            // Find the matching closing brace
645            if let Some(end_idx) = find_matching_brace(&query_str) {
646                let complete_query = &query_str[..end_idx];
647                if let Ok(query) = Self::parse(complete_query) {
648                    queries.push(query);
649                }
650            }
651        }
652
653        Ok(queries)
654    }
655}
656
657// Helper function to find matching closing brace
658fn find_matching_brace(input: &str) -> Option<usize> {
659    let mut depth = 0;
660    let mut in_string = false;
661    let mut escape_next = false;
662
663    for (i, ch) in input.chars().enumerate() {
664        if escape_next {
665            escape_next = false;
666            continue;
667        }
668
669        match ch {
670            '\\' => escape_next = true,
671            '"' => in_string = !in_string,
672            '{' if !in_string => depth += 1,
673            '}' if !in_string => {
674                depth -= 1;
675                if depth == 0 {
676                    return Some(i + 1);
677                }
678            }
679            _ => {}
680        }
681    }
682
683    None
684}
685
686/// Executor for GRL queries
687pub struct GRLQueryExecutor;
688
689impl GRLQueryExecutor {
690    /// Execute a single query
691    pub fn execute(
692        query: &GRLQuery,
693        bc_engine: &mut BackwardEngine,
694        facts: &mut Facts,
695    ) -> Result<QueryResult, RuleEngineError> {
696        // Check when condition
697        if !query.should_execute(facts)? {
698            return Ok(QueryResult {
699                provable: false,
700                bindings: HashMap::new(),
701                proof_trace: ProofTrace {
702                    goal: String::new(),
703                    steps: Vec::new(),
704                },
705                missing_facts: Vec::new(),
706                stats: QueryStats::default(),
707                solutions: Vec::new(),
708            });
709        }
710
711        // Apply config
712        bc_engine.set_config(query.to_config());
713
714        // Parse compound goals (support &&, ||, and !=)
715        let result = if query.goal.contains("&&") && query.goal.contains("||") {
716            // Complex expression with both AND and OR - need proper parsing
717            // For now, evaluate left-to-right with precedence: AND before OR
718            Self::execute_complex_goal(&query.goal, bc_engine, facts)?
719        } else if query.goal.contains("||") {
720            // Split on || and check any goal (OR logic)
721            Self::execute_compound_or_goal(&query.goal, bc_engine, facts)?
722        } else if query.goal.contains("&&") {
723            // Split on && and check all goals (AND logic)
724            Self::execute_compound_and_goal(&query.goal, bc_engine, facts)?
725        } else {
726            // Single goal
727            bc_engine.query(&query.goal, facts)?
728        };
729
730        // Execute appropriate actions
731        if result.provable {
732            query.execute_success_actions(facts)?;
733        } else if !result.missing_facts.is_empty() {
734            query.execute_missing_actions(facts)?;
735        } else {
736            query.execute_failure_actions(facts)?;
737        }
738
739        Ok(result)
740    }
741
742    /// Execute compound AND goal (all must be true)
743    fn execute_compound_and_goal(
744        goal_expr: &str,
745        bc_engine: &mut BackwardEngine,
746        facts: &mut Facts,
747    ) -> Result<QueryResult, RuleEngineError> {
748        let sub_goals: Vec<&str> = goal_expr.split("&&").map(|s| s.trim()).collect();
749
750        let mut all_provable = true;
751        let combined_bindings = HashMap::new();
752        let all_missing = Vec::new();
753        let combined_stats = QueryStats::default();
754
755        for sub_goal in sub_goals.iter() {
756            // Handle != by using expression parser directly
757            let goal_satisfied = if sub_goal.contains("!=") {
758                // Parse and evaluate the expression directly
759                use crate::backward::expression::ExpressionParser;
760
761                match ExpressionParser::parse(sub_goal) {
762                    Ok(expr) => expr.is_satisfied(facts),
763                    Err(_) => false,
764                }
765            } else {
766                // Normal == comparison, use backward chaining
767                let result = bc_engine.query(sub_goal, facts)?;
768                result.provable
769            };
770
771            if !goal_satisfied {
772                all_provable = false;
773            }
774
775            // Note: For compound goals with !=, we don't track missing facts well yet
776            // This is a simplification for now
777        }
778
779        Ok(QueryResult {
780            provable: all_provable,
781            bindings: combined_bindings,
782            proof_trace: ProofTrace {
783                goal: goal_expr.to_string(),
784                steps: Vec::new(),
785            },
786            missing_facts: all_missing,
787            stats: combined_stats,
788            solutions: Vec::new(),
789        })
790    }
791
792    /// Execute compound OR goal (any must be true)
793    fn execute_compound_or_goal(
794        goal_expr: &str,
795        bc_engine: &mut BackwardEngine,
796        facts: &mut Facts,
797    ) -> Result<QueryResult, RuleEngineError> {
798        let sub_goals: Vec<&str> = goal_expr.split("||").map(|s| s.trim()).collect();
799
800        let mut any_provable = false;
801        let mut combined_bindings = HashMap::new();
802        let mut all_missing = Vec::new();
803        let mut combined_stats = QueryStats::default();
804        let mut all_solutions = Vec::new();
805
806        for sub_goal in sub_goals.iter() {
807            // Handle != by using expression parser directly
808            let (goal_satisfied, result_opt) = if sub_goal.contains("!=") {
809                // Parse and evaluate the expression directly
810                use crate::backward::expression::ExpressionParser;
811
812                match ExpressionParser::parse(sub_goal) {
813                    Ok(expr) => (expr.is_satisfied(facts), None),
814                    Err(_) => (false, None),
815                }
816            } else {
817                // Normal == comparison, use backward chaining
818                let result = bc_engine.query(sub_goal, facts)?;
819                let provable = result.provable;
820                (provable, Some(result))
821            };
822
823            if goal_satisfied {
824                any_provable = true;
825
826                // Merge results from successful branch
827                if let Some(result) = result_opt {
828                    combined_bindings.extend(result.bindings);
829                    all_missing.extend(result.missing_facts);
830                    combined_stats.goals_explored += result.stats.goals_explored;
831                    combined_stats.rules_evaluated += result.stats.rules_evaluated;
832                    if let Some(dur) = result.stats.duration_ms {
833                        combined_stats.duration_ms =
834                            Some(combined_stats.duration_ms.unwrap_or(0) + dur);
835                    }
836                    all_solutions.extend(result.solutions);
837                }
838            }
839        }
840
841        Ok(QueryResult {
842            provable: any_provable,
843            bindings: combined_bindings,
844            proof_trace: ProofTrace {
845                goal: goal_expr.to_string(),
846                steps: Vec::new(),
847            },
848            missing_facts: all_missing,
849            stats: combined_stats,
850            solutions: all_solutions,
851        })
852    }
853
854    /// Strip outer parentheses from expression
855    fn strip_outer_parens(expr: &str) -> &str {
856        let trimmed = expr.trim();
857        if trimmed.starts_with('(') && trimmed.ends_with(')') {
858            // Check if these are matching outer parens
859            let inner = &trimmed[1..trimmed.len() - 1];
860            let mut depth = 0;
861            for ch in inner.chars() {
862                match ch {
863                    '(' => depth += 1,
864                    ')' => {
865                        depth -= 1;
866                        if depth < 0 {
867                            // Closing paren in middle, so outer parens don't match
868                            return trimmed;
869                        }
870                    }
871                    _ => {}
872                }
873            }
874            if depth == 0 {
875                // Outer parens match, return inner
876                return inner.trim();
877            }
878        }
879        trimmed
880    }
881
882    /// Execute complex goal with both AND and OR operators
883    /// Precedence: AND is evaluated before OR (like multiplication before addition)
884    /// Example: "A || B && C" is evaluated as "A || (B && C)"
885    fn execute_complex_goal(
886        goal_expr: &str,
887        bc_engine: &mut BackwardEngine,
888        facts: &mut Facts,
889    ) -> Result<QueryResult, RuleEngineError> {
890        // Strip outer parentheses first
891        let cleaned_expr = Self::strip_outer_parens(goal_expr);
892
893        // Split by || first (lowest precedence)
894        let or_parts: Vec<&str> = cleaned_expr.split("||").map(|s| s.trim()).collect();
895
896        let mut any_provable = false;
897        let mut combined_bindings = HashMap::new();
898        let mut all_missing = Vec::new();
899        let mut combined_stats = QueryStats::default();
900        let mut all_solutions = Vec::new();
901
902        for or_part in or_parts.iter() {
903            // Strip parentheses from each part
904            let cleaned_part = Self::strip_outer_parens(or_part);
905
906            // Each OR part might contain AND clauses
907            let result = if cleaned_part.contains("&&") {
908                Self::execute_compound_and_goal(cleaned_part, bc_engine, facts)?
909            } else {
910                bc_engine.query(cleaned_part, facts)?
911            };
912
913            if result.provable {
914                any_provable = true;
915                combined_bindings.extend(result.bindings);
916                all_missing.extend(result.missing_facts);
917                combined_stats.goals_explored += result.stats.goals_explored;
918                combined_stats.rules_evaluated += result.stats.rules_evaluated;
919                if let Some(dur) = result.stats.duration_ms {
920                    combined_stats.duration_ms =
921                        Some(combined_stats.duration_ms.unwrap_or(0) + dur);
922                }
923                all_solutions.extend(result.solutions);
924            }
925        }
926
927        Ok(QueryResult {
928            provable: any_provable,
929            bindings: combined_bindings,
930            proof_trace: ProofTrace {
931                goal: goal_expr.to_string(),
932                steps: Vec::new(),
933            },
934            missing_facts: all_missing,
935            stats: combined_stats,
936            solutions: all_solutions,
937        })
938    }
939
940    /// Execute multiple queries
941    pub fn execute_queries(
942        queries: &[GRLQuery],
943        bc_engine: &mut BackwardEngine,
944        facts: &mut Facts,
945    ) -> Result<Vec<QueryResult>, RuleEngineError> {
946        let mut results = Vec::new();
947
948        for query in queries {
949            let result = Self::execute(query, bc_engine, facts)?;
950            results.push(result);
951        }
952
953        Ok(results)
954    }
955}
956
957#[cfg(test)]
958mod tests {
959    use super::*;
960
961    #[test]
962    fn test_parse_simple_query() {
963        let input = r#"
964        query "TestQuery" {
965            goal: User.IsVIP == true
966        }
967        "#;
968
969        let query = GRLQueryParser::parse(input).unwrap();
970        assert_eq!(query.name, "TestQuery");
971        assert_eq!(query.strategy, GRLSearchStrategy::DepthFirst);
972        assert_eq!(query.max_depth, 10);
973    }
974
975    #[test]
976    fn test_parse_query_with_strategy() {
977        let input = r#"
978        query "TestQuery" {
979            goal: User.IsVIP == true
980            strategy: breadth-first
981            max-depth: 5
982        }
983        "#;
984
985        let query = GRLQueryParser::parse(input).unwrap();
986        assert_eq!(query.strategy, GRLSearchStrategy::BreadthFirst);
987        assert_eq!(query.max_depth, 5);
988    }
989
990    #[test]
991    fn test_parse_query_with_actions() {
992        let input = r#"
993        query "TestQuery" {
994            goal: User.IsVIP == true
995            on-success: {
996                User.DiscountRate = 0.2;
997                LogMessage("VIP confirmed");
998            }
999        }
1000        "#;
1001
1002        let query = GRLQueryParser::parse(input).unwrap();
1003        assert!(query.on_success.is_some());
1004
1005        let action = query.on_success.unwrap();
1006        assert_eq!(action.assignments.len(), 1);
1007        assert_eq!(action.calls.len(), 1);
1008    }
1009
1010    #[test]
1011    fn test_parse_query_with_when_condition() {
1012        let input = r#"
1013        query "TestQuery" {
1014            goal: User.IsVIP == true
1015            when: Environment.Mode == "Production"
1016        }
1017        "#;
1018
1019        let query = GRLQueryParser::parse(input).unwrap();
1020        assert!(query.when_condition.is_some());
1021    }
1022
1023    #[test]
1024    fn test_parse_multiple_queries() {
1025        let input = r#"
1026        query "Query1" {
1027            goal: A == true
1028        }
1029        
1030        query "Query2" {
1031            goal: B == true
1032            strategy: breadth-first
1033        }
1034        "#;
1035
1036        let queries = GRLQueryParser::parse_queries(input).unwrap();
1037        assert_eq!(queries.len(), 2);
1038        assert_eq!(queries[0].name, "Query1");
1039        assert_eq!(queries[1].name, "Query2");
1040    }
1041
1042    #[test]
1043    fn test_query_config_conversion() {
1044        let query = GRLQuery::new("Test".to_string(), "X == true".to_string())
1045            .with_strategy(GRLSearchStrategy::BreadthFirst)
1046            .with_max_depth(15)
1047            .with_memoization(false);
1048
1049        let config = query.to_config();
1050        assert_eq!(config.max_depth, 15);
1051        assert!(!config.enable_memoization);
1052    }
1053
1054    #[test]
1055    fn test_action_execution() {
1056        let mut facts = Facts::new();
1057
1058        let mut action = QueryAction::new();
1059        action
1060            .assignments
1061            .push(("User.DiscountRate".to_string(), "0.2".to_string()));
1062
1063        action.execute(&mut facts).unwrap();
1064
1065        // Check that assignment was executed
1066        let value = facts.get("User.DiscountRate");
1067        assert!(value.is_some());
1068    }
1069
1070    #[test]
1071    fn test_should_execute_no_condition() {
1072        let query = GRLQuery::new("Q".to_string(), "X == true".to_string());
1073        let facts = Facts::new();
1074        // No when condition -> should execute
1075        let res = query.should_execute(&facts).unwrap();
1076        assert!(res);
1077    }
1078
1079    #[test]
1080    fn test_should_execute_condition_true() {
1081        let facts = Facts::new();
1082        facts.set("Environment.Mode", Value::String("Production".to_string()));
1083
1084        let query = GRLQuery::new("Q".to_string(), "X == true".to_string())
1085            .with_when("Environment.Mode == \"Production\"".to_string());
1086
1087        let res = query.should_execute(&facts).unwrap();
1088        assert!(res, "expected when condition to be satisfied");
1089    }
1090
1091    #[test]
1092    fn test_should_execute_condition_false() {
1093        let facts = Facts::new();
1094        facts.set("Environment.Mode", Value::String("Development".to_string()));
1095
1096        let query = GRLQuery::new("Q".to_string(), "X == true".to_string())
1097            .with_when("Environment.Mode == \"Production\"".to_string());
1098
1099        let res = query.should_execute(&facts).unwrap();
1100        assert!(!res, "expected when condition to be unsatisfied");
1101    }
1102
1103    #[test]
1104    fn test_should_execute_parse_error_propagates() {
1105        let facts = Facts::new();
1106        // Use an unterminated string literal to force a parse error from the expression parser
1107        let query = GRLQuery::new("Q".to_string(), "X == true".to_string())
1108            .with_when("Environment.Mode == \"Production".to_string());
1109
1110        let res = query.should_execute(&facts);
1111        assert!(res.is_err(), "expected parse error to propagate");
1112    }
1113
1114    #[test]
1115    fn test_parse_query_with_or_goal() {
1116        let input = r#"
1117        query "TestOR" {
1118            goal: User.IsVIP == true || User.TotalSpent > 10000
1119        }
1120        "#;
1121
1122        let query = GRLQueryParser::parse(input).unwrap();
1123        assert_eq!(query.name, "TestOR");
1124        assert!(query.goal.contains("||"));
1125    }
1126
1127    #[test]
1128    fn test_parse_query_with_complex_goal() {
1129        let input = r#"
1130        query "ComplexQuery" {
1131            goal: (User.IsVIP == true && User.Active == true) || User.TotalSpent > 10000
1132        }
1133        "#;
1134
1135        let query = GRLQueryParser::parse(input).unwrap();
1136        assert!(query.goal.contains("||"));
1137        assert!(query.goal.contains("&&"));
1138    }
1139
1140    #[test]
1141    fn test_parse_query_with_multiple_or_branches() {
1142        let input = r#"
1143        query "MultiOR" {
1144            goal: Employee.IsManager == true || Employee.IsSenior == true || Employee.IsDirector == true
1145        }
1146        "#;
1147
1148        let query = GRLQueryParser::parse(input).unwrap();
1149        let branches: Vec<&str> = query.goal.split("||").collect();
1150        assert_eq!(branches.len(), 3);
1151    }
1152
1153    #[test]
1154    fn test_parse_query_with_parentheses() {
1155        let input = r#"
1156        query "ParenQuery" {
1157            goal: (User.IsVIP == true && User.Active == true) || User.TotalSpent > 10000
1158        }
1159        "#;
1160
1161        let query = GRLQueryParser::parse(input).unwrap();
1162        assert!(query.goal.contains("("));
1163        assert!(query.goal.contains(")"));
1164        assert!(query.goal.contains("||"));
1165        assert!(query.goal.contains("&&"));
1166    }
1167
1168    #[test]
1169    fn test_parse_query_with_nested_parentheses() {
1170        let input = r#"
1171        query "NestedParen" {
1172            goal: ((A == true && B == true) || C == true) && D == true
1173        }
1174        "#;
1175
1176        let query = GRLQueryParser::parse(input).unwrap();
1177        assert_eq!(query.name, "NestedParen");
1178        // Check that parentheses are preserved
1179        assert!(query.goal.starts_with("(("));
1180    }
1181
1182    #[test]
1183    fn test_parse_query_unclosed_parenthesis() {
1184        let input = r#"
1185        query "BadParen" {
1186            goal: (User.IsVIP == true && User.Active == true
1187        }
1188        "#;
1189
1190        let result = GRLQueryParser::parse(input);
1191        assert!(result.is_err());
1192        if let Err(e) = result {
1193            let msg = format!("{:?}", e);
1194            assert!(msg.contains("unclosed parentheses") || msg.contains("parenthesis"));
1195        }
1196    }
1197}