1use std::collections::{HashMap, HashSet};
10
11use super::shacl_types::{CompiledShape, ShaclConstraint, ShaclSeverity};
12use super::text_input::build_graph;
13use crate::{q_hash, NQuin};
14
15fn pred_aliases(local: &str) -> Vec<u64> {
17 let full = format!("http://www.w3.org/ns/shacl#{local}");
18 let short = format!("sh:{local}");
19 vec![q_hash(&full), q_hash(&short), q_hash(local)]
20}
21
22fn is_pred(p: u64, local: &str) -> bool {
25 pred_aliases(local).contains(&p)
26}
27
28fn rdf_type() -> u64 {
31 q_hash("a")
33}
34
35fn is_node_shape_type(o: u64, resolve: &HashMap<u64, String>) -> bool {
38 if let Some(s) = resolve.get(&o) {
39 return s == "sh:NodeShape"
40 || s.ends_with("#NodeShape")
41 || s.ends_with(":NodeShape")
42 || s == "NodeShape";
43 }
44 pred_aliases("NodeShape").contains(&o)
45}
46
47fn lexical(h: u64, resolve: &HashMap<u64, String>) -> String {
50 resolve
51 .get(&h)
52 .cloned()
53 .unwrap_or_else(|| format!("node:{h:016x}"))
54}
55
56fn object_f64(object: u64, resolve: &HashMap<u64, String>) -> Option<f64> {
60 if let Some(s) = resolve.get(&object) {
61 if let Ok(i) = s.parse::<i64>() {
62 return Some(i as f64);
63 }
64 if let Ok(f) = s.parse::<f64>() {
65 return Some(f);
66 }
67 }
68 crate::modalities::logic::shacl::validate::object_as_f64(object)
69}
70
71fn objects_of<'a>(quins: &'a [NQuin], subject: u64, pred_local: &str) -> Vec<&'a NQuin> {
74 quins
75 .iter()
76 .filter(|q| q.subject == subject && is_pred(q.predicate, pred_local))
77 .collect()
78}
79
80fn first_object(quins: &[NQuin], subject: u64, pred_local: &str) -> Option<u64> {
83 objects_of(quins, subject, pred_local)
84 .first()
85 .map(|q| q.object)
86}
87
88fn constraint_from_property(
93 quins: &[NQuin],
94 prop_node: u64,
95 resolve: &HashMap<u64, String>,
96) -> Result<Vec<ShaclConstraint>, String> {
97 let mut out = Vec::new();
98 let mut in_values: Vec<String> = Vec::new();
99 let mut and_values: Vec<String> = Vec::new();
100 let mut or_values: Vec<String> = Vec::new();
101 let mut xone_values: Vec<String> = Vec::new();
102 let mut lang_in_values: Vec<String> = Vec::new();
103 let mut is_closed = false;
104 let mut ignored_props: Vec<String> = Vec::new();
105
106 for q in quins.iter().filter(|q| q.subject == prop_node) {
107 let Some(pname) = resolve.get(&q.predicate) else {
108 push_constraint_by_hash(
110 quins,
111 q.predicate,
112 q.object,
113 resolve,
114 &mut out,
115 &mut in_values,
116 );
117 continue;
118 };
119 let is_shacl_ns =
120 pname.starts_with("sh:") || pname.starts_with("http://www.w3.org/ns/shacl#");
121 let local = pname
122 .rsplit(['#', ':', '/'])
123 .next()
124 .unwrap_or(pname.as_str());
125
126 if is_shacl_ns && !is_known_shacl_local(local) {
127 return Err(format!("unknown SHACL predicate: {pname}"));
128 }
129
130 match local {
131 "in" => push_list_items(q.object, resolve, &mut in_values),
132 "and" => push_shape_ref_items(quins, q.object, resolve, &mut and_values),
133 "or" => push_shape_ref_items(quins, q.object, resolve, &mut or_values),
134 "xone" => push_shape_ref_items(quins, q.object, resolve, &mut xone_values),
135 "languageIn" => push_list_items(q.object, resolve, &mut lang_in_values),
136 "closed" => {
137 let v = lexical(q.object, resolve);
138 if v == "true" || v == "1" || object_f64(q.object, resolve) == Some(1.0) {
139 is_closed = true;
140 }
141 }
142 "ignoredProperties" => push_list_items(q.object, resolve, &mut ignored_props),
143 _ => push_constraint(quins, local, q.object, resolve, &mut out),
144 }
145 }
146
147 if !in_values.is_empty() {
148 out.push(ShaclConstraint::In(in_values));
149 }
150 if !and_values.is_empty() {
151 out.push(ShaclConstraint::And(and_values));
152 }
153 if !or_values.is_empty() {
154 out.push(ShaclConstraint::Or(or_values));
155 }
156 if !xone_values.is_empty() {
157 out.push(ShaclConstraint::Xone(xone_values));
158 }
159 if !lang_in_values.is_empty() {
160 out.push(ShaclConstraint::LanguageIn(lang_in_values));
161 }
162 if is_closed {
163 out.push(ShaclConstraint::Closed {
164 ignored_properties: ignored_props,
165 });
166 }
167
168 Ok(out)
169}
170
171fn is_known_shacl_local(local: &str) -> bool {
173 matches!(
174 local,
175 "minInclusive"
176 | "maxInclusive"
177 | "minExclusive"
178 | "maxExclusive"
179 | "minCount"
180 | "maxCount"
181 | "minLength"
182 | "maxLength"
183 | "pattern"
184 | "class"
185 | "datatype"
186 | "nodeKind"
187 | "hasValue"
188 | "in"
189 | "equals"
190 | "lessThan"
191 | "lessThanOrEquals"
192 | "greaterThan"
193 | "greaterThanOrEquals"
194 | "node"
195 | "not"
196 | "and"
197 | "or"
198 | "xone"
199 | "languageIn"
200 | "uniqueLang"
201 | "closed"
202 | "ignoredProperties"
203 | "path"
204 | "targetClass"
205 | "targetNode"
206 | "targetObjectsOf"
207 | "targetSubjectsOf"
208 | "property"
209 | "severity"
210 | "name"
211 | "description"
212 | "message"
213 | "sparql"
214 | "select"
215 | "prefixes"
216 | "declare"
217 | "prefix"
218 | "namespace"
219 | "order"
220 | "group"
221 | "defaultValue"
222 | "flags"
223 | "deactivated"
224 | "NodeShape"
225 | "PropertyShape"
226 | "deonticObligate"
227 | "DeonticObligate"
228 | "deonticPermit"
229 | "DeonticPermit"
230 | "deonticForbid"
231 | "DeonticForbid"
232 | "valuesConsentNonCoerced"
233 | "ValuesConsentNonCoerced"
234 | "valuesHarmBelowCeiling"
235 | "ValuesHarmBelowCeiling"
236 )
237}
238
239fn resolve_shape_ref(quins: &[NQuin], object: u64, resolve: &HashMap<u64, String>) -> String {
243 first_object(quins, object, "targetClass")
244 .map(|tc| lexical(tc, resolve))
245 .unwrap_or_else(|| lexical(object, resolve))
246}
247
248fn push_list_items(object: u64, resolve: &HashMap<u64, String>, out: &mut Vec<String>) {
249 let raw = lexical(object, resolve);
250 let trimmed = raw.trim();
251 if trimmed.starts_with('(') && trimmed.ends_with(')') {
252 let inner = &trimmed[1..trimmed.len() - 1];
253 for tok in inner.split_whitespace() {
254 let clean = tok.trim_matches('"');
255 if !clean.is_empty() {
256 out.push(clean.to_string());
257 }
258 }
259 } else if !trimmed.is_empty() {
260 out.push(trimmed.trim_matches('"').to_string());
261 }
262}
263
264fn push_shape_ref_items(
265 quins: &[NQuin],
266 object: u64,
267 resolve: &HashMap<u64, String>,
268 out: &mut Vec<String>,
269) {
270 out.push(resolve_shape_ref(quins, object, resolve));
271}
272
273fn push_constraint_by_hash(
277 quins: &[NQuin],
278 pred: u64,
279 object: u64,
280 resolve: &HashMap<u64, String>,
281 out: &mut Vec<ShaclConstraint>,
282 in_values: &mut Vec<String>,
283) {
284 if is_pred(pred, "in") {
285 push_list_items(object, resolve, in_values);
286 return;
287 }
288 for local in [
289 "minInclusive",
290 "maxInclusive",
291 "minExclusive",
292 "maxExclusive",
293 "minCount",
294 "maxCount",
295 "minLength",
296 "maxLength",
297 "pattern",
298 "class",
299 "datatype",
300 "nodeKind",
301 "hasValue",
302 "node",
303 "not",
304 ] {
305 if is_pred(pred, local) {
306 push_constraint(quins, local, object, resolve, out);
307 return;
308 }
309 }
310}
311
312fn push_constraint(
316 quins: &[NQuin],
317 local: &str,
318 object: u64,
319 resolve: &HashMap<u64, String>,
320 out: &mut Vec<ShaclConstraint>,
321) {
322 let text = || lexical(object, resolve);
323 let num = || object_f64(object, resolve).unwrap_or(0.0);
324 let u = || num() as u32;
325 match local {
326 "minInclusive" => out.push(ShaclConstraint::MinInclusive(num())),
327 "maxInclusive" => out.push(ShaclConstraint::MaxInclusive(num())),
328 "minExclusive" => out.push(ShaclConstraint::MinExclusive(num())),
329 "maxExclusive" => out.push(ShaclConstraint::MaxExclusive(num())),
330 "minCount" => out.push(ShaclConstraint::MinCount(u())),
331 "maxCount" => out.push(ShaclConstraint::MaxCount(u())),
332 "minLength" => out.push(ShaclConstraint::MinLength(u())),
333 "maxLength" => out.push(ShaclConstraint::MaxLength(u())),
334 "pattern" => out.push(ShaclConstraint::Pattern(text())),
335 "class" => out.push(ShaclConstraint::Class(text())),
336 "datatype" => out.push(ShaclConstraint::DataType(text())),
337 "nodeKind" => out.push(ShaclConstraint::NodeKind(text())),
338 "hasValue" => out.push(ShaclConstraint::HasValue(text())),
339 "equals" => out.push(ShaclConstraint::Equals(text())),
340 "lessThan" => out.push(ShaclConstraint::LessThan(text())),
341 "lessThanOrEquals" => out.push(ShaclConstraint::LessThanOrEquals(text())),
342 "greaterThan" => out.push(ShaclConstraint::GreaterThan(text())),
343 "greaterThanOrEquals" => out.push(ShaclConstraint::GreaterThanOrEquals(text())),
344 "node" => out.push(ShaclConstraint::Node(resolve_shape_ref(
345 quins, object, resolve,
346 ))),
347 "not" => out.push(ShaclConstraint::Not(resolve_shape_ref(
348 quins, object, resolve,
349 ))),
350 "uniqueLang" => out.push(ShaclConstraint::UniqueLang),
351 "deonticObligate" | "DeonticObligate" => out.push(ShaclConstraint::DeonticObligate),
352 "deonticPermit" | "DeonticPermit" => out.push(ShaclConstraint::DeonticPermit),
353 "deonticForbid" | "DeonticForbid" => out.push(ShaclConstraint::DeonticForbid),
354 "valuesConsentNonCoerced" | "ValuesConsentNonCoerced" => {
355 let n = num();
356 out.push(ShaclConstraint::ValuesConsentNonCoerced {
357 max_imbalance: if n.is_finite() && n > 0.0 { n } else { 0.5 },
358 })
359 }
360 "valuesHarmBelowCeiling" | "ValuesHarmBelowCeiling" => {
361 out.push(ShaclConstraint::ValuesHarmBelowCeiling { max_harm: num() })
362 }
363 "path" | "targetClass" | "property" | "severity" | "name" | "description" | "message" => {}
364 _ => {}
365 }
366}
367
368pub fn shapes_from_turtle(turtle: &str) -> Result<Vec<CompiledShape>, String> {
373 let (quins, resolve) = build_graph(turtle);
374 if quins.is_empty() {
375 return Err("empty SHACL Turtle / N3 document".into());
376 }
377
378 let mut shape_nodes: HashSet<u64> = HashSet::new();
379 for q in &quins {
380 if q.predicate == rdf_type() && is_node_shape_type(q.object, &resolve) {
381 shape_nodes.insert(q.subject);
382 }
383 if is_pred(q.predicate, "targetClass") {
384 shape_nodes.insert(q.subject);
385 }
386 }
387 if shape_nodes.is_empty() {
388 return Err("no sh:NodeShape / sh:targetClass found".into());
389 }
390
391 let mut shapes = Vec::new();
392 for shape_id in shape_nodes {
393 let target = first_object(&quins, shape_id, "targetClass")
394 .map(|o| lexical(o, &resolve))
395 .unwrap_or_else(|| lexical(shape_id, &resolve));
396
397 let severity = match first_object(&quins, shape_id, "severity")
398 .and_then(|o| resolve.get(&o).map(|s| s.as_str()))
399 {
400 Some(s) if s.contains("Warning") || s.ends_with("warning") => ShaclSeverity::Warning,
401 Some(s) if s.contains("Info") || s.ends_with("info") => ShaclSeverity::Info,
402 _ => ShaclSeverity::Violation,
403 };
404
405 let prop_nodes: Vec<u64> = objects_of(&quins, shape_id, "property")
406 .into_iter()
407 .map(|q| q.object)
408 .collect();
409
410 for prop in &prop_nodes {
411 let path = first_object(&quins, *prop, "path")
412 .map(|o| lexical(o, &resolve))
413 .unwrap_or_default();
414 let constraints = constraint_from_property(&quins, *prop, &resolve)?;
415 if constraints.is_empty() {
416 continue;
417 }
418 let mut shape = CompiledShape::new(target.clone(), constraints, severity);
419 shape.property_path = path;
420 shape.name = Some(lexical(shape_id, &resolve));
421 shapes.push(shape);
422 }
423
424 let node_constraints = constraint_from_property(&quins, shape_id, &resolve)?;
427 if !node_constraints.is_empty() {
428 let mut shape = CompiledShape::new(target, node_constraints, severity);
429 shape.property_path = String::new();
430 shape.name = Some(lexical(shape_id, &resolve));
431 shapes.push(shape);
432 }
433 }
434
435 if shapes.is_empty() {
436 return Err("SHACL Turtle compiled to zero usable constraints".into());
437 }
438 Ok(shapes)
439}
440
441pub fn validate_turtle_shapes(
443 data: &str,
444 shapes_ttl: &str,
445) -> Result<super::shacl_types::ValidationReport, String> {
446 let shapes = shapes_from_turtle(shapes_ttl)?;
447 let (quins, resolver) = build_graph(data);
448 let engine = super::validate::ShaclEngine::new(&quins, &shapes);
449 Ok(engine.validate(&|h| resolver.get(&h).cloned()))
450}
451
452#[cfg(test)]
453mod tests {
454 use super::*;
455
456 #[test]
457 fn turtle_nodeshape_mininclusive_rejects_underage() {
458 let shapes = r#"
459:PersonShape a sh:NodeShape .
460:PersonShape sh:targetClass :Person .
461:PersonShape sh:property :ageProp .
462:ageProp sh:path :age .
463:ageProp sh:minInclusive 18 .
464"#;
465 let compiled = shapes_from_turtle(shapes).expect("compile");
466 assert_eq!(compiled.len(), 1);
467 assert_eq!(compiled[0].shape_class, ":Person");
468 assert_eq!(compiled[0].property_path, ":age");
469 assert!(matches!(
470 compiled[0].constraints[0],
471 ShaclConstraint::MinInclusive(v) if (v - 18.0).abs() < 1e-9
472 ));
473
474 let data = ":alice a :Person .\n:alice :age 15 .\n:bob a :Person .\n:bob :age 40 .";
475 let report = validate_turtle_shapes(data, shapes).expect("validate");
476 assert!(!report.conforms, "15 < 18 must violate");
477 }
478
479 #[test]
480 fn empty_turtle_fails_closed() {
481 assert!(shapes_from_turtle("").is_err());
482 assert!(shapes_from_turtle(":x :y :z .").is_err());
483 }
484
485 #[test]
486 fn nodeshape_compiles_both_property_and_node_level_not() {
487 let shapes = r#"
488idf:NaturalAgentShape a sh:NodeShape ;
489 sh:targetClass idf:NaturalAgent ;
490 sh:property idf:NaturalAgent-planeProp ;
491 sh:not idf:NaturalAgent-notOwlThing .
492idf:NaturalAgent-planeProp sh:path idf:plane ;
493 sh:minCount 1 ;
494 sh:hasValue "NaturalAgent" .
495idf:NaturalAgent-notOwlThing a sh:NodeShape ;
496 sh:class owl:Thing .
497"#;
498 let ok_data = r#"
499:alice a idf:NaturalAgent ;
500 idf:plane "NaturalAgent" .
501"#;
502 let ok_report = validate_turtle_shapes(ok_data, shapes).expect("validate ok");
503 assert!(ok_report.conforms, "valid NaturalAgent must conform");
504
505 let bad_thing_data = r#"
506:alice a idf:NaturalAgent ;
507 a owl:Thing ;
508 idf:plane "NaturalAgent" .
509"#;
510 let bad_report = validate_turtle_shapes(bad_thing_data, shapes).expect("validate bad");
511 assert!(
512 !bad_report.conforms,
513 "NaturalAgent also typed owl:Thing must violate sh:not even when sh:property conforms"
514 );
515 }
516
517 #[test]
518 fn sh_in_and_unknown_shacl_predicate_fail_closed() {
519 let shapes = r#"
520idf:KeyRoleShape a sh:NodeShape ;
521 sh:targetClass idf:KeyGrant ;
522 sh:property idf:KeyRole-prop .
523idf:KeyRole-prop sh:path idf:memberKeyRole ;
524 sh:minCount 1 ;
525 sh:in "SessionAuthentication" , "RouteUpdate" , "TransportAead" .
526"#;
527 let ok_data = ":g1 a idf:KeyGrant ; idf:memberKeyRole \"SessionAuthentication\" .";
528 assert!(validate_turtle_shapes(ok_data, shapes).unwrap().conforms);
529
530 let bad_data = ":g2 a idf:KeyGrant ; idf:memberKeyRole \"UnknownRole\" .";
531 assert!(!validate_turtle_shapes(bad_data, shapes).unwrap().conforms);
532
533 let unknown_pred_shapes = r#"
534idf:BadShape a sh:NodeShape ;
535 sh:targetClass idf:Bad ;
536 sh:property idf:Bad-prop .
537idf:Bad-prop sh:path idf:x ;
538 sh:unknownInventedConstraint 42 .
539"#;
540 assert!(
541 shapes_from_turtle(unknown_pred_shapes).is_err(),
542 "unknown sh:* predicate must fail closed"
543 );
544 }
545}