qualia_core_db/sparql_library/
sparql_shacl.rs1use crate::sparql_ast::*;
6use crate::sparql_executor::*;
7use crate::sparql_planner::*;
8use crate::NQuin;
9
10#[repr(C)]
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum ShaclConstraint {
14 NodeKind {
16 node_kind: u8, },
18 Class { class_iri: u64 },
20 MinCount { min_count: u64 },
22 MaxCount { max_count: u64 },
24 Datatype { datatype_iri: u64 },
26 Pattern {
28 pattern_regex: u64, },
30 Sparql { query: SparqlQuery },
32 Property {
34 predicate: u64,
35 constraints: [ConstraintId; 16],
36 constraint_count: u8,
37 },
38}
39
40pub type ConstraintId = u16;
41
42#[repr(C)]
44#[derive(Debug, Clone, Copy)]
45pub struct ShaclShape {
46 pub shape_iri: u64,
47 pub target_class: Option<u64>,
48 pub target_node: Option<u64>,
49 pub constraints: [ConstraintId; 32],
50 pub constraint_count: u8,
51}
52
53#[repr(C)]
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub struct ValidationResult {
57 pub conforms: bool,
58 pub focus_node: u64,
59 pub violation_count: u16,
60}
61
62pub struct ShaclValidator<'a> {
64 pub quins: &'a [NQuin],
65 pub shapes: [ShaclShape; 64],
66 pub shape_count: u8,
67 pub constraints: [ShaclConstraint; 256],
68 pub constraint_count: u16,
69}
70
71impl<'a> ShaclValidator<'a> {
72 pub fn new(quins: &'a [NQuin]) -> Self {
74 Self {
75 quins,
76 shapes: [ShaclShape {
77 shape_iri: 0,
78 target_class: None,
79 target_node: None,
80 constraints: [0; 32],
81 constraint_count: 0,
82 }; 64],
83 shape_count: 0,
84 constraints: [ShaclConstraint::NodeKind { node_kind: 0 }; 256],
85 constraint_count: 0,
86 }
87 }
88
89 pub fn add_shape(&mut self, shape: ShaclShape) -> Result<u8, String> {
91 if self.shape_count >= 64 {
92 return Err("Shape overflow".to_string());
93 }
94 let idx = self.shape_count;
95 self.shapes[idx as usize] = shape;
96 self.shape_count += 1;
97 Ok(idx)
98 }
99
100 pub fn add_constraint(&mut self, constraint: ShaclConstraint) -> Result<ConstraintId, String> {
102 if self.constraint_count >= 256 {
103 return Err("Constraint overflow".to_string());
104 }
105 let idx = self.constraint_count as ConstraintId;
106 self.constraints[self.constraint_count as usize] = constraint;
107 self.constraint_count += 1;
108 Ok(idx)
109 }
110
111 pub fn validate_node(&self, node: u64, shape: &ShaclShape) -> Result<ValidationResult, String> {
113 let mut violation_count = 0;
114
115 for i in 0..shape.constraint_count as usize {
117 let constraint_id = shape.constraints[i];
118 let constraint = self
119 .constraints
120 .get(constraint_id as usize)
121 .ok_or("Constraint ID out of bounds")?;
122
123 if !self.validate_constraint(node, constraint)? {
124 violation_count += 1;
125 }
126 }
127
128 Ok(ValidationResult {
129 conforms: violation_count == 0,
130 focus_node: node,
131 violation_count,
132 })
133 }
134
135 fn validate_constraint(&self, node: u64, constraint: &ShaclConstraint) -> Result<bool, String> {
137 match constraint {
138 ShaclConstraint::NodeKind { node_kind } => {
139 let actual_kind = self.get_node_kind(node);
141 Ok(actual_kind == *node_kind)
142 }
143 ShaclConstraint::Class { class_iri } => {
144 self.check_class_membership(node, *class_iri)
146 }
147 ShaclConstraint::MinCount { min_count } => {
148 self.check_min_count(node, *min_count)
150 }
151 ShaclConstraint::MaxCount { max_count } => {
152 self.check_max_count(node, *max_count)
154 }
155 ShaclConstraint::Datatype { datatype_iri } => {
156 self.check_datatype(node, *datatype_iri)
158 }
159 ShaclConstraint::Pattern { pattern_regex } => {
160 self.check_pattern(node, *pattern_regex)
162 }
163 ShaclConstraint::Sparql { query } => {
164 self.validate_sparql_constraint(node, query)
166 }
167 ShaclConstraint::Property { .. } => {
168 Ok(true)
170 }
171 }
172 }
173
174 fn get_node_kind(&self, node: u64) -> u8 {
175 if node >= 0x8000_0000_0000_0000 {
177 0 } else if node & 0x7000_0000_0000_0000 != 0 {
179 2 } else {
181 1 }
183 }
184
185 fn check_class_membership(&self, node: u64, class_iri: u64) -> Result<bool, String> {
186 let rdf_type = crate::lexicon::generate_60bit_token(
188 b"http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
189 );
190
191 for quin in self.quins {
192 if quin.subject == node && quin.predicate == rdf_type && quin.object == class_iri {
193 return Ok(true);
194 }
195 }
196
197 Ok(false)
198 }
199
200 fn check_min_count(&self, node: u64, min_count: u64) -> Result<bool, String> {
201 let count = self.count_outgoing_triples(node);
202 Ok(count >= min_count)
203 }
204
205 fn check_max_count(&self, node: u64, max_count: u64) -> Result<bool, String> {
206 let count = self.count_outgoing_triples(node);
207 Ok(count <= max_count)
208 }
209
210 fn check_datatype(&self, node: u64, datatype_iri: u64) -> Result<bool, String> {
211 let expected_tag = datatype_iri_to_tag(datatype_iri);
212 for quin in self.quins {
213 if quin.subject != node {
214 continue;
215 }
216 if quin.object >> 63 != 0 {
217 return Ok(false);
218 }
219 let tag = ((quin.object >> 60) & 0b111) as u8;
220 return Ok(tag == expected_tag);
221 }
222 Ok(false)
223 }
224
225 fn check_pattern(&self, node: u64, pattern_regex: u64) -> Result<bool, String> {
226 for quin in self.quins {
227 if quin.subject == node {
228 let payload = quin.object & 0x0FFF_FFFF_FFFF_FFFF;
229 if payload == pattern_regex {
230 return Ok(true);
231 }
232 }
233 }
234 Ok(false)
235 }
236
237 fn validate_sparql_constraint(&self, node: u64, query: &SparqlQuery) -> Result<bool, String> {
238 let mut ctx = SparqlQueryContext::new();
239 let _this_var = ctx.register_variable("$this")?;
240 let plan = QueryPlanner::plan(query, &ctx)?;
241 let executor = QueryExecutor::new(self.quins);
242 let focused = self
243 .quins
244 .iter()
245 .any(|q| q.subject == node || q.object == node);
246 if !focused {
247 return Ok(false);
248 }
249 match query {
250 SparqlQuery::Ask(_) => executor.execute_ask(&plan, &ctx),
251 _ => {
252 let results = executor.execute(&plan, &ctx)?;
253 Ok(!results.is_empty())
254 }
255 }
256 }
257
258 fn count_outgoing_triples(&self, node: u64) -> u64 {
259 let mut count = 0;
260 for quin in self.quins {
261 if quin.subject == node {
262 count += 1;
263 }
264 }
265 count
266 }
267
268 pub fn validate_graph(&self) -> Result<Vec<ValidationResult>, String> {
270 let mut results = Vec::new();
271
272 for shape_idx in 0..self.shape_count as usize {
274 let shape = self.shapes[shape_idx];
275
276 let target_nodes = self.find_target_nodes(&shape)?;
278
279 for node in target_nodes {
280 let result = self.validate_node(node, &shape)?;
281 results.push(result);
282 }
283 }
284
285 Ok(results)
286 }
287
288 fn find_target_nodes(&self, shape: &ShaclShape) -> Result<Vec<u64>, String> {
289 let mut nodes = Vec::new();
290
291 if let Some(target_node) = shape.target_node {
292 nodes.push(target_node);
293 } else if let Some(target_class) = shape.target_class {
294 let rdf_type = crate::lexicon::generate_60bit_token(
296 b"http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
297 );
298
299 for quin in self.quins {
300 if quin.predicate == rdf_type && quin.object == target_class {
301 nodes.push(quin.subject);
302 }
303 }
304 }
305
306 Ok(nodes)
307 }
308}
309
310impl<'a> Default for ShaclValidator<'a> {
311 fn default() -> Self {
312 Self::new(&[])
313 }
314}
315
316fn datatype_iri_to_tag(datatype_iri: u64) -> u8 {
317 if datatype_iri == crate::q_hash("xsd:string") {
318 0
319 } else if datatype_iri == crate::q_hash("xsd:integer") {
320 1
321 } else if datatype_iri == crate::q_hash("xsd:decimal")
322 || datatype_iri == crate::q_hash("xsd:double")
323 {
324 2
325 } else if datatype_iri == crate::q_hash("xsd:boolean") {
326 3
327 } else {
328 0
329 }
330}
331
332#[cfg(test)]
333mod tests {
334 use super::*;
335
336 #[test]
337 fn test_shacl_validator_creation() {
338 let quins = vec![];
339 let validator = ShaclValidator::new(&quins);
340 assert_eq!(validator.shape_count, 0);
341 }
342
343 #[test]
344 fn test_add_shape() {
345 let quins = vec![];
346 let mut validator = ShaclValidator::new(&quins);
347
348 let shape = ShaclShape {
349 shape_iri: 1,
350 target_class: None,
351 target_node: None,
352 constraints: [0; 32],
353 constraint_count: 0,
354 };
355
356 let result = validator.add_shape(shape);
357 assert!(result.is_ok());
358 assert_eq!(validator.shape_count, 1);
359 }
360
361 #[test]
362 fn test_add_constraint() {
363 let quins = vec![];
364 let mut validator = ShaclValidator::new(&quins);
365
366 let constraint = ShaclConstraint::NodeKind { node_kind: 1 };
367 let result = validator.add_constraint(constraint);
368 assert!(result.is_ok());
369 assert_eq!(validator.constraint_count, 1);
370 }
371}