qualia_core_db/modalities/logic/shacl/
shacl_compiler.rs1use super::shacl_extension_bridge::append_extension_opcodes;
7use super::shacl_types::{
8 CompiledShape, NodeKindType, ShaclConstraint, ShaclSeverity, ShaclTarget,
9};
10use crate::webizen::SlgOpcode;
11
12pub struct ShaclCompiler;
14
15impl ShaclCompiler {
16 pub fn new() -> Self {
19 ShaclCompiler
20 }
21
22 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 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 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 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 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 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 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 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 | 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 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 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
330fn 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
343fn 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}