inference_engine/shacl12/
plan.rs1use shacl_structural_model::inference::{RuleNumber, RuleSchedule};
2use std::{cmp::Ordering, error::Error, fmt};
3
4#[derive(Debug)]
6pub struct Rule<Id> {
7 pub(super) id: Id,
8 pub(super) schedule: RuleSchedule,
9}
10impl<Id> Rule<Id> {
11 pub const fn new(id: Id, schedule: RuleSchedule) -> Self {
13 Self { id, schedule }
14 }
15 pub const fn id(&self) -> &Id {
17 &self.id
18 }
19 pub const fn schedule(&self) -> &RuleSchedule {
21 &self.schedule
22 }
23}
24
25#[derive(Debug)]
27pub struct Plan<Id> {
28 pub(super) rules: Vec<Rule<Id>>,
29}
30impl<Id: Eq> Plan<Id> {
31 pub fn try_new(mut rules: Vec<Rule<Id>>, maximum: usize) -> Result<Self, PlanError> {
38 if rules.len() > maximum {
39 return Err(PlanError::TooManyRules);
40 }
41 for (index, rule) in rules.iter().enumerate() {
42 if rules[..index].iter().any(|earlier| earlier.id == rule.id) {
43 return Err(PlanError::DuplicateRule);
44 }
45 }
46 rules.sort_by(|a, b| {
48 number_cmp(a.schedule.layer(), b.schedule.layer())
49 .then_with(|| {
50 b.schedule
51 .run_once()
52 .unwrap_or(false)
53 .cmp(&a.schedule.run_once().unwrap_or(false))
54 })
55 .then_with(|| number_cmp(a.schedule.order(), b.schedule.order()))
56 });
57 Ok(Self { rules })
58 }
59}
60
61#[derive(Debug, Clone, Copy, Eq, PartialEq)]
63pub enum PlanError {
64 TooManyRules,
66 DuplicateRule,
68}
69impl fmt::Display for PlanError {
70 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71 f.write_str(match self {
72 Self::TooManyRules => "SHACL rule-count limit exceeded",
73 Self::DuplicateRule => "duplicate SHACL rule identity",
74 })
75 }
76}
77impl Error for PlanError {}
78
79pub(super) fn number_cmp(a: Option<&RuleNumber>, b: Option<&RuleNumber>) -> Ordering {
80 match (a, b) {
81 (Some(a), Some(b)) => a.cmp_value(b),
82 (None, None) => Ordering::Equal,
83 (Some(a), None) => versus_zero(a),
84 (None, Some(b)) => versus_zero(b).reverse(),
85 }
86}
87fn versus_zero(number: &RuleNumber) -> Ordering {
88 let lexical = number.literal().lexical();
91 if lexical
92 .bytes()
93 .all(|byte| matches!(byte, b'0' | b'.' | b'+' | b'-'))
94 {
95 Ordering::Equal
96 } else if lexical.starts_with('-') {
97 Ordering::Less
98 } else {
99 Ordering::Greater
100 }
101}