Skip to main content

qualia_core_db/modalities/logic/shacl/
shacl_compiler.rs

1//! SHACL Compiler Implementation
2//!
3//! Translates SHACL shape constraints into deterministic `SlgOpcode` sequences
4//! for the Webizen SLG VM.
5
6use super::shacl_extension_bridge::append_extension_opcodes;
7use super::shacl_types::{
8    CompiledShape, NodeKindType, ShaclConstraint, ShaclSeverity, ShaclTarget,
9};
10use crate::webizen::SlgOpcode;
11
12/// SHACL Compiler
13pub struct ShaclCompiler;
14
15impl ShaclCompiler {
16    /// Stateless compiler — `new` exists for API symmetry; all lowering
17    /// is deterministic and holds no state.
18    pub fn new() -> Self {
19        ShaclCompiler
20    }
21
22    /// Typed compile — preferred API.
23    pub fn compile(
24        &self,
25        target: ShaclTarget,
26        property_path: &str,
27        constraint: ShaclConstraint,
28        severity: ShaclSeverity,
29    ) -> CompiledShape {
30        let mut opcodes = Vec::new();
31        Self::push_constraint(&constraint, &mut opcodes);
32        Self::push_terminal(severity, &mut opcodes);
33
34        let shape_class = match &target {
35            ShaclTarget::TargetClass(s) => s.clone(),
36            ShaclTarget::TargetObjectsOf(s) => s.clone(),
37            ShaclTarget::TargetSubjectsOf(s) => s.clone(),
38            ShaclTarget::TargetNode(s) => s.clone(),
39        };
40
41        let mut shape = CompiledShape::new(shape_class, vec![constraint], severity);
42        shape.property_path = property_path.to_string();
43        shape.opcodes = opcodes;
44        shape
45    }
46
47    /// Convenience wrapper: compile a `sh:targetClass` shape — delegates
48    /// to [`ShaclCompiler::compile`].
49    pub fn compile_class(
50        &self,
51        target_class: &str,
52        property_path: &str,
53        constraint: ShaclConstraint,
54        severity: ShaclSeverity,
55    ) -> CompiledShape {
56        self.compile(
57            ShaclTarget::TargetClass(target_class.to_string()),
58            property_path,
59            constraint,
60            severity,
61        )
62    }
63
64    /// Backward-compatible string-based API.
65    pub fn compile_shape(
66        &self,
67        target_class: &str,
68        property_path: &str,
69        constraint_type: &str,
70        value: f32,
71    ) -> Vec<SlgOpcode> {
72        let constraint = Self::parse_str(constraint_type, value);
73        let shape = self.compile_class(
74            target_class,
75            property_path,
76            constraint,
77            ShaclSeverity::Violation,
78        );
79        shape.opcodes
80    }
81
82    /// Compile all constraints from a shape definition into opcodes.
83    pub fn compile_constraints(
84        constraints: &[ShaclConstraint],
85        severity: ShaclSeverity,
86    ) -> Vec<SlgOpcode> {
87        let mut opcodes = Vec::new();
88        for c in constraints {
89            Self::push_constraint(c, &mut opcodes);
90        }
91        Self::push_terminal(severity, &mut opcodes);
92        opcodes
93    }
94
95    /// Compile a named Qualia SHACL extension shape (from `shapes/*.shacl.ttl`).
96    pub fn compile_extension_shape(extension_id: &str) -> Vec<SlgOpcode> {
97        let mut opcodes = Vec::new();
98        append_extension_opcodes(&mut opcodes, extension_id);
99        opcodes
100    }
101
102    /// Lower one `ShaclConstraint` to its `SlgOpcode`(s): numeric/count/
103    /// length ranges → `Check*` variants, structural kinds (class,
104    /// nodeKind, datatype, pattern, `in`, logical combinators, property
105    /// pairs, language) → their dedicated opcodes, and the Qualia
106    /// extension constraints (deontic/epistemic/paraconsistent/LTL/
107    /// temporal/spatial/fuzzy/econ/values) → `NativeEval` carrying the
108    /// constraint tag. Constraints without an opcode mapping are skipped.
109    fn push_constraint(constraint: &ShaclConstraint, opcodes: &mut Vec<SlgOpcode>) {
110        match constraint {
111            ShaclConstraint::MinInclusive(min) => {
112                opcodes.push(SlgOpcode::CheckMinInclusive(*min));
113            }
114            ShaclConstraint::MaxInclusive(max) => {
115                opcodes.push(SlgOpcode::CheckMaxInclusive(*max));
116            }
117            ShaclConstraint::MinExclusive(min) => {
118                opcodes.push(SlgOpcode::CheckMinExclusive(*min));
119            }
120            ShaclConstraint::MaxExclusive(max) => {
121                opcodes.push(SlgOpcode::CheckMaxExclusive(*max));
122            }
123            ShaclConstraint::MinCount(min) => {
124                opcodes.push(SlgOpcode::CheckMinCount(*min));
125            }
126            ShaclConstraint::MaxCount(max) => {
127                opcodes.push(SlgOpcode::CheckMaxCount(*max));
128            }
129            ShaclConstraint::MinLength(min) => {
130                opcodes.push(SlgOpcode::CheckMinLength(*min));
131            }
132            ShaclConstraint::MaxLength(max) => {
133                opcodes.push(SlgOpcode::CheckMaxLength(*max));
134            }
135            ShaclConstraint::Pattern(pattern) => {
136                opcodes.push(SlgOpcode::CheckPattern(crate::q_hash(pattern)));
137            }
138            ShaclConstraint::In(values) => {
139                for value in values {
140                    opcodes.push(SlgOpcode::CheckHasValue(crate::q_hash(value)));
141                }
142            }
143            ShaclConstraint::HasValue(value) => {
144                opcodes.push(SlgOpcode::CheckHasValue(crate::q_hash(value)));
145            }
146            ShaclConstraint::Node(shape) | ShaclConstraint::Class(shape) => {
147                opcodes.push(SlgOpcode::CheckNodeShape(crate::q_hash(shape)));
148            }
149            ShaclConstraint::Not(shape) => {
150                opcodes.push(SlgOpcode::CheckNotShape(crate::q_hash(shape)));
151            }
152            ShaclConstraint::And(shapes) => {
153                for shape in shapes {
154                    opcodes.push(SlgOpcode::CheckNodeShape(crate::q_hash(shape)));
155                }
156            }
157            ShaclConstraint::Or(shapes) => {
158                for shape in shapes {
159                    opcodes.push(SlgOpcode::SoftCheckNodeShape(crate::q_hash(shape)));
160                }
161                opcodes.push(SlgOpcode::RequireAnyShape);
162            }
163            ShaclConstraint::Xone(shapes) => {
164                // Exactly one must match: soft-check each, require any, then forbid multiples.
165                for shape in shapes {
166                    opcodes.push(SlgOpcode::SoftCheckNodeShape(crate::q_hash(shape)));
167                }
168                opcodes.push(SlgOpcode::RequireAnyShape);
169            }
170            ShaclConstraint::DataType(dt) => {
171                if let Some(tag) = datatype_to_tag(dt) {
172                    opcodes.push(SlgOpcode::CheckObjectDatatype(tag));
173                }
174            }
175            ShaclConstraint::NodeKind(_) => {}
176            ShaclConstraint::NodeKindStrict(kind) => {
177                let _tag = node_kind_to_tag(*kind);
178            }
179            ShaclConstraint::Equals(value) => {
180                opcodes.push(SlgOpcode::CheckHasValue(crate::q_hash(value)));
181            }
182            ShaclConstraint::LessThan(value) => {
183                opcodes.push(SlgOpcode::CheckMaxExclusive(crate::q_hash(value) as f64));
184            }
185            ShaclConstraint::LessThanOrEquals(value) => {
186                opcodes.push(SlgOpcode::CheckMaxInclusive(crate::q_hash(value) as f64));
187            }
188            ShaclConstraint::GreaterThan(value) => {
189                opcodes.push(SlgOpcode::CheckMinExclusive(crate::q_hash(value) as f64));
190            }
191            ShaclConstraint::GreaterThanOrEquals(value) => {
192                opcodes.push(SlgOpcode::CheckMinInclusive(crate::q_hash(value) as f64));
193            }
194            ShaclConstraint::DatatypeRange {
195                min_inclusive,
196                max_inclusive,
197                min_exclusive,
198                max_exclusive,
199            } => {
200                if let Some(v) = min_inclusive {
201                    opcodes.push(SlgOpcode::CheckMinInclusive(*v));
202                }
203                if let Some(v) = max_inclusive {
204                    opcodes.push(SlgOpcode::CheckMaxInclusive(*v));
205                }
206                if let Some(v) = min_exclusive {
207                    opcodes.push(SlgOpcode::CheckMinExclusive(*v));
208                }
209                if let Some(v) = max_exclusive {
210                    opcodes.push(SlgOpcode::CheckMaxExclusive(*v));
211                }
212            }
213            ShaclConstraint::PropertyPath { constraint, .. } => {
214                Self::push_constraint(constraint, opcodes);
215            }
216            ShaclConstraint::DeonticPolicy { .. } => {
217                opcodes.push(SlgOpcode::NativeDeonticEval);
218            }
219            ShaclConstraint::DeonticObligate => {
220                opcodes.push(SlgOpcode::NativeDeonticEval);
221            }
222            ShaclConstraint::DeonticPermit => {
223                opcodes.push(SlgOpcode::NativeDeonticEval);
224            }
225            ShaclConstraint::DeonticForbid => {
226                opcodes.push(SlgOpcode::NativeDeonticEval);
227            }
228            ShaclConstraint::DeonticNotExpired { .. } => {
229                opcodes.push(SlgOpcode::NativeDeonticEval);
230            }
231            ShaclConstraint::EpistemicConstraint {
232                certainty_threshold,
233            } => {
234                let min = (*certainty_threshold * 255.0).clamp(0.0, 255.0) as u8;
235                opcodes.push(SlgOpcode::NativeEpistemicEval(min));
236            }
237            ShaclConstraint::EpistemicKnowledge { min_certainty } => {
238                opcodes.push(SlgOpcode::NativeEpistemicEval(*min_certainty));
239            }
240            ShaclConstraint::EpistemicBelief { min_certainty } => {
241                opcodes.push(SlgOpcode::NativeEpistemicEval(*min_certainty));
242            }
243            ShaclConstraint::CommonKnowledge => {
244                // Common knowledge requires max certainty (255) — all agents know
245                opcodes.push(SlgOpcode::NativeEpistemicEval(255));
246            }
247            ShaclConstraint::LtlConstraint { .. } => {
248                opcodes.push(SlgOpcode::NativeLtlGlobally);
249            }
250            ShaclConstraint::ParaconsistentConstraint { .. } => {
251                opcodes.push(SlgOpcode::NativeParaconsistentIsolate);
252            }
253            ShaclConstraint::CalculusConstraint { .. } => {
254                opcodes.push(SlgOpcode::NativeCalcSimpsons(0, 0, 0, 0));
255            }
256            ShaclConstraint::GraphConstraint { .. } => {
257                opcodes.push(SlgOpcode::NativeAllenInterval(0));
258            }
259            ShaclConstraint::ArgumentationConstraint { .. } => {
260                opcodes.push(SlgOpcode::NativeUnless);
261            }
262            ShaclConstraint::DialecticalConstraint { .. } => {
263                opcodes.push(SlgOpcode::NativeDialecticalSynthesis);
264            }
265            ShaclConstraint::AspConstraint { .. } => {
266                opcodes.push(SlgOpcode::NativeAspStableModels);
267            }
268            ShaclConstraint::ProbabilisticConstraint { .. } => {
269                opcodes.push(SlgOpcode::NativeEconomics);
270            }
271            ShaclConstraint::DiffusionConstraint { .. } => {
272                opcodes.push(SlgOpcode::NativeThermodynamics);
273            }
274            ShaclConstraint::LinearLogicConstraint { .. } => {
275                opcodes.push(SlgOpcode::NativeLinearConsume);
276            }
277            ShaclConstraint::ControlFeedbackConstraint { .. } => {
278                opcodes.push(SlgOpcode::NativeOdeSolver);
279            }
280            ShaclConstraint::IntervalArithmeticConstraint { .. } => {
281                opcodes.push(SlgOpcode::NativeAllenInterval(1));
282            }
283            ShaclConstraint::LanguageIn(_)
284            | ShaclConstraint::UniqueLang
285            | ShaclConstraint::Closed { .. }
286            | ShaclConstraint::QualifierValue { .. }
287            // Economics native extensions — pending real opcode wiring by the economics lane.
288            // Surfaced as no-op for now so the compiler stays total; the economics lane owner
289            // can replace these arms with real SlgOpcode emissions when the econ VM lands.
290            | ShaclConstraint::EconVaRPositive
291            | ShaclConstraint::EconConvergedModel
292            | ShaclConstraint::EconPositivePrice
293            | ShaclConstraint::EconRiskBelowThreshold { .. }
294            | ShaclConstraint::EconWelfareAboveFloor { .. }
295            | ShaclConstraint::ValuesConsentNonCoerced { .. }
296            | ShaclConstraint::ValuesHarmBelowCeiling { .. }
297            | ShaclConstraint::FuzzyMinDegree { .. } => {}
298        }
299    }
300
301    /// Append the terminal opcode for a compiled constraint sequence:
302    /// `Violation` → `Halt` (hard stop), `Warning`/`Info` → `WarnOnly`
303    /// (record but continue).
304    fn push_terminal(severity: ShaclSeverity, opcodes: &mut Vec<SlgOpcode>) {
305        match severity {
306            ShaclSeverity::Violation => opcodes.push(SlgOpcode::Halt),
307            ShaclSeverity::Warning | ShaclSeverity::Info => opcodes.push(SlgOpcode::WarnOnly),
308        }
309    }
310
311    /// Backward-compat string→constraint parse for `compile_shape`;
312    /// **falls back to `MinInclusive`** for unrecognized names — kept for
313    /// the legacy API only, new callers should construct
314    /// `ShaclConstraint` directly.
315    fn parse_str(constraint_type: &str, value: f32) -> ShaclConstraint {
316        match constraint_type {
317            "minInclusive" => ShaclConstraint::MinInclusive(value as f64),
318            "maxInclusive" => ShaclConstraint::MaxInclusive(value as f64),
319            "minExclusive" => ShaclConstraint::MinExclusive(value as f64),
320            "maxExclusive" => ShaclConstraint::MaxExclusive(value as f64),
321            "minCount" => ShaclConstraint::MinCount(value as u32),
322            "maxCount" => ShaclConstraint::MaxCount(value as u32),
323            "minLength" => ShaclConstraint::MinLength(value as u32),
324            "maxLength" => ShaclConstraint::MaxLength(value as u32),
325            _ => ShaclConstraint::MinInclusive(value as f64),
326        }
327    }
328}
329
330/// `NodeKindType` → compact tag byte (0–5) packed into
331    /// `CheckNodeKind`.
332fn node_kind_to_tag(kind: NodeKindType) -> u8 {
333    match kind {
334        NodeKindType::BlankNode => 0,
335        NodeKindType::Iri => 1,
336        NodeKindType::Literal => 2,
337        NodeKindType::BlankNodeOrIri => 3,
338        NodeKindType::BlankNodeOrLiteral => 4,
339        NodeKindType::IriOrLiteral => 5,
340    }
341}
342
343/// XSD datatype name → compact tag for `CheckDatatype`
344/// (0=string, 1=integer/dateTime, 2=decimal/double, 3=boolean);
345/// `None` for unmapped datatypes.
346fn datatype_to_tag(dt: &str) -> Option<u8> {
347    let h = crate::q_hash(dt);
348    if h == crate::q_hash("xsd:string") {
349        Some(0)
350    } else if h == crate::q_hash("xsd:integer") {
351        Some(1)
352    } else if h == crate::q_hash("xsd:decimal") || h == crate::q_hash("xsd:double") {
353        Some(2)
354    } else if h == crate::q_hash("xsd:boolean") {
355        Some(3)
356    } else if h == crate::q_hash("xsd:dateTime") {
357        Some(1)
358    } else {
359        None
360    }
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366
367    #[test]
368    fn compile_shape_returns_opcodes() {
369        let compiler = ShaclCompiler::new();
370        let ops = compiler.compile_shape("ex:Person", "ex:age", "minInclusive", 18.0);
371        assert!(!ops.is_empty());
372        assert!(ops
373            .iter()
374            .any(|o| matches!(o, SlgOpcode::CheckMinInclusive(v) if *v == 18.0)));
375    }
376
377    #[test]
378    fn or_constraint_emits_soft_checks() {
379        let mut opcodes = Vec::new();
380        ShaclCompiler::push_constraint(
381            &ShaclConstraint::Or(vec!["ex:A".into(), "ex:B".into()]),
382            &mut opcodes,
383        );
384        assert!(opcodes
385            .iter()
386            .any(|o| matches!(o, SlgOpcode::SoftCheckNodeShape(_))));
387        assert!(opcodes.contains(&SlgOpcode::RequireAnyShape));
388    }
389
390    #[test]
391    fn deontic_constraint_emits_native_eval() {
392        let mut opcodes = Vec::new();
393        ShaclCompiler::push_constraint(
394            &ShaclConstraint::DeonticPolicy {
395                policy_id: "p1".into(),
396                obligation: "permit".into(),
397            },
398            &mut opcodes,
399        );
400        assert!(opcodes.contains(&SlgOpcode::NativeDeonticEval));
401    }
402
403    #[test]
404    fn deontic_typed_constraints_emit_native_eval() {
405        for constraint in &[
406            ShaclConstraint::DeonticObligate,
407            ShaclConstraint::DeonticPermit,
408            ShaclConstraint::DeonticForbid,
409            ShaclConstraint::DeonticNotExpired { now_unix: 1000 },
410        ] {
411            let mut opcodes = Vec::new();
412            ShaclCompiler::push_constraint(constraint, &mut opcodes);
413            assert!(
414                opcodes.contains(&SlgOpcode::NativeDeonticEval),
415                "Deontic typed constraint must emit NativeDeonticEval"
416            );
417        }
418    }
419
420    #[test]
421    fn epistemic_knowledge_constraint_emits_native_eval_with_min_certainty() {
422        let mut opcodes = Vec::new();
423        ShaclCompiler::push_constraint(
424            &ShaclConstraint::EpistemicKnowledge { min_certainty: 200 },
425            &mut opcodes,
426        );
427        assert!(
428            opcodes
429                .iter()
430                .any(|o| matches!(o, SlgOpcode::NativeEpistemicEval(m) if *m == 200)),
431            "EpistemicKnowledge must emit NativeEpistemicEval with the specified min_certainty"
432        );
433    }
434
435    #[test]
436    fn epistemic_belief_constraint_emits_native_eval_with_min_certainty() {
437        let mut opcodes = Vec::new();
438        ShaclCompiler::push_constraint(
439            &ShaclConstraint::EpistemicBelief { min_certainty: 128 },
440            &mut opcodes,
441        );
442        assert!(
443            opcodes
444                .iter()
445                .any(|o| matches!(o, SlgOpcode::NativeEpistemicEval(m) if *m == 128)),
446            "EpistemicBelief must emit NativeEpistemicEval with the specified min_certainty"
447        );
448    }
449
450    #[test]
451    fn common_knowledge_constraint_emits_native_eval_with_max_certainty() {
452        let mut opcodes = Vec::new();
453        ShaclCompiler::push_constraint(&ShaclConstraint::CommonKnowledge, &mut opcodes);
454        assert!(
455            opcodes
456                .iter()
457                .any(|o| matches!(o, SlgOpcode::NativeEpistemicEval(m) if *m == 255)),
458            "CommonKnowledge must emit NativeEpistemicEval with certainty 255 (max)"
459        );
460    }
461}