1use crate::{Rule, RuleAtom, Term};
42use anyhow::{anyhow, Context, Result};
43use regex::Regex;
44use std::collections::HashMap;
45use tracing::{info, warn};
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum SourceFormat {
50 Jena,
52 Drools,
54 Clips,
56}
57
58impl SourceFormat {
59 pub fn name(&self) -> &str {
61 match self {
62 Self::Jena => "Apache Jena",
63 Self::Drools => "Drools DRL",
64 Self::Clips => "CLIPS",
65 }
66 }
67}
68
69#[derive(Debug, Clone)]
71pub struct MigrationWarning {
72 pub message: String,
74 pub line: Option<usize>,
76 pub severity: WarningSeverity,
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum WarningSeverity {
83 Info,
84 Warning,
85 Error,
86}
87
88#[derive(Debug)]
90pub struct MigrationResult {
91 pub rules: Vec<Rule>,
93 pub warnings: Vec<MigrationWarning>,
95 pub source_format: SourceFormat,
97 pub original_count: usize,
99 pub migrated_count: usize,
101}
102
103impl MigrationResult {
104 pub fn generate_report(&self) -> String {
106 let mut report = String::new();
107 report.push_str("═══════════════════════════════════════════════════════════════\n");
108 report.push_str(&format!(
109 " Migration Report: {} → OxiRS\n",
110 self.source_format.name()
111 ));
112 report.push_str("═══════════════════════════════════════════════════════════════\n\n");
113
114 report.push_str(&format!("Original rules: {}\n", self.original_count));
115 report.push_str(&format!("Migrated rules: {}\n", self.migrated_count));
116 report.push_str(&format!(
117 "Success rate: {:.1}%\n\n",
118 (self.migrated_count as f64 / self.original_count as f64) * 100.0
119 ));
120
121 if !self.warnings.is_empty() {
122 report.push_str("Warnings:\n");
123 report.push_str("─────────────────────────────────────────────────────────────\n");
124
125 let mut errors = 0;
126 let mut warnings = 0;
127 let mut infos = 0;
128
129 for warning in &self.warnings {
130 let prefix = match warning.severity {
131 WarningSeverity::Error => {
132 errors += 1;
133 "ERROR"
134 }
135 WarningSeverity::Warning => {
136 warnings += 1;
137 "WARN"
138 }
139 WarningSeverity::Info => {
140 infos += 1;
141 "INFO"
142 }
143 };
144
145 if let Some(line) = warning.line {
146 report.push_str(&format!(
147 " [{}] Line {}: {}\n",
148 prefix, line, warning.message
149 ));
150 } else {
151 report.push_str(&format!(" [{}] {}\n", prefix, warning.message));
152 }
153 }
154
155 report.push_str(&format!(
156 "\nSummary: {} errors, {} warnings, {} info\n",
157 errors, warnings, infos
158 ));
159 }
160
161 report.push_str("\n═══════════════════════════════════════════════════════════════\n");
162 report
163 }
164
165 pub fn is_successful(&self) -> bool {
167 self.warnings
168 .iter()
169 .all(|w| w.severity != WarningSeverity::Error)
170 }
171}
172
173pub struct MigrationTool {
175 strict_mode: bool,
177 namespace_mappings: HashMap<String, String>,
179}
180
181impl Default for MigrationTool {
182 fn default() -> Self {
183 Self::new()
184 }
185}
186
187impl MigrationTool {
188 pub fn new() -> Self {
190 Self {
191 strict_mode: false,
192 namespace_mappings: HashMap::new(),
193 }
194 }
195
196 pub fn with_strict_mode(mut self, strict: bool) -> Self {
198 self.strict_mode = strict;
199 self
200 }
201
202 pub fn add_namespace_mapping(&mut self, from: &str, to: &str) {
204 self.namespace_mappings
205 .insert(from.to_string(), to.to_string());
206 }
207
208 pub fn migrate(&mut self, source: &str, format: SourceFormat) -> Result<MigrationResult> {
210 info!("Starting migration from {}", format.name());
211
212 let mut warnings = Vec::new();
213 let rules = match format {
214 SourceFormat::Jena => self.migrate_jena(source, &mut warnings)?,
215 SourceFormat::Drools => self.migrate_drools(source, &mut warnings)?,
216 SourceFormat::Clips => self.migrate_clips(source, &mut warnings)?,
217 };
218
219 let original_count = source
220 .lines()
221 .filter(|line| {
222 let trimmed = line.trim();
223 !trimmed.is_empty() && !trimmed.starts_with('#') && !trimmed.starts_with("//")
224 })
225 .count();
226
227 Ok(MigrationResult {
228 migrated_count: rules.len(),
229 rules,
230 warnings,
231 source_format: format,
232 original_count,
233 })
234 }
235
236 fn migrate_jena(
238 &mut self,
239 source: &str,
240 warnings: &mut Vec<MigrationWarning>,
241 ) -> Result<Vec<Rule>> {
242 let mut rules = Vec::new();
243
244 let rule_regex = Regex::new(r"\[(\w+):\s*(.+?)\s*->\s*(.+?)\]")
246 .context("Failed to compile Jena rule regex")?;
247
248 for (line_num, line) in source.lines().enumerate() {
249 let trimmed = line.trim();
250 if trimmed.is_empty() || trimmed.starts_with('#') {
251 continue;
252 }
253
254 if let Some(captures) = rule_regex.captures(trimmed) {
255 let rule_name = captures.get(1).expect("regex capture group 1").as_str();
256 let body_str = captures.get(2).expect("regex capture group 2").as_str();
257 let head_str = captures.get(3).expect("regex capture group 3").as_str();
258
259 match self.parse_jena_atoms(body_str, head_str, rule_name) {
260 Ok(rule) => rules.push(rule),
261 Err(e) => {
262 warnings.push(MigrationWarning {
263 message: format!("Failed to parse rule '{}': {}", rule_name, e),
264 line: Some(line_num + 1),
265 severity: if self.strict_mode {
266 WarningSeverity::Error
267 } else {
268 WarningSeverity::Warning
269 },
270 });
271 }
272 }
273 } else {
274 warnings.push(MigrationWarning {
275 message: format!("Could not parse Jena rule syntax: {}", trimmed),
276 line: Some(line_num + 1),
277 severity: WarningSeverity::Warning,
278 });
279 }
280 }
281
282 info!("Migrated {} Jena rules", rules.len());
283 Ok(rules)
284 }
285
286 fn parse_jena_atoms(&self, body_str: &str, head_str: &str, rule_name: &str) -> Result<Rule> {
288 let body = self.parse_jena_triples(body_str)?;
289 let head = self.parse_jena_triples(head_str)?;
290
291 Ok(Rule {
292 name: rule_name.to_string(),
293 body,
294 head,
295 })
296 }
297
298 fn parse_jena_triples(&self, patterns: &str) -> Result<Vec<RuleAtom>> {
300 let mut atoms = Vec::new();
301
302 for pattern in patterns.split(',') {
304 let pattern = pattern.trim();
305 if pattern.is_empty() {
306 continue;
307 }
308
309 let pattern = pattern.strip_prefix('(').unwrap_or(pattern);
311 let pattern = pattern.strip_suffix(')').unwrap_or(pattern);
312
313 let parts: Vec<&str> = pattern.split_whitespace().collect();
315 if parts.len() == 3 {
316 atoms.push(RuleAtom::Triple {
317 subject: self.parse_jena_term(parts[0])?,
318 predicate: self.parse_jena_term(parts[1])?,
319 object: self.parse_jena_term(parts[2])?,
320 });
321 } else {
322 return Err(anyhow!("Invalid triple pattern: {}", pattern));
323 }
324 }
325
326 Ok(atoms)
327 }
328
329 fn parse_jena_term(&self, term: &str) -> Result<Term> {
331 if let Some(var_name) = term.strip_prefix('?') {
332 Ok(Term::Variable(var_name.to_string()))
334 } else if term.starts_with('"') && term.ends_with('"') {
335 Ok(Term::Literal(term[1..term.len() - 1].to_string()))
337 } else {
338 let expanded = self.expand_namespace(term);
340 Ok(Term::Constant(expanded))
341 }
342 }
343
344 fn migrate_drools(
346 &mut self,
347 source: &str,
348 warnings: &mut Vec<MigrationWarning>,
349 ) -> Result<Vec<Rule>> {
350 let mut rules = Vec::new();
351
352 let rule_regex = Regex::new(r#"rule\s+"([^"]+)"\s+when\s+(.+?)\s+then\s+(.+?)\s+end"#)
356 .context("Failed to compile Drools rule regex")?;
357
358 for (line_num, captures) in rule_regex.captures_iter(source).enumerate() {
359 let rule_name = captures.get(1).expect("regex capture group 1").as_str();
360 let when_clause = captures.get(2).expect("regex capture group 2").as_str();
361 let then_clause = captures.get(3).expect("regex capture group 3").as_str();
362
363 match self.parse_drools_rule(rule_name, when_clause, then_clause) {
365 Ok(rule) => {
366 if !rule.body.is_empty() || !rule.head.is_empty() {
367 rules.push(rule);
368 warnings.push(MigrationWarning {
369 message: format!(
370 "Drools rule '{}' migrated - complex DRL features (Java code, salience, etc.) not supported",
371 rule_name
372 ),
373 line: Some(line_num + 1),
374 severity: WarningSeverity::Info,
375 });
376 } else {
377 warnings.push(MigrationWarning {
378 message: format!(
379 "Drools rule '{}' skipped - no parseable patterns found",
380 rule_name
381 ),
382 line: Some(line_num + 1),
383 severity: WarningSeverity::Warning,
384 });
385 }
386 }
387 Err(e) => {
388 warnings.push(MigrationWarning {
389 message: format!("Failed to parse Drools rule '{}': {}", rule_name, e),
390 line: Some(line_num + 1),
391 severity: WarningSeverity::Error,
392 });
393 }
394 }
395 }
396
397 info!("Migrated {} Drools rules", rules.len());
398 Ok(rules)
399 }
400
401 fn parse_drools_rule(&self, name: &str, when_clause: &str, then_clause: &str) -> Result<Rule> {
403 let body = self.parse_drools_when_clause(when_clause)?;
405
406 let head = self.parse_drools_then_clause(then_clause)?;
408
409 if body.is_empty() && head.is_empty() {
410 warn!(
411 "Drools rule '{}' has no parseable conditions or actions",
412 name
413 );
414 }
415
416 Ok(Rule {
417 name: name.to_string(),
418 body,
419 head,
420 })
421 }
422
423 fn parse_drools_when_clause(&self, when_clause: &str) -> Result<Vec<RuleAtom>> {
425 let mut atoms = Vec::new();
426
427 let pattern_regex =
429 Regex::new(r"(\w+)\s*\((.*?)\)").context("Failed to compile Drools pattern regex")?;
430
431 for captures in pattern_regex.captures_iter(when_clause) {
432 let class_name = captures.get(1).expect("regex capture group 1").as_str();
433 let conditions = captures.get(2).expect("regex capture group 2").as_str();
434
435 for condition in conditions.split(',') {
437 let condition = condition.trim();
438 if condition.is_empty() {
439 continue;
440 }
441
442 if let Some((field, value)) = self.parse_drools_condition(condition) {
444 atoms.push(RuleAtom::Triple {
446 subject: Term::Variable(format!("{}Instance", class_name)),
447 predicate: Term::Constant(field),
448 object: self.parse_drools_value(&value),
449 });
450 }
451 }
452
453 atoms.push(RuleAtom::Triple {
455 subject: Term::Variable(format!("{}Instance", class_name)),
456 predicate: Term::Constant("rdf:type".to_string()),
457 object: Term::Constant(class_name.to_string()),
458 });
459 }
460
461 Ok(atoms)
462 }
463
464 fn parse_drools_then_clause(&self, then_clause: &str) -> Result<Vec<RuleAtom>> {
466 let mut atoms = Vec::new();
467
468 let insert_regex = Regex::new(r"insert\s*\(\s*new\s+(\w+)\s*\((.*?)\)\s*\)")
470 .context("Failed to compile Drools insert regex")?;
471
472 for captures in insert_regex.captures_iter(then_clause) {
473 let class_name = captures.get(1).expect("regex capture group 1").as_str();
474 let params = captures.get(2).expect("regex capture group 2").as_str();
475
476 atoms.push(RuleAtom::Triple {
478 subject: Term::Variable(format!("new{}", class_name)),
479 predicate: Term::Constant("rdf:type".to_string()),
480 object: Term::Constant(class_name.to_string()),
481 });
482
483 for param in params.split(',') {
485 let param = param.trim();
486 if let Some((field, value)) = self.parse_drools_condition(param) {
487 atoms.push(RuleAtom::Triple {
488 subject: Term::Variable(format!("new{}", class_name)),
489 predicate: Term::Constant(field),
490 object: self.parse_drools_value(&value),
491 });
492 }
493 }
494 }
495
496 let modify_regex = Regex::new(r"modify\s*\(\s*(\w+)\s*\)\s*\{([^}]+)\}")
498 .context("Failed to compile Drools modify regex")?;
499
500 let setter_regex =
502 Regex::new(r"set(\w+)\s*\(([^)]+)\)").context("Failed to compile setter regex")?;
503
504 for captures in modify_regex.captures_iter(then_clause) {
505 let var_name = captures.get(1).expect("regex capture group 1").as_str();
506 let modifications = captures.get(2).expect("regex capture group 2").as_str();
507
508 for setter_captures in setter_regex.captures_iter(modifications) {
509 let field_name = setter_captures
510 .get(1)
511 .expect("regex capture group 1")
512 .as_str();
513 let value = setter_captures
514 .get(2)
515 .expect("regex capture group 2")
516 .as_str()
517 .trim();
518
519 atoms.push(RuleAtom::Triple {
520 subject: Term::Variable(var_name.to_string()),
521 predicate: Term::Constant(field_name.to_string()),
522 object: self.parse_drools_value(value),
523 });
524 }
525 }
526
527 Ok(atoms)
528 }
529
530 fn parse_drools_condition(&self, condition: &str) -> Option<(String, String)> {
532 if let Some(eq_pos) = condition.find("==") {
534 let field = condition[..eq_pos].trim().to_string();
535 let value = condition[eq_pos + 2..].trim().to_string();
536 return Some((field, value));
537 }
538
539 if let Some(colon_pos) = condition.find(':') {
541 let field = condition[..colon_pos].trim().to_string();
542 let value = condition[colon_pos + 1..].trim().to_string();
543 return Some((field, value));
544 }
545
546 None
547 }
548
549 fn parse_drools_value(&self, value: &str) -> Term {
551 let value = value.trim();
552
553 if (value.starts_with('"') && value.ends_with('"'))
555 || (value.starts_with('\'') && value.ends_with('\''))
556 {
557 return Term::Literal(value[1..value.len() - 1].to_string());
558 }
559
560 if let Some(var_name) = value.strip_prefix('$') {
562 return Term::Variable(var_name.to_string());
563 }
564
565 if value
567 .chars()
568 .all(|c| c.is_numeric() || c == '.' || c == '-')
569 {
570 Term::Literal(value.to_string())
571 } else {
572 Term::Constant(value.to_string())
573 }
574 }
575
576 fn migrate_clips(
578 &mut self,
579 source: &str,
580 warnings: &mut Vec<MigrationWarning>,
581 ) -> Result<Vec<Rule>> {
582 let mut rules = Vec::new();
583
584 let rule_regex = Regex::new(r"\(defrule\s+(\S+)\s+(.+?)\s+=>\s+(.+?)\)")
586 .context("Failed to compile CLIPS rule regex")?;
587
588 for (line_num, captures) in rule_regex.captures_iter(source).enumerate() {
589 let rule_name = captures.get(1).expect("regex capture group 1").as_str();
590 let pattern_clause = captures.get(2).expect("regex capture group 2").as_str();
591 let action_clause = captures.get(3).expect("regex capture group 3").as_str();
592
593 match self.parse_clips_rule(rule_name, pattern_clause, action_clause) {
594 Ok(rule) => {
595 if !rule.body.is_empty() || !rule.head.is_empty() {
596 rules.push(rule);
597 warnings.push(MigrationWarning {
598 message: format!(
599 "CLIPS rule '{}' migrated - procedural attachments and advanced features not supported",
600 rule_name
601 ),
602 line: Some(line_num + 1),
603 severity: WarningSeverity::Info,
604 });
605 } else {
606 warnings.push(MigrationWarning {
607 message: format!(
608 "CLIPS rule '{}' skipped - no parseable patterns found",
609 rule_name
610 ),
611 line: Some(line_num + 1),
612 severity: WarningSeverity::Warning,
613 });
614 }
615 }
616 Err(e) => {
617 warnings.push(MigrationWarning {
618 message: format!("Failed to parse CLIPS rule '{}': {}", rule_name, e),
619 line: Some(line_num + 1),
620 severity: WarningSeverity::Error,
621 });
622 }
623 }
624 }
625
626 info!("Migrated {} CLIPS rules", rules.len());
627 Ok(rules)
628 }
629
630 fn parse_clips_rule(
632 &self,
633 name: &str,
634 pattern_clause: &str,
635 action_clause: &str,
636 ) -> Result<Rule> {
637 let body = self.parse_clips_patterns(pattern_clause)?;
639
640 let head = self.parse_clips_actions(action_clause)?;
642
643 if body.is_empty() && head.is_empty() {
644 warn!("CLIPS rule '{}' has no parseable patterns or actions", name);
645 }
646
647 Ok(Rule {
648 name: name.to_string(),
649 body,
650 head,
651 })
652 }
653
654 fn parse_clips_patterns(&self, patterns: &str) -> Result<Vec<RuleAtom>> {
656 let mut atoms = Vec::new();
657
658 let pattern_regex = Regex::new(r"\((\w+)(?:\s+\(([^)]+)\))*\)")
660 .context("Failed to compile CLIPS pattern regex")?;
661
662 for captures in pattern_regex.captures_iter(patterns) {
663 let template_name = captures.get(1).expect("regex capture group 1").as_str();
664
665 if template_name == "test"
667 || template_name == "not"
668 || template_name == "and"
669 || template_name == "or"
670 {
671 continue;
672 }
673
674 atoms.push(RuleAtom::Triple {
676 subject: Term::Variable(format!("{}Instance", template_name)),
677 predicate: Term::Constant("rdf:type".to_string()),
678 object: Term::Constant(template_name.to_string()),
679 });
680
681 if let Some(slots) = captures.get(2) {
683 let slot_text = slots.as_str();
684 let slot_parts: Vec<&str> = slot_text.split_whitespace().collect();
686
687 if slot_parts.len() >= 2 {
688 let slot_name = slot_parts[0];
689 let slot_value = slot_parts[1];
690
691 atoms.push(RuleAtom::Triple {
692 subject: Term::Variable(format!("{}Instance", template_name)),
693 predicate: Term::Constant(slot_name.to_string()),
694 object: self.parse_clips_value(slot_value),
695 });
696 }
697 }
698 }
699
700 Ok(atoms)
701 }
702
703 fn parse_clips_actions(&self, actions: &str) -> Result<Vec<RuleAtom>> {
705 let mut atoms = Vec::new();
706
707 let assert_regex = Regex::new(r"\(assert\s+\((\w+)(?:\s+\(([^)]+)\))*\)\)")
709 .context("Failed to compile CLIPS assert regex")?;
710
711 for captures in assert_regex.captures_iter(actions) {
712 let template_name = captures.get(1).expect("regex capture group 1").as_str();
713
714 atoms.push(RuleAtom::Triple {
716 subject: Term::Variable(format!("new{}", template_name)),
717 predicate: Term::Constant("rdf:type".to_string()),
718 object: Term::Constant(template_name.to_string()),
719 });
720
721 if let Some(slots) = captures.get(2) {
723 let slot_text = slots.as_str();
724 let slot_parts: Vec<&str> = slot_text.split_whitespace().collect();
725
726 if slot_parts.len() >= 2 {
727 let slot_name = slot_parts[0];
728 let slot_value = slot_parts[1];
729
730 atoms.push(RuleAtom::Triple {
731 subject: Term::Variable(format!("new{}", template_name)),
732 predicate: Term::Constant(slot_name.to_string()),
733 object: self.parse_clips_value(slot_value),
734 });
735 }
736 }
737 }
738
739 let modify_regex = Regex::new(r"\(modify\s+\?(\w+)\s+\((\w+)\s+([^)]+)\)\)")
741 .context("Failed to compile CLIPS modify regex")?;
742
743 for captures in modify_regex.captures_iter(actions) {
744 let var_name = captures.get(1).expect("regex capture group 1").as_str();
745 let slot_name = captures.get(2).expect("regex capture group 2").as_str();
746 let slot_value = captures.get(3).expect("regex capture group 3").as_str();
747
748 atoms.push(RuleAtom::Triple {
749 subject: Term::Variable(var_name.to_string()),
750 predicate: Term::Constant(slot_name.to_string()),
751 object: self.parse_clips_value(slot_value),
752 });
753 }
754
755 Ok(atoms)
756 }
757
758 fn parse_clips_value(&self, value: &str) -> Term {
760 let value = value.trim();
761
762 if let Some(var_name) = value.strip_prefix('?') {
764 return Term::Variable(var_name.to_string());
765 }
766
767 if (value.starts_with('"') && value.ends_with('"'))
769 || (value.starts_with('\'') && value.ends_with('\''))
770 {
771 return Term::Literal(value[1..value.len() - 1].to_string());
772 }
773
774 if value
776 .chars()
777 .all(|c| c.is_numeric() || c == '.' || c == '-')
778 {
779 Term::Literal(value.to_string())
780 } else {
781 Term::Constant(value.to_string())
782 }
783 }
784
785 fn expand_namespace(&self, term: &str) -> String {
787 if let Some(colon_pos) = term.find(':') {
788 let prefix = &term[..colon_pos];
789 let local = &term[colon_pos + 1..];
790
791 if let Some(namespace) = self.namespace_mappings.get(prefix) {
792 return format!("{}{}", namespace, local);
793 }
794 }
795 term.to_string()
796 }
797}
798
799#[cfg(test)]
800mod tests {
801 use super::*;
802
803 #[test]
804 fn test_migration_tool_creation() {
805 let tool = MigrationTool::new();
806 assert!(!tool.strict_mode);
807 assert!(tool.namespace_mappings.is_empty());
808 }
809
810 #[test]
811 fn test_migration_tool_with_strict_mode() {
812 let tool = MigrationTool::new().with_strict_mode(true);
813 assert!(tool.strict_mode);
814 }
815
816 #[test]
817 fn test_namespace_mapping() {
818 let mut tool = MigrationTool::new();
819 tool.add_namespace_mapping("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
820
821 assert_eq!(
822 tool.namespace_mappings.get("rdf"),
823 Some(&"http://www.w3.org/1999/02/22-rdf-syntax-ns#".to_string())
824 );
825 }
826
827 #[test]
828 fn test_jena_simple_rule_migration() -> Result<(), Box<dyn std::error::Error>> {
829 let mut tool = MigrationTool::new();
830
831 let jena_rules = r#"
832[rule1: (?a rdf:type Person) -> (?a rdf:type Human)]
833"#;
834
835 let result = tool.migrate(jena_rules, SourceFormat::Jena)?;
836
837 assert_eq!(result.rules.len(), 1);
838 assert_eq!(result.rules[0].name, "rule1");
839 assert_eq!(result.source_format, SourceFormat::Jena);
840 Ok(())
841 }
842
843 #[test]
844 fn test_jena_multiple_rules() -> Result<(), Box<dyn std::error::Error>> {
845 let mut tool = MigrationTool::new();
846
847 let jena_rules = r#"
848[rule1: (?x parent ?y) -> (?y hasParent ?x)]
849[rule2: (?a knows ?b) -> (?b knows ?a)]
850"#;
851
852 let result = tool.migrate(jena_rules, SourceFormat::Jena)?;
853
854 assert_eq!(result.rules.len(), 2);
855 assert_eq!(result.rules[0].name, "rule1");
856 assert_eq!(result.rules[1].name, "rule2");
857 Ok(())
858 }
859
860 #[test]
861 fn test_jena_with_comments() -> Result<(), Box<dyn std::error::Error>> {
862 let mut tool = MigrationTool::new();
863
864 let jena_rules = r#"
865# This is a comment
866[rule1: (?x parent ?y) -> (?y hasParent ?x)]
867# Another comment
868[rule2: (?a knows ?b) -> (?b knows ?a)]
869"#;
870
871 let result = tool.migrate(jena_rules, SourceFormat::Jena)?;
872
873 assert_eq!(result.rules.len(), 2);
874 Ok(())
875 }
876
877 #[test]
878 fn test_parse_jena_term_variable() -> Result<(), Box<dyn std::error::Error>> {
879 let tool = MigrationTool::new();
880
881 let term = tool.parse_jena_term("?x")?;
882 assert!(matches!(term, Term::Variable(v) if v == "x"));
883 Ok(())
884 }
885
886 #[test]
887 fn test_parse_jena_term_constant() -> Result<(), Box<dyn std::error::Error>> {
888 let tool = MigrationTool::new();
889
890 let term = tool.parse_jena_term("rdf:type")?;
891 assert!(matches!(term, Term::Constant(c) if c == "rdf:type"));
892 Ok(())
893 }
894
895 #[test]
896 fn test_parse_jena_term_literal() -> Result<(), Box<dyn std::error::Error>> {
897 let tool = MigrationTool::new();
898
899 let term = tool.parse_jena_term("\"John\"")?;
900 assert!(matches!(term, Term::Literal(l) if l == "John"));
901 Ok(())
902 }
903
904 #[test]
905 fn test_migration_report_generation() {
906 let result = MigrationResult {
907 rules: vec![],
908 warnings: vec![MigrationWarning {
909 message: "Test warning".to_string(),
910 line: Some(1),
911 severity: WarningSeverity::Warning,
912 }],
913 source_format: SourceFormat::Jena,
914 original_count: 10,
915 migrated_count: 9,
916 };
917
918 let report = result.generate_report();
919
920 assert!(report.contains("Apache Jena"));
921 assert!(report.contains("Original rules: 10"));
922 assert!(report.contains("Migrated rules: 9"));
923 assert!(report.contains("Test warning"));
924 }
925
926 #[test]
927 fn test_migration_success_check() {
928 let result_success = MigrationResult {
929 rules: vec![],
930 warnings: vec![MigrationWarning {
931 message: "Info".to_string(),
932 line: None,
933 severity: WarningSeverity::Info,
934 }],
935 source_format: SourceFormat::Jena,
936 original_count: 1,
937 migrated_count: 1,
938 };
939
940 assert!(result_success.is_successful());
941
942 let result_failure = MigrationResult {
943 rules: vec![],
944 warnings: vec![MigrationWarning {
945 message: "Error".to_string(),
946 line: None,
947 severity: WarningSeverity::Error,
948 }],
949 source_format: SourceFormat::Jena,
950 original_count: 1,
951 migrated_count: 0,
952 };
953
954 assert!(!result_failure.is_successful());
955 }
956
957 #[test]
958 fn test_expand_namespace() {
959 let mut tool = MigrationTool::new();
960 tool.add_namespace_mapping("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
961
962 let expanded = tool.expand_namespace("rdf:type");
963 assert_eq!(expanded, "http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
964 }
965
966 #[test]
967 fn test_source_format_names() {
968 assert_eq!(SourceFormat::Jena.name(), "Apache Jena");
969 assert_eq!(SourceFormat::Drools.name(), "Drools DRL");
970 assert_eq!(SourceFormat::Clips.name(), "CLIPS");
971 }
972
973 #[test]
974 fn test_drools_simple_rule() -> Result<(), Box<dyn std::error::Error>> {
975 let mut tool = MigrationTool::new();
976
977 let drools_rules = r#"
978rule "adult-rule"
979when
980 Person(age == 25)
981then
982 insert(new Adult(status: "verified"))
983end
984"#;
985
986 let result = tool.migrate(drools_rules, SourceFormat::Drools)?;
987
988 assert_eq!(result.rules.len(), 1);
989 assert_eq!(result.rules[0].name, "adult-rule");
990 assert!(!result.rules[0].body.is_empty());
991 assert!(!result.rules[0].head.is_empty());
992 Ok(())
993 }
994
995 #[test]
996 fn test_drools_with_insert() -> Result<(), Box<dyn std::error::Error>> {
997 let mut tool = MigrationTool::new();
998
999 let drools_rules = r#"
1000rule "create-employee"
1001when
1002 Person(name == "John")
1003then
1004 insert(new Employee(name: "John", role: "Developer"))
1005end
1006"#;
1007
1008 let result = tool.migrate(drools_rules, SourceFormat::Drools)?;
1009
1010 assert_eq!(result.rules.len(), 1);
1011 let rule = &result.rules[0];
1012
1013 assert!(rule.head.iter().any(|atom| {
1015 matches!(atom, RuleAtom::Triple {
1016 predicate: Term::Constant(p),
1017 object: Term::Constant(o), ..
1018 } if p == "rdf:type" && o == "Employee")
1019 }));
1020 Ok(())
1021 }
1022
1023 #[test]
1024 fn test_drools_with_modify() -> Result<(), Box<dyn std::error::Error>> {
1025 let mut tool = MigrationTool::new();
1026
1027 let drools_rules = r#"
1028rule "update-status"
1029when
1030 Person(name == "Alice")
1031then
1032 modify(person) { setStatus("active") }
1033end
1034"#;
1035
1036 let result = tool.migrate(drools_rules, SourceFormat::Drools)?;
1037
1038 assert_eq!(result.rules.len(), 1);
1039 let rule = &result.rules[0];
1040
1041 assert!(rule.head.iter().any(|atom| {
1043 matches!(atom, RuleAtom::Triple {
1044 predicate: Term::Constant(p), ..
1045 } if p == "Status")
1046 }));
1047 Ok(())
1048 }
1049
1050 #[test]
1051 fn test_drools_value_parsing() {
1052 let tool = MigrationTool::new();
1053
1054 let value1 = tool.parse_drools_value("\"hello\"");
1056 assert!(matches!(value1, Term::Literal(v) if v == "hello"));
1057
1058 let value2 = tool.parse_drools_value("$var");
1060 assert!(matches!(value2, Term::Variable(v) if v == "var"));
1061
1062 let value3 = tool.parse_drools_value("42");
1064 assert!(matches!(value3, Term::Literal(v) if v == "42"));
1065
1066 let value4 = tool.parse_drools_value("active");
1068 assert!(matches!(value4, Term::Constant(v) if v == "active"));
1069 }
1070
1071 #[test]
1072 fn test_drools_condition_parsing() -> Result<(), Box<dyn std::error::Error>> {
1073 let tool = MigrationTool::new();
1074
1075 let (field, value) = tool
1077 .parse_drools_condition("age == 18")
1078 .ok_or("expected Some value")?;
1079 assert_eq!(field, "age");
1080 assert_eq!(value, "18");
1081
1082 let (field2, value2) = tool
1084 .parse_drools_condition("status : active")
1085 .ok_or("expected Some value")?;
1086 assert_eq!(field2, "status");
1087 assert_eq!(value2, "active");
1088 Ok(())
1089 }
1090
1091 #[test]
1092 fn test_clips_simple_rule() -> Result<(), Box<dyn std::error::Error>> {
1093 let mut tool = MigrationTool::new();
1094
1095 let clips_rules = r#"
1096(defrule adult-check (person (age 25)) => (assert (adult (verified yes))))
1097"#;
1098
1099 let result = tool.migrate(clips_rules, SourceFormat::Clips)?;
1100
1101 assert_eq!(result.rules.len(), 1);
1102 assert_eq!(result.rules[0].name, "adult-check");
1103 Ok(())
1104 }
1105
1106 #[test]
1107 fn test_clips_with_assert() -> Result<(), Box<dyn std::error::Error>> {
1108 let mut tool = MigrationTool::new();
1109
1110 let clips_rules = r#"
1111(defrule make-employee (person (name John)) => (assert (employee (name John))))
1112"#;
1113
1114 let result = tool.migrate(clips_rules, SourceFormat::Clips)?;
1115
1116 assert_eq!(result.rules.len(), 1);
1118 assert_eq!(result.rules[0].name, "make-employee");
1119
1120 assert!(result.source_format == SourceFormat::Clips);
1122 Ok(())
1123 }
1124
1125 #[test]
1126 fn test_clips_with_modify() -> Result<(), Box<dyn std::error::Error>> {
1127 let mut tool = MigrationTool::new();
1128
1129 let clips_rules = r#"
1130(defrule update-status (person) => (modify ?person (status active)))
1131"#;
1132
1133 let result = tool.migrate(clips_rules, SourceFormat::Clips)?;
1134
1135 assert_eq!(result.rules.len(), 1);
1137 assert_eq!(result.rules[0].name, "update-status");
1138
1139 assert!(result.source_format == SourceFormat::Clips);
1141 Ok(())
1142 }
1143
1144 #[test]
1145 fn test_clips_value_parsing() -> Result<(), Box<dyn std::error::Error>> {
1146 let tool = MigrationTool::new();
1147
1148 let value1 = tool.parse_clips_value("?x");
1150 assert!(matches!(value1, Term::Variable(v) if v == "x"));
1151
1152 let value2 = tool.parse_clips_value("\"hello\"");
1154 assert!(matches!(value2, Term::Literal(v) if v == "hello"));
1155
1156 let value3 = tool.parse_clips_value("42");
1158 assert!(matches!(value3, Term::Literal(v) if v == "42"));
1159
1160 let value4 = tool.parse_clips_value("active");
1162 assert!(matches!(value4, Term::Constant(v) if v == "active"));
1163 Ok(())
1164 }
1165
1166 #[test]
1167 fn test_drools_multiple_conditions() -> Result<(), Box<dyn std::error::Error>> {
1168 let mut tool = MigrationTool::new();
1169
1170 let drools_rules = r#"
1171rule "complex-rule"
1172when
1173 Person(age == 25, status == "active")
1174then
1175 insert(new Adult(verified: true))
1176end
1177"#;
1178
1179 let result = tool.migrate(drools_rules, SourceFormat::Drools)?;
1180
1181 assert_eq!(result.rules.len(), 1);
1182 let rule = &result.rules[0];
1183
1184 assert!(rule.body.len() >= 2);
1186 Ok(())
1187 }
1188
1189 #[test]
1190 fn test_migration_warnings_severity() {
1191 let result = MigrationResult {
1192 rules: vec![],
1193 warnings: vec![
1194 MigrationWarning {
1195 message: "Info".to_string(),
1196 line: Some(1),
1197 severity: WarningSeverity::Info,
1198 },
1199 MigrationWarning {
1200 message: "Warning".to_string(),
1201 line: Some(2),
1202 severity: WarningSeverity::Warning,
1203 },
1204 MigrationWarning {
1205 message: "Error".to_string(),
1206 line: Some(3),
1207 severity: WarningSeverity::Error,
1208 },
1209 ],
1210 source_format: SourceFormat::Jena,
1211 original_count: 3,
1212 migrated_count: 0,
1213 };
1214
1215 let report = result.generate_report();
1216
1217 assert!(report.contains("[INFO]"));
1218 assert!(report.contains("[WARN]"));
1219 assert!(report.contains("[ERROR]"));
1220 }
1221
1222 #[test]
1223 fn test_empty_drools_rule() -> Result<(), Box<dyn std::error::Error>> {
1224 let mut tool = MigrationTool::new();
1225
1226 let drools_rules = r#"
1227rule "empty"
1228when
1229then
1230end
1231"#;
1232
1233 let result = tool.migrate(drools_rules, SourceFormat::Drools)?;
1234
1235 assert!(result.source_format == SourceFormat::Drools);
1238 if !result.rules.is_empty() {
1239 assert!(result.rules[0].body.is_empty() && result.rules[0].head.is_empty());
1241 }
1242 Ok(())
1243 }
1244
1245 #[test]
1246 fn test_clips_pattern_filtering() -> Result<(), Box<dyn std::error::Error>> {
1247 let tool = MigrationTool::new();
1248
1249 let patterns = "(test (> ?x 5)) (person (age ?x))";
1251 let atoms = tool.parse_clips_patterns(patterns)?;
1252
1253 assert!(atoms.iter().any(|atom| {
1255 matches!(atom, RuleAtom::Triple {
1256 object: Term::Constant(o), ..
1257 } if o == "person")
1258 }));
1259 Ok(())
1260 }
1261}