1use crate::Rule;
63use anyhow::Result;
64use std::collections::{HashMap, HashSet};
65use std::time::Instant;
66use tracing::info;
67
68#[derive(Debug)]
70pub struct CoverageAnalyzer {
71 active: bool,
73 start_time: Option<Instant>,
75 tracked_rules: HashMap<String, Rule>,
77 executed_rules: HashSet<String>,
79 execution_counts: HashMap<String, usize>,
81 execution_paths: HashMap<String, HashSet<String>>,
83 data_flow: HashMap<String, HashSet<String>>,
85}
86
87impl Default for CoverageAnalyzer {
88 fn default() -> Self {
89 Self::new()
90 }
91}
92
93impl CoverageAnalyzer {
94 pub fn new() -> Self {
96 Self {
97 active: false,
98 start_time: None,
99 tracked_rules: HashMap::new(),
100 executed_rules: HashSet::new(),
101 execution_counts: HashMap::new(),
102 execution_paths: HashMap::new(),
103 data_flow: HashMap::new(),
104 }
105 }
106
107 pub fn register_rule(&mut self, rule: Rule) {
109 self.tracked_rules.insert(rule.name.clone(), rule);
110 }
111
112 pub fn register_rules(&mut self, rules: Vec<Rule>) {
114 for rule in rules {
115 self.register_rule(rule);
116 }
117 }
118
119 pub fn start_tracking(&mut self) {
121 info!(
122 "Starting coverage tracking for {} rules",
123 self.tracked_rules.len()
124 );
125 self.active = true;
126 self.start_time = Some(Instant::now());
127 }
128
129 pub fn stop_tracking(&mut self) {
131 self.active = false;
132 info!(
133 "Stopped coverage tracking after {:?}",
134 self.start_time.map(|t| t.elapsed())
135 );
136 }
137
138 pub fn record_rule_execution(&mut self, rule_name: &str) {
140 if !self.active {
141 return;
142 }
143
144 self.executed_rules.insert(rule_name.to_string());
145 *self
146 .execution_counts
147 .entry(rule_name.to_string())
148 .or_insert(0) += 1;
149 }
150
151 pub fn record_execution_path(&mut self, from_rule: &str, to_rule: &str) {
153 if !self.active {
154 return;
155 }
156
157 self.execution_paths
158 .entry(from_rule.to_string())
159 .or_default()
160 .insert(to_rule.to_string());
161 }
162
163 pub fn record_data_flow(&mut self, rule_name: &str, variable: &str) {
165 if !self.active {
166 return;
167 }
168
169 self.data_flow
170 .entry(rule_name.to_string())
171 .or_default()
172 .insert(variable.to_string());
173 }
174
175 pub fn generate_report(&self) -> CoverageReport {
177 let total_rules = self.tracked_rules.len();
178 let executed_rules = self.executed_rules.len();
179
180 let rule_coverage = if total_rules > 0 {
181 (executed_rules as f64 / total_rules as f64) * 100.0
182 } else {
183 0.0
184 };
185
186 let total_possible_paths = self.calculate_total_possible_paths();
188 let covered_paths = self
189 .execution_paths
190 .values()
191 .map(|s| s.len())
192 .sum::<usize>();
193 let path_coverage = if total_possible_paths > 0 {
194 (covered_paths as f64 / total_possible_paths as f64) * 100.0
195 } else {
196 0.0
197 };
198
199 let unexecuted_rules: Vec<String> = self
201 .tracked_rules
202 .keys()
203 .filter(|name| !self.executed_rules.contains(*name))
204 .cloned()
205 .collect();
206
207 CoverageReport {
208 total_rules,
209 executed_rules,
210 rule_coverage,
211 path_coverage,
212 execution_counts: self.execution_counts.clone(),
213 unexecuted_rules,
214 execution_paths: self.execution_paths.clone(),
215 data_flow_coverage: self.data_flow.clone(),
216 }
217 }
218
219 fn calculate_total_possible_paths(&self) -> usize {
221 let n = self.tracked_rules.len();
223 if n > 1 {
224 n * (n - 1)
225 } else {
226 0
227 }
228 }
229
230 pub fn get_dead_rules(&self) -> Vec<String> {
232 self.tracked_rules
233 .keys()
234 .filter(|name| !self.executed_rules.contains(*name))
235 .cloned()
236 .collect()
237 }
238
239 pub fn get_hot_rules(&self, threshold: usize) -> Vec<(String, usize)> {
241 let mut hot_rules: Vec<(String, usize)> = self
242 .execution_counts
243 .iter()
244 .filter(|(_, &count)| count >= threshold)
245 .map(|(name, &count)| (name.clone(), count))
246 .collect();
247
248 hot_rules.sort_by_key(|b| std::cmp::Reverse(b.1));
249 hot_rules
250 }
251
252 pub fn reset(&mut self) {
254 self.active = false;
255 self.start_time = None;
256 self.executed_rules.clear();
257 self.execution_counts.clear();
258 self.execution_paths.clear();
259 self.data_flow.clear();
260 }
261
262 pub fn export_to_json(&self) -> Result<String> {
264 use serde_json::json;
265
266 let report = self.generate_report();
267
268 let data = json!({
269 "total_rules": report.total_rules,
270 "executed_rules": report.executed_rules,
271 "rule_coverage": report.rule_coverage,
272 "path_coverage": report.path_coverage,
273 "execution_counts": report.execution_counts,
274 "unexecuted_rules": report.unexecuted_rules,
275 "execution_paths": report.execution_paths,
276 "data_flow_coverage": report.data_flow_coverage,
277 });
278
279 Ok(serde_json::to_string_pretty(&data)?)
280 }
281
282 pub fn is_active(&self) -> bool {
284 self.active
285 }
286
287 pub fn tracked_rule_count(&self) -> usize {
289 self.tracked_rules.len()
290 }
291}
292
293#[derive(Debug, Clone)]
295pub struct CoverageReport {
296 pub total_rules: usize,
298 pub executed_rules: usize,
300 pub rule_coverage: f64,
302 pub path_coverage: f64,
304 pub execution_counts: HashMap<String, usize>,
306 pub unexecuted_rules: Vec<String>,
308 pub execution_paths: HashMap<String, HashSet<String>>,
310 pub data_flow_coverage: HashMap<String, HashSet<String>>,
312}
313
314impl CoverageReport {
315 pub fn overall_coverage(&self) -> f64 {
317 (self.rule_coverage * 0.7) + (self.path_coverage * 0.3)
319 }
320
321 pub fn to_string_report(&self) -> String {
323 let mut report = String::new();
324
325 report.push_str("=== Rule Coverage Report ===\n\n");
326
327 report.push_str(&format!("Total Rules: {}\n", self.total_rules));
328 report.push_str(&format!("Executed Rules: {}\n", self.executed_rules));
329 report.push_str(&format!("Rule Coverage: {:.1}%\n", self.rule_coverage));
330 report.push_str(&format!("Path Coverage: {:.1}%\n", self.path_coverage));
331 report.push_str(&format!(
332 "Overall Coverage: {:.1}%\n\n",
333 self.overall_coverage()
334 ));
335
336 if !self.unexecuted_rules.is_empty() {
337 report.push_str("=== Unexecuted Rules (Dead Code) ===\n\n");
338 for rule_name in &self.unexecuted_rules {
339 report.push_str(&format!("- {}\n", rule_name));
340 }
341 report.push('\n');
342 }
343
344 report.push_str("=== Execution Statistics ===\n\n");
345
346 let mut sorted_counts: Vec<(&String, &usize)> = self.execution_counts.iter().collect();
347 sorted_counts.sort_by(|a, b| b.1.cmp(a.1));
348
349 for (rule_name, count) in sorted_counts {
350 report.push_str(&format!("{}: {} executions\n", rule_name, count));
351 }
352
353 report.push('\n');
354
355 if !self.execution_paths.is_empty() {
356 report.push_str("=== Execution Paths ===\n\n");
357 for (from_rule, to_rules) in &self.execution_paths {
358 report.push_str(&format!("{} ->\n", from_rule));
359 for to_rule in to_rules {
360 report.push_str(&format!(" - {}\n", to_rule));
361 }
362 report.push('\n');
363 }
364 }
365
366 if !self.data_flow_coverage.is_empty() {
367 report.push_str("=== Data Flow Coverage ===\n\n");
368 for (rule_name, variables) in &self.data_flow_coverage {
369 report.push_str(&format!("{}: {:?}\n", rule_name, variables));
370 }
371 report.push('\n');
372 }
373
374 report
375 }
376
377 pub fn get_grade(&self) -> CoverageGrade {
379 let coverage = self.overall_coverage();
380
381 if coverage >= 90.0 {
382 CoverageGrade::Excellent
383 } else if coverage >= 80.0 {
384 CoverageGrade::Good
385 } else if coverage >= 70.0 {
386 CoverageGrade::Fair
387 } else if coverage >= 60.0 {
388 CoverageGrade::Poor
389 } else {
390 CoverageGrade::Inadequate
391 }
392 }
393}
394
395#[derive(Debug, Clone, Copy, PartialEq, Eq)]
397pub enum CoverageGrade {
398 Excellent,
400 Good,
402 Fair,
404 Poor,
406 Inadequate,
408}
409
410impl std::fmt::Display for CoverageGrade {
411 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
412 match self {
413 CoverageGrade::Excellent => write!(f, "Excellent (A)"),
414 CoverageGrade::Good => write!(f, "Good (B)"),
415 CoverageGrade::Fair => write!(f, "Fair (C)"),
416 CoverageGrade::Poor => write!(f, "Poor (D)"),
417 CoverageGrade::Inadequate => write!(f, "Inadequate (F)"),
418 }
419 }
420}
421
422#[cfg(test)]
423mod tests {
424 use super::*;
425 use crate::{RuleAtom, Term};
426
427 #[test]
428 fn test_coverage_basic() {
429 let mut analyzer = CoverageAnalyzer::new();
430
431 let rule1 = Rule {
432 name: "rule1".to_string(),
433 body: vec![RuleAtom::Triple {
434 subject: Term::Variable("X".to_string()),
435 predicate: Term::Constant("p".to_string()),
436 object: Term::Variable("Y".to_string()),
437 }],
438 head: vec![RuleAtom::Triple {
439 subject: Term::Variable("X".to_string()),
440 predicate: Term::Constant("q".to_string()),
441 object: Term::Variable("Y".to_string()),
442 }],
443 };
444
445 analyzer.register_rule(rule1);
446 analyzer.start_tracking();
447 analyzer.record_rule_execution("rule1");
448 analyzer.stop_tracking();
449
450 let report = analyzer.generate_report();
451 assert_eq!(report.total_rules, 1);
452 assert_eq!(report.executed_rules, 1);
453 assert_eq!(report.rule_coverage, 100.0);
454 }
455
456 #[test]
457 fn test_dead_code_detection() {
458 let mut analyzer = CoverageAnalyzer::new();
459
460 let rule1 = Rule {
461 name: "executed_rule".to_string(),
462 body: vec![],
463 head: vec![],
464 };
465
466 let rule2 = Rule {
467 name: "dead_rule".to_string(),
468 body: vec![],
469 head: vec![],
470 };
471
472 analyzer.register_rules(vec![rule1, rule2]);
473 analyzer.start_tracking();
474 analyzer.record_rule_execution("executed_rule");
475 analyzer.stop_tracking();
476
477 let dead_rules = analyzer.get_dead_rules();
478 assert_eq!(dead_rules.len(), 1);
479 assert!(dead_rules.contains(&"dead_rule".to_string()));
480 }
481
482 #[test]
483 fn test_hot_rules() {
484 let mut analyzer = CoverageAnalyzer::new();
485
486 analyzer.register_rule(Rule {
487 name: "hot_rule".to_string(),
488 body: vec![],
489 head: vec![],
490 });
491
492 analyzer.start_tracking();
493
494 for _ in 0..100 {
495 analyzer.record_rule_execution("hot_rule");
496 }
497
498 analyzer.stop_tracking();
499
500 let hot_rules = analyzer.get_hot_rules(50);
501 assert_eq!(hot_rules.len(), 1);
502 assert_eq!(hot_rules[0].0, "hot_rule");
503 assert_eq!(hot_rules[0].1, 100);
504 }
505
506 #[test]
507 fn test_execution_paths() {
508 let mut analyzer = CoverageAnalyzer::new();
509
510 analyzer.start_tracking();
511 analyzer.record_execution_path("rule1", "rule2");
512 analyzer.record_execution_path("rule1", "rule3");
513 analyzer.stop_tracking();
514
515 let report = analyzer.generate_report();
516 assert!(report.execution_paths.contains_key("rule1"));
517 assert_eq!(report.execution_paths["rule1"].len(), 2);
518 }
519
520 #[test]
521 fn test_data_flow_coverage() {
522 let mut analyzer = CoverageAnalyzer::new();
523
524 analyzer.start_tracking();
525 analyzer.record_data_flow("rule1", "X");
526 analyzer.record_data_flow("rule1", "Y");
527 analyzer.stop_tracking();
528
529 let report = analyzer.generate_report();
530 assert!(report.data_flow_coverage.contains_key("rule1"));
531 assert_eq!(report.data_flow_coverage["rule1"].len(), 2);
532 }
533
534 #[test]
535 fn test_coverage_reset() {
536 let mut analyzer = CoverageAnalyzer::new();
537
538 analyzer.register_rule(Rule {
539 name: "rule1".to_string(),
540 body: vec![],
541 head: vec![],
542 });
543
544 analyzer.start_tracking();
545 analyzer.record_rule_execution("rule1");
546 analyzer.stop_tracking();
547
548 assert_eq!(analyzer.executed_rules.len(), 1);
549
550 analyzer.reset();
551
552 assert_eq!(analyzer.executed_rules.len(), 0);
553 assert!(!analyzer.is_active());
554 }
555
556 #[test]
557 fn test_coverage_grade() {
558 let report = CoverageReport {
559 total_rules: 10,
560 executed_rules: 9,
561 rule_coverage: 90.0,
562 path_coverage: 90.0,
563 execution_counts: HashMap::new(),
564 unexecuted_rules: vec![],
565 execution_paths: HashMap::new(),
566 data_flow_coverage: HashMap::new(),
567 };
568
569 assert_eq!(report.get_grade(), CoverageGrade::Excellent);
570 assert_eq!(report.overall_coverage(), 90.0);
571 }
572
573 #[test]
574 fn test_json_export() -> Result<(), Box<dyn std::error::Error>> {
575 let mut analyzer = CoverageAnalyzer::new();
576
577 analyzer.register_rule(Rule {
578 name: "rule1".to_string(),
579 body: vec![],
580 head: vec![],
581 });
582
583 analyzer.start_tracking();
584 analyzer.record_rule_execution("rule1");
585 analyzer.stop_tracking();
586
587 let json = analyzer.export_to_json()?;
588 assert!(json.contains("rule1"));
589 assert!(json.contains("rule_coverage"));
590 Ok(())
591 }
592
593 #[test]
594 fn test_partial_coverage() {
595 let mut analyzer = CoverageAnalyzer::new();
596
597 for i in 0..10 {
598 analyzer.register_rule(Rule {
599 name: format!("rule{i}"),
600 body: vec![],
601 head: vec![],
602 });
603 }
604
605 analyzer.start_tracking();
606
607 for i in 0..5 {
609 analyzer.record_rule_execution(&format!("rule{i}"));
610 }
611
612 analyzer.stop_tracking();
613
614 let report = analyzer.generate_report();
615 assert_eq!(report.total_rules, 10);
616 assert_eq!(report.executed_rules, 5);
617 assert_eq!(report.rule_coverage, 50.0);
618 assert_eq!(report.unexecuted_rules.len(), 5);
619 }
620
621 #[test]
622 fn test_string_report() {
623 let mut analyzer = CoverageAnalyzer::new();
624
625 analyzer.register_rule(Rule {
626 name: "rule1".to_string(),
627 body: vec![],
628 head: vec![],
629 });
630
631 analyzer.start_tracking();
632 analyzer.record_rule_execution("rule1");
633 analyzer.stop_tracking();
634
635 let report = analyzer.generate_report();
636 let string_report = report.to_string_report();
637
638 assert!(string_report.contains("Rule Coverage Report"));
639 assert!(string_report.contains("rule1"));
640 }
641}