Skip to main content

inference_engine/shacl12/
plan.rs

1use shacl_structural_model::inference::{RuleNumber, RuleSchedule};
2use std::{cmp::Ordering, error::Error, fmt};
3
4/// One unique preflight-checked rule handle and its shared schedule declaration.
5#[derive(Debug)]
6pub struct Rule<Id> {
7    pub(super) id: Id,
8    pub(super) schedule: RuleSchedule,
9}
10impl<Id> Rule<Id> {
11    /// Associate an existing backend rule with its checked declaration.
12    pub const fn new(id: Id, schedule: RuleSchedule) -> Self {
13        Self { id, schedule }
14    }
15    /// Original backend rule identity.
16    pub const fn id(&self) -> &Id {
17        &self.id
18    }
19    /// Original shared declaration, without lexical normalization.
20    pub const fn schedule(&self) -> &RuleSchedule {
21        &self.schedule
22    }
23}
24
25/// Finite, explicitly capped rule programme sorted by exact layer/order values.
26#[derive(Debug)]
27pub struct Plan<Id> {
28    pub(super) rules: Vec<Rule<Id>>,
29}
30impl<Id: Eq> Plan<Id> {
31    /// Check the finite programme and sort it by layer, run-once phase and order.
32    /// Inactive rules must have been removed by the preflight compiler. Repeated
33    /// shape links must resolve to one rule handle before this boundary.
34    ///
35    /// # Errors
36    /// Rejects excess rules or repeated identities; never silently truncates.
37    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        // bounded: the caller-specified rule-count cap was checked above.
47        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/// A rejected rule programme, before graph execution starts.
62#[derive(Debug, Clone, Copy, Eq, PartialEq)]
63pub enum PlanError {
64    /// The explicit finite rule-count cap was exceeded.
65    TooManyRules,
66    /// One rule identity appeared more than once.
67    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    // Only apply the absent-property default. General numeric comparison belongs
89    // to the checked shared model; no float or bounded integer conversion occurs.
90    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}