oxirs-rule 0.2.4

Forward/backward rule engine for RDFS, OWL, and SWRL reasoning
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
//! Forward Chaining Inference Engine
//!
//! Implementation of forward chaining rule application with fixpoint calculation.
//! Applies rules from facts to derive new facts until no more facts can be derived.

use crate::{Rule, RuleAtom, Term};
use anyhow::Result;
use scirs2_core::metrics::{Counter, Gauge};
use std::collections::{HashMap, HashSet};
use tracing::{debug, info, trace, warn};

// Global metrics for memory tracking
lazy_static::lazy_static! {
    static ref SUBSTITUTION_CLONES: Counter = Counter::new("forward_chain_substitution_clones".to_string());
    static ref FACT_SET_CLONES: Counter = Counter::new("forward_chain_fact_set_clones".to_string());
    static ref ACTIVE_SUBSTITUTIONS: Gauge = Gauge::new("forward_chain_active_substitutions".to_string());
}

/// Variable substitution mapping
pub type Substitution = HashMap<String, Term>;

/// Forward chaining inference engine
#[derive(Debug)]
pub struct ForwardChainer {
    /// Rules to apply
    rules: Vec<Rule>,
    /// Known facts
    facts: HashSet<RuleAtom>,
    /// Maximum number of iterations to prevent infinite loops
    max_iterations: usize,
    /// Enable detailed logging
    debug_mode: bool,
}

impl Default for ForwardChainer {
    fn default() -> Self {
        Self::new()
    }
}

impl ForwardChainer {
    /// Create a new forward chainer
    pub fn new() -> Self {
        Self {
            rules: Vec::new(),
            facts: HashSet::new(),
            max_iterations: 1000,
            debug_mode: false,
        }
    }

    /// Create a new forward chainer with custom configuration
    pub fn with_config(max_iterations: usize, debug_mode: bool) -> Self {
        Self {
            rules: Vec::new(),
            facts: HashSet::new(),
            max_iterations,
            debug_mode,
        }
    }

    /// Add a rule to the engine
    pub fn add_rule(&mut self, rule: Rule) {
        if self.debug_mode {
            debug!("Adding rule: {}", rule.name);
        }
        self.rules.push(rule);
    }

    /// Add multiple rules to the engine
    pub fn add_rules(&mut self, rules: Vec<Rule>) {
        for rule in rules {
            self.add_rule(rule);
        }
    }

    /// Add a fact to the knowledge base
    pub fn add_fact(&mut self, fact: RuleAtom) {
        if self.debug_mode {
            trace!("Adding fact: {:?}", fact);
        }
        self.facts.insert(fact);
    }

    /// Add multiple facts to the knowledge base
    pub fn add_facts(&mut self, facts: Vec<RuleAtom>) {
        for fact in facts {
            self.add_fact(fact);
        }
    }

    /// Get all current facts
    pub fn get_facts(&self) -> Vec<RuleAtom> {
        self.facts.iter().cloned().collect()
    }

    /// Clear all facts
    pub fn clear_facts(&mut self) {
        self.facts.clear();
    }

    /// Perform forward chaining inference
    pub fn infer(&mut self) -> Result<Vec<RuleAtom>> {
        let initial_fact_count = self.facts.len();
        let mut iteration = 0;
        let mut new_facts_added = true;

        info!(
            "Starting forward chaining with {} initial facts and {} rules",
            initial_fact_count,
            self.rules.len()
        );

        while new_facts_added && iteration < self.max_iterations {
            new_facts_added = false;
            iteration += 1;

            if self.debug_mode {
                debug!(
                    "Forward chaining iteration {} with {} facts",
                    iteration,
                    self.facts.len()
                );
            }

            // Apply all rules to current facts
            for rule in &self.rules {
                let new_facts = self.apply_rule(rule)?;
                for fact in new_facts {
                    if !self.facts.contains(&fact) {
                        if self.debug_mode {
                            trace!("Derived new fact from rule '{}': {:?}", rule.name, fact);
                        }
                        self.facts.insert(fact);
                        new_facts_added = true;
                    }
                }
            }
        }

        if iteration >= self.max_iterations {
            warn!(
                "Forward chaining reached maximum iterations ({}), may not have reached fixpoint",
                self.max_iterations
            );
        }

        let final_fact_count = self.facts.len();
        info!(
            "Forward chaining completed after {} iterations: {} -> {} facts",
            iteration, initial_fact_count, final_fact_count
        );

        Ok(self.get_facts())
    }

    /// Apply a single rule to current facts
    fn apply_rule(&self, rule: &Rule) -> Result<Vec<RuleAtom>> {
        let mut new_facts = Vec::new();

        // Find all possible substitutions that satisfy the rule body
        let substitutions = self.find_substitutions(&rule.body)?;

        // Apply each substitution to the rule head
        for substitution in substitutions {
            for head_atom in &rule.head {
                let instantiated = self.apply_substitution(head_atom, &substitution)?;
                new_facts.push(instantiated);
            }
        }

        if self.debug_mode && !new_facts.is_empty() {
            debug!(
                "Rule '{}' produced {} new facts",
                rule.name,
                new_facts.len()
            );
        }

        Ok(new_facts)
    }

    /// Find all substitutions that satisfy the rule body
    fn find_substitutions(&self, body: &[RuleAtom]) -> Result<Vec<Substitution>> {
        if body.is_empty() {
            return Ok(vec![HashMap::new()]);
        }

        // Start with the first atom in the body
        let mut substitutions = self.match_atom(&body[0], &HashMap::new())?;

        // Track active substitutions
        ACTIVE_SUBSTITUTIONS.set(substitutions.len() as f64);

        // Extend substitutions with remaining atoms
        for atom in &body[1..] {
            let mut new_substitutions = Vec::new();
            for substitution in substitutions {
                let extended = self.match_atom(atom, &substitution)?;
                new_substitutions.extend(extended);
            }
            substitutions = new_substitutions;

            // Update gauge with current count
            ACTIVE_SUBSTITUTIONS.set(substitutions.len() as f64);
        }

        Ok(substitutions)
    }

    /// Match an atom against facts with a given partial substitution
    fn match_atom(&self, atom: &RuleAtom, partial_sub: &Substitution) -> Result<Vec<Substitution>> {
        let mut substitutions = Vec::new();

        match atom {
            RuleAtom::Triple {
                subject,
                predicate,
                object,
            } => {
                // Match against all facts
                for fact in &self.facts {
                    if let RuleAtom::Triple {
                        subject: fact_subject,
                        predicate: fact_predicate,
                        object: fact_object,
                    } = fact
                    {
                        // OPTIMIZED: Only clone inside unify_triple if unification succeeds
                        if let Some(substitution) = self.unify_triple(
                            (subject, predicate, object),
                            (fact_subject, fact_predicate, fact_object),
                            partial_sub,
                        )? {
                            // Track successful unification (clone happened inside unify_triple)
                            SUBSTITUTION_CLONES.inc();
                            substitutions.push(substitution);
                        }
                    }
                }
            }
            RuleAtom::Builtin { name, args } => {
                // OPTIMIZED: Only clone if predicate succeeds
                if let Some(substitution) = self.evaluate_builtin(name, args, partial_sub)? {
                    SUBSTITUTION_CLONES.inc();
                    substitutions.push(substitution);
                }
            }
            RuleAtom::NotEqual { left, right } => {
                // Handle not-equal constraint
                let left_term = self.substitute_term(left, partial_sub);
                let right_term = self.substitute_term(right, partial_sub);
                if !self.terms_equal(&left_term, &right_term) {
                    SUBSTITUTION_CLONES.inc();
                    substitutions.push(partial_sub.clone());
                }
            }
            RuleAtom::GreaterThan { left, right } => {
                // Handle greater-than constraint
                let left_term = self.substitute_term(left, partial_sub);
                let right_term = self.substitute_term(right, partial_sub);
                if self.compare_terms(&left_term, &right_term) > 0 {
                    SUBSTITUTION_CLONES.inc();
                    substitutions.push(partial_sub.clone());
                }
            }
            RuleAtom::LessThan { left, right } => {
                // Handle less-than constraint
                let left_term = self.substitute_term(left, partial_sub);
                let right_term = self.substitute_term(right, partial_sub);
                if self.compare_terms(&left_term, &right_term) < 0 {
                    SUBSTITUTION_CLONES.inc();
                    substitutions.push(partial_sub.clone());
                }
            }
        }

        Ok(substitutions)
    }

    /// Unify two triples and extend the substitution
    /// OPTIMIZED: Takes reference to avoid unnecessary clones
    fn unify_triple(
        &self,
        pattern: (&Term, &Term, &Term),
        fact: (&Term, &Term, &Term),
        substitution: &Substitution,
    ) -> Result<Option<Substitution>> {
        // Clone only once at the start - will be cheaper than cloning for every match attempt
        let mut new_substitution = substitution.clone();

        // Unify subject
        if !self.unify_terms(pattern.0, fact.0, &mut new_substitution)? {
            return Ok(None);
        }

        // Unify predicate
        if !self.unify_terms(pattern.1, fact.1, &mut new_substitution)? {
            return Ok(None);
        }

        // Unify object
        if !self.unify_terms(pattern.2, fact.2, &mut new_substitution)? {
            return Ok(None);
        }

        Ok(Some(new_substitution))
    }

    /// Unify two terms and update the substitution
    fn unify_terms(
        &self,
        pattern_term: &Term,
        fact_term: &Term,
        substitution: &mut Substitution,
    ) -> Result<bool> {
        match (pattern_term, fact_term) {
            // Variable in pattern
            (Term::Variable(var), fact_term) => {
                if let Some(existing) = substitution.get(var) {
                    // Check if consistent with existing binding
                    Ok(self.terms_equal(existing, fact_term))
                } else {
                    // Add new binding
                    substitution.insert(var.clone(), fact_term.clone());
                    Ok(true)
                }
            }
            // Variable in fact (shouldn't happen in forward chaining, but handle anyway)
            (fact_term, Term::Variable(var)) => {
                if let Some(existing) = substitution.get(var) {
                    Ok(self.terms_equal(existing, fact_term))
                } else {
                    substitution.insert(var.clone(), fact_term.clone());
                    Ok(true)
                }
            }
            // Both constants - must match exactly
            (Term::Constant(c1), Term::Constant(c2)) => Ok(c1 == c2),
            (Term::Literal(l1), Term::Literal(l2)) => Ok(l1 == l2),
            (Term::Constant(c), Term::Literal(l)) | (Term::Literal(l), Term::Constant(c)) => {
                Ok(c == l) // Allow constants and literals to unify if equal
            }
            // Function terms unify if name and args match
            (Term::Function { name: n1, args: a1 }, Term::Function { name: n2, args: a2 }) => {
                if n1 != n2 || a1.len() != a2.len() {
                    Ok(false)
                } else {
                    // Recursively unify all arguments
                    for (arg1, arg2) in a1.iter().zip(a2.iter()) {
                        if !self.unify_terms(arg1, arg2, substitution)? {
                            return Ok(false);
                        }
                    }
                    Ok(true)
                }
            }
            // Other combinations don't unify
            _ => Ok(false),
        }
    }

    /// Check if two terms are equal
    fn terms_equal(&self, term1: &Term, term2: &Term) -> bool {
        match (term1, term2) {
            (Term::Variable(v1), Term::Variable(v2)) => v1 == v2,
            (Term::Constant(c1), Term::Constant(c2)) => c1 == c2,
            (Term::Literal(l1), Term::Literal(l2)) => l1 == l2,
            (Term::Constant(c), Term::Literal(l)) | (Term::Literal(l), Term::Constant(c)) => c == l,
            (Term::Function { name: n1, args: a1 }, Term::Function { name: n2, args: a2 }) => {
                n1 == n2 && a1 == a2
            }
            _ => false,
        }
    }

    /// Compare two terms for ordering (-1: left < right, 0: equal, 1: left > right)
    fn compare_terms(&self, term1: &Term, term2: &Term) -> i32 {
        match (term1, term2) {
            (Term::Constant(c1), Term::Constant(c2)) => {
                // Try to parse as numbers first
                if let (Ok(n1), Ok(n2)) = (c1.parse::<f64>(), c2.parse::<f64>()) {
                    if n1 < n2 {
                        -1
                    } else if n1 > n2 {
                        1
                    } else {
                        0
                    }
                } else {
                    // Fallback to string comparison
                    if c1 < c2 {
                        -1
                    } else if c1 > c2 {
                        1
                    } else {
                        0
                    }
                }
            }
            (Term::Literal(l1), Term::Literal(l2)) => {
                // Try to parse as numbers first
                if let (Ok(n1), Ok(n2)) = (l1.parse::<f64>(), l2.parse::<f64>()) {
                    if n1 < n2 {
                        -1
                    } else if n1 > n2 {
                        1
                    } else {
                        0
                    }
                } else {
                    // Fallback to string comparison
                    if l1 < l2 {
                        -1
                    } else if l1 > l2 {
                        1
                    } else {
                        0
                    }
                }
            }
            (Term::Constant(c), Term::Literal(l)) | (Term::Literal(l), Term::Constant(c)) => {
                // Try to parse as numbers first
                if let (Ok(n1), Ok(n2)) = (c.parse::<f64>(), l.parse::<f64>()) {
                    if n1 < n2 {
                        -1
                    } else if n1 > n2 {
                        1
                    } else {
                        0
                    }
                } else {
                    // Fallback to string comparison
                    if c < l {
                        -1
                    } else if c > l {
                        1
                    } else {
                        0
                    }
                }
            }
            (Term::Function { name: n1, args: a1 }, Term::Function { name: n2, args: a2 }) => {
                // Compare function names first
                if n1 < n2 {
                    -1
                } else if n1 > n2 {
                    1
                } else {
                    // If names are equal, compare arg counts
                    if a1.len() < a2.len() {
                        -1
                    } else if a1.len() > a2.len() {
                        1
                    } else {
                        0
                    } // Equal functions
                }
            }
            // Variables and mixed types can't be compared meaningfully
            _ => 0,
        }
    }

    /// Apply substitution to an atom
    fn apply_substitution(&self, atom: &RuleAtom, substitution: &Substitution) -> Result<RuleAtom> {
        match atom {
            RuleAtom::Triple {
                subject,
                predicate,
                object,
            } => Ok(RuleAtom::Triple {
                subject: self.substitute_term(subject, substitution),
                predicate: self.substitute_term(predicate, substitution),
                object: self.substitute_term(object, substitution),
            }),
            RuleAtom::Builtin { name, args } => {
                let substituted_args = args
                    .iter()
                    .map(|arg| self.substitute_term(arg, substitution))
                    .collect();
                Ok(RuleAtom::Builtin {
                    name: name.clone(),
                    args: substituted_args,
                })
            }
            RuleAtom::NotEqual { left, right } => Ok(RuleAtom::NotEqual {
                left: self.substitute_term(left, substitution),
                right: self.substitute_term(right, substitution),
            }),
            RuleAtom::GreaterThan { left, right } => Ok(RuleAtom::GreaterThan {
                left: self.substitute_term(left, substitution),
                right: self.substitute_term(right, substitution),
            }),
            RuleAtom::LessThan { left, right } => Ok(RuleAtom::LessThan {
                left: self.substitute_term(left, substitution),
                right: self.substitute_term(right, substitution),
            }),
        }
    }

    /// Substitute variables in a term
    #[allow(clippy::only_used_in_recursion)]
    fn substitute_term(&self, term: &Term, substitution: &Substitution) -> Term {
        match term {
            Term::Variable(var) => substitution
                .get(var)
                .cloned()
                .unwrap_or_else(|| term.clone()),
            Term::Function { name, args } => {
                let substituted_args = args
                    .iter()
                    .map(|arg| self.substitute_term(arg, substitution))
                    .collect();
                Term::Function {
                    name: name.clone(),
                    args: substituted_args,
                }
            }
            _ => term.clone(),
        }
    }

    /// Evaluate built-in predicates
    /// OPTIMIZED: Takes reference to avoid unnecessary clones
    fn evaluate_builtin(
        &self,
        name: &str,
        args: &[Term],
        substitution: &Substitution,
    ) -> Result<Option<Substitution>> {
        match name {
            "equal" => {
                if args.len() != 2 {
                    return Err(anyhow::anyhow!("equal/2 requires exactly 2 arguments"));
                }
                let arg1 = self.substitute_term(&args[0], substitution);
                let arg2 = self.substitute_term(&args[1], substitution);
                if self.terms_equal(&arg1, &arg2) {
                    Ok(Some(substitution.clone()))
                } else {
                    Ok(None)
                }
            }
            "notEqual" => {
                if args.len() != 2 {
                    return Err(anyhow::anyhow!("notEqual/2 requires exactly 2 arguments"));
                }
                let arg1 = self.substitute_term(&args[0], substitution);
                let arg2 = self.substitute_term(&args[1], substitution);
                if !self.terms_equal(&arg1, &arg2) {
                    Ok(Some(substitution.clone()))
                } else {
                    Ok(None)
                }
            }
            "bound" => {
                if args.len() != 1 {
                    return Err(anyhow::anyhow!("bound/1 requires exactly 1 argument"));
                }
                match &args[0] {
                    Term::Variable(var) => {
                        if substitution.contains_key(var) {
                            Ok(Some(substitution.clone()))
                        } else {
                            Ok(None)
                        }
                    }
                    _ => Ok(Some(substitution.clone())), // Non-variables are always "bound"
                }
            }
            "unbound" => {
                if args.len() != 1 {
                    return Err(anyhow::anyhow!("unbound/1 requires exactly 1 argument"));
                }
                match &args[0] {
                    Term::Variable(var) => {
                        if !substitution.contains_key(var) {
                            Ok(Some(substitution.clone()))
                        } else {
                            Ok(None)
                        }
                    }
                    _ => Ok(None), // Non-variables are always "bound"
                }
            }
            _ => {
                warn!("Unknown built-in predicate: {}", name);
                Ok(None)
            }
        }
    }

    /// Get statistics about the inference process
    pub fn get_stats(&self) -> ForwardChainingStats {
        ForwardChainingStats {
            total_facts: self.facts.len(),
            total_rules: self.rules.len(),
        }
    }

    /// Check if a specific fact is derivable
    /// OPTIMIZED: Use count-based restoration instead of full clone
    pub fn can_derive(&mut self, target: &RuleAtom) -> Result<bool> {
        // Store initial count instead of cloning entire set
        let initial_count = self.facts.len();

        // Quick check: if already present, no need to infer
        if self.facts.contains(target) {
            return Ok(true);
        }

        // Collect initial facts into a vector for efficient restoration
        let initial_facts: Vec<RuleAtom> = self.facts.iter().cloned().collect();

        self.infer()?;
        let result = self.facts.contains(target);

        // Restore by removing new facts (cheaper than full clone for small deltas)
        if self.facts.len() > initial_count {
            FACT_SET_CLONES.inc();
            self.facts.clear();
            self.facts.extend(initial_facts);
        }

        Ok(result)
    }

    /// Derive all facts and return only the newly derived ones
    /// OPTIMIZED: Avoid full clone by using set difference efficiently
    pub fn derive_new_facts(&mut self) -> Result<Vec<RuleAtom>> {
        // Store initial facts as a vector for efficient difference computation
        let initial_facts: Vec<RuleAtom> = self.facts.iter().cloned().collect();
        let initial_set: HashSet<RuleAtom> = initial_facts.iter().cloned().collect();

        FACT_SET_CLONES.inc();

        self.infer()?;

        // Only collect the difference
        let new_facts: Vec<RuleAtom> = self.facts.difference(&initial_set).cloned().collect();

        Ok(new_facts)
    }
}

/// Statistics about forward chaining inference
#[derive(Debug, Clone)]
pub struct ForwardChainingStats {
    pub total_facts: usize,
    pub total_rules: usize,
}

impl std::fmt::Display for ForwardChainingStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Facts: {}, Rules: {}",
            self.total_facts, self.total_rules
        )
    }
}

/// Forward chaining result
#[derive(Debug, Clone)]
pub struct ForwardChainingResult {
    pub facts: Vec<RuleAtom>,
    pub iterations: usize,
    pub new_facts_derived: usize,
}

impl PartialEq for RuleAtom {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (
                RuleAtom::Triple {
                    subject: s1,
                    predicate: p1,
                    object: o1,
                },
                RuleAtom::Triple {
                    subject: s2,
                    predicate: p2,
                    object: o2,
                },
            ) => s1 == s2 && p1 == p2 && o1 == o2,
            (
                RuleAtom::Builtin { name: n1, args: a1 },
                RuleAtom::Builtin { name: n2, args: a2 },
            ) => n1 == n2 && a1 == a2,
            (
                RuleAtom::NotEqual {
                    left: l1,
                    right: r1,
                },
                RuleAtom::NotEqual {
                    left: l2,
                    right: r2,
                },
            ) => l1 == l2 && r1 == r2,
            (
                RuleAtom::GreaterThan {
                    left: l1,
                    right: r1,
                },
                RuleAtom::GreaterThan {
                    left: l2,
                    right: r2,
                },
            ) => l1 == l2 && r1 == r2,
            (
                RuleAtom::LessThan {
                    left: l1,
                    right: r1,
                },
                RuleAtom::LessThan {
                    left: l2,
                    right: r2,
                },
            ) => l1 == l2 && r1 == r2,
            _ => false,
        }
    }
}

impl Eq for RuleAtom {}

impl std::hash::Hash for RuleAtom {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        match self {
            RuleAtom::Triple {
                subject,
                predicate,
                object,
            } => {
                0.hash(state);
                subject.hash(state);
                predicate.hash(state);
                object.hash(state);
            }
            RuleAtom::Builtin { name, args } => {
                1.hash(state);
                name.hash(state);
                args.hash(state);
            }
            RuleAtom::NotEqual { left, right } => {
                2.hash(state);
                left.hash(state);
                right.hash(state);
            }
            RuleAtom::GreaterThan { left, right } => {
                3.hash(state);
                left.hash(state);
                right.hash(state);
            }
            RuleAtom::LessThan { left, right } => {
                4.hash(state);
                left.hash(state);
                right.hash(state);
            }
        }
    }
}

impl PartialEq for Term {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Term::Variable(v1), Term::Variable(v2)) => v1 == v2,
            (Term::Constant(c1), Term::Constant(c2)) => c1 == c2,
            (Term::Literal(l1), Term::Literal(l2)) => l1 == l2,
            (Term::Function { name: n1, args: a1 }, Term::Function { name: n2, args: a2 }) => {
                n1 == n2 && a1 == a2
            }
            _ => false,
        }
    }
}

impl Eq for Term {}

impl std::hash::Hash for Term {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        match self {
            Term::Variable(v) => {
                0.hash(state);
                v.hash(state);
            }
            Term::Constant(c) => {
                1.hash(state);
                c.hash(state);
            }
            Term::Literal(l) => {
                2.hash(state);
                l.hash(state);
            }
            Term::Function { name, args } => {
                3.hash(state);
                name.hash(state);
                args.hash(state);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_basic_forward_chaining() -> Result<(), Box<dyn std::error::Error>> {
        let mut chainer = ForwardChainer::new();

        // Add rule: mortal(X) :- human(X)
        chainer.add_rule(Rule {
            name: "mortality_rule".to_string(),
            body: vec![RuleAtom::Triple {
                subject: Term::Variable("X".to_string()),
                predicate: Term::Constant("type".to_string()),
                object: Term::Constant("human".to_string()),
            }],
            head: vec![RuleAtom::Triple {
                subject: Term::Variable("X".to_string()),
                predicate: Term::Constant("type".to_string()),
                object: Term::Constant("mortal".to_string()),
            }],
        });

        // Add fact: human(socrates)
        chainer.add_fact(RuleAtom::Triple {
            subject: Term::Constant("socrates".to_string()),
            predicate: Term::Constant("type".to_string()),
            object: Term::Constant("human".to_string()),
        });

        // Run inference
        let facts = chainer.infer()?;

        // Should derive: mortal(socrates)
        let expected = RuleAtom::Triple {
            subject: Term::Constant("socrates".to_string()),
            predicate: Term::Constant("type".to_string()),
            object: Term::Constant("mortal".to_string()),
        };

        assert!(facts.contains(&expected));
        Ok(())
    }

    #[test]
    fn test_transitive_chaining() -> Result<(), Box<dyn std::error::Error>> {
        let mut chainer = ForwardChainer::new();

        // Add rule: ancestor(X,Z) :- parent(X,Y), ancestor(Y,Z)
        chainer.add_rule(Rule {
            name: "transitive_ancestor".to_string(),
            body: vec![
                RuleAtom::Triple {
                    subject: Term::Variable("X".to_string()),
                    predicate: Term::Constant("parent".to_string()),
                    object: Term::Variable("Y".to_string()),
                },
                RuleAtom::Triple {
                    subject: Term::Variable("Y".to_string()),
                    predicate: Term::Constant("ancestor".to_string()),
                    object: Term::Variable("Z".to_string()),
                },
            ],
            head: vec![RuleAtom::Triple {
                subject: Term::Variable("X".to_string()),
                predicate: Term::Constant("ancestor".to_string()),
                object: Term::Variable("Z".to_string()),
            }],
        });

        // Add rule: ancestor(X,Y) :- parent(X,Y)
        chainer.add_rule(Rule {
            name: "direct_ancestor".to_string(),
            body: vec![RuleAtom::Triple {
                subject: Term::Variable("X".to_string()),
                predicate: Term::Constant("parent".to_string()),
                object: Term::Variable("Y".to_string()),
            }],
            head: vec![RuleAtom::Triple {
                subject: Term::Variable("X".to_string()),
                predicate: Term::Constant("ancestor".to_string()),
                object: Term::Variable("Y".to_string()),
            }],
        });

        // Add facts
        chainer.add_fact(RuleAtom::Triple {
            subject: Term::Constant("john".to_string()),
            predicate: Term::Constant("parent".to_string()),
            object: Term::Constant("mary".to_string()),
        });
        chainer.add_fact(RuleAtom::Triple {
            subject: Term::Constant("mary".to_string()),
            predicate: Term::Constant("parent".to_string()),
            object: Term::Constant("bob".to_string()),
        });

        // Run inference
        let facts = chainer.infer()?;

        // Should derive ancestor relationships
        assert!(facts.contains(&RuleAtom::Triple {
            subject: Term::Constant("john".to_string()),
            predicate: Term::Constant("ancestor".to_string()),
            object: Term::Constant("mary".to_string()),
        }));
        assert!(facts.contains(&RuleAtom::Triple {
            subject: Term::Constant("mary".to_string()),
            predicate: Term::Constant("ancestor".to_string()),
            object: Term::Constant("bob".to_string()),
        }));
        assert!(facts.contains(&RuleAtom::Triple {
            subject: Term::Constant("john".to_string()),
            predicate: Term::Constant("ancestor".to_string()),
            object: Term::Constant("bob".to_string()),
        }));
        Ok(())
    }

    #[test]
    fn test_builtin_predicates() -> Result<(), Box<dyn std::error::Error>> {
        let mut chainer = ForwardChainer::new();

        // Add rule with built-in: same(X,X) :- bound(X)
        chainer.add_rule(Rule {
            name: "reflexive_same".to_string(),
            body: vec![
                RuleAtom::Triple {
                    subject: Term::Variable("X".to_string()),
                    predicate: Term::Constant("exists".to_string()),
                    object: Term::Constant("true".to_string()),
                },
                RuleAtom::Builtin {
                    name: "bound".to_string(),
                    args: vec![Term::Variable("X".to_string())],
                },
            ],
            head: vec![RuleAtom::Triple {
                subject: Term::Variable("X".to_string()),
                predicate: Term::Constant("same".to_string()),
                object: Term::Variable("X".to_string()),
            }],
        });

        chainer.add_fact(RuleAtom::Triple {
            subject: Term::Constant("a".to_string()),
            predicate: Term::Constant("exists".to_string()),
            object: Term::Constant("true".to_string()),
        });

        let facts = chainer.infer()?;

        assert!(facts.contains(&RuleAtom::Triple {
            subject: Term::Constant("a".to_string()),
            predicate: Term::Constant("same".to_string()),
            object: Term::Constant("a".to_string()),
        }));
        Ok(())
    }
}