Skip to main content

shacl_ir/compiled/
shape.rs

1use super::compiled_shacl_error::CompiledShaclError;
2use super::component_ir::ComponentIR;
3use super::node_shape::NodeShapeIR;
4use super::property_shape::PropertyShapeIR;
5use super::target::CompiledTarget;
6use crate::dependency_graph::{DependencyGraph, PosNeg};
7use crate::reifier_info::ReifierInfo;
8use crate::schema_ir::SchemaIR;
9use crate::severity::CompiledSeverity;
10use crate::shape_label_idx::ShapeLabelIdx;
11use iri_s::IriS;
12use rudof_rdf::rdf_core::{Rdf, SHACLPath, term::Object};
13use shacl_ast::ShaclSchema;
14use shacl_ast::shape::Shape;
15use std::collections::HashSet;
16use std::fmt::Display;
17
18#[derive(Debug, Clone)]
19pub enum ShapeIR {
20    NodeShape(Box<NodeShapeIR>),
21    PropertyShape(Box<PropertyShapeIR>),
22}
23
24impl ShapeIR {
25    pub fn deactivated(&self) -> bool {
26        match self {
27            ShapeIR::NodeShape(ns) => ns.deactivated(),
28            ShapeIR::PropertyShape(ps) => ps.deactivated(),
29        }
30    }
31
32    pub fn reifier_info(&self) -> Option<ReifierInfo> {
33        match self {
34            ShapeIR::NodeShape(_ns) => None,
35            ShapeIR::PropertyShape(ps) => ps.reifier_info(),
36        }
37    }
38
39    pub fn path(&self) -> Option<SHACLPath> {
40        match self {
41            ShapeIR::NodeShape(_) => None,
42            ShapeIR::PropertyShape(ps) => Some(ps.path().clone()),
43        }
44    }
45
46    pub fn show_severity(&self) -> String {
47        if let Some(severity) = self.severity().into() {
48            format!("(severity: {severity})")
49        } else {
50            "(severity: Violation)".to_string()
51        }
52    }
53
54    pub fn id(&self) -> &Object {
55        match self {
56            ShapeIR::NodeShape(ns) => ns.id(),
57            ShapeIR::PropertyShape(ps) => ps.id(),
58        }
59    }
60
61    pub fn targets(&self) -> &Vec<CompiledTarget> {
62        match self {
63            ShapeIR::NodeShape(ns) => ns.targets(),
64            ShapeIR::PropertyShape(ps) => ps.targets(),
65        }
66    }
67
68    pub fn components(&self) -> &Vec<ComponentIR> {
69        match self {
70            ShapeIR::NodeShape(ns) => ns.components(),
71            ShapeIR::PropertyShape(ps) => ps.components(),
72        }
73    }
74
75    pub fn property_shapes(&self) -> &Vec<ShapeLabelIdx> {
76        match self {
77            ShapeIR::NodeShape(ns) => ns.property_shapes(),
78            ShapeIR::PropertyShape(ps) => ps.property_shapes(),
79        }
80    }
81
82    pub fn path_str(&self) -> Option<String> {
83        match self {
84            ShapeIR::NodeShape(_) => None,
85            ShapeIR::PropertyShape(ps) => Some(ps.path().to_string()),
86        }
87    }
88
89    pub fn severity_iri(&self) -> IriS {
90        let iri_s: IriS = match self {
91            ShapeIR::NodeShape(ns) => ns.severity().iri(),
92            ShapeIR::PropertyShape(ps) => ps.severity().iri(),
93        };
94        iri_s
95    }
96
97    pub fn severity(&self) -> CompiledSeverity {
98        match self {
99            ShapeIR::NodeShape(ns) => ns.severity(),
100            ShapeIR::PropertyShape(ps) => ps.severity(),
101        }
102    }
103
104    pub fn compile<RDF: Rdf>(
105        shape: Shape<RDF>,
106        schema: &ShaclSchema<RDF>,
107        idx: &ShapeLabelIdx,
108        schema_ir: &mut SchemaIR,
109    ) -> Result<ShapeLabelIdx, Box<CompiledShaclError>> {
110        let shape_ir = match shape {
111            Shape::NodeShape(node_shape) => {
112                let node_shape = NodeShapeIR::compile(node_shape, schema, schema_ir)?;
113                ShapeIR::NodeShape(Box::new(node_shape))
114            },
115            Shape::PropertyShape(property_shape) => {
116                let property_shape = PropertyShapeIR::compile(*property_shape, schema, schema_ir)?;
117                ShapeIR::PropertyShape(Box::new(property_shape))
118            },
119        };
120        let idx = schema_ir.add_shape(*idx, shape_ir)?;
121        Ok(idx)
122    }
123
124    pub(crate) fn add_edges(
125        &self,
126        shape_idx: ShapeLabelIdx,
127        dg: &mut DependencyGraph,
128        posneg: PosNeg,
129        schema_ir: &SchemaIR,
130        visited: &mut HashSet<ShapeLabelIdx>,
131    ) {
132        match self {
133            ShapeIR::NodeShape(ns) => {
134                ns.add_edges(shape_idx, dg, posneg, schema_ir, visited);
135            },
136            ShapeIR::PropertyShape(ps) => {
137                ps.add_edges(shape_idx, dg, posneg, schema_ir, visited);
138            },
139        }
140    }
141
142    pub fn closed(&self) -> bool {
143        match self {
144            ShapeIR::NodeShape(ns) => ns.closed(),
145            ShapeIR::PropertyShape(ps) => ps.closed(),
146        }
147    }
148
149    pub fn allowed_properties(&self) -> HashSet<IriS> {
150        match self {
151            ShapeIR::NodeShape(ns) => ns.allowed_properties(),
152            ShapeIR::PropertyShape(ps) => ps.allowed_properties(),
153        }
154    }
155}
156
157impl Display for ShapeIR {
158    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
159        match self {
160            ShapeIR::NodeShape(_shape) => {
161                writeln!(f, "NodeShape")?;
162            },
163            ShapeIR::PropertyShape(shape) => {
164                writeln!(f, "PropertyShape")?;
165                writeln!(f, " path: {}", shape.path())?;
166                if let Some(reifier_info) = shape.reifier_info() {
167                    writeln!(
168                        f,
169                        " reifier info: reification required: {}, reifier shapes: [{}]",
170                        reifier_info.reification_required(),
171                        reifier_info
172                            .reifier_shape()
173                            .iter()
174                            .map(|s| s.to_string())
175                            .collect::<Vec<_>>()
176                            .join(", ")
177                    )?;
178                }
179            },
180        }
181        if self.deactivated() {
182            writeln!(f, " Deactivated: {}", self.deactivated())?;
183        }
184        if self.severity() != CompiledSeverity::Violation {
185            writeln!(f, " Severity: {}", self.severity())?;
186        }
187        if self.closed() {
188            writeln!(f, " closed: {}", self.closed())?;
189        }
190        let mut components = self.components().iter().peekable();
191        if components.peek().is_some() {
192            writeln!(f, " Components:")?;
193            for component in components {
194                writeln!(f, "  - {component}")?;
195            }
196        }
197        let mut targets = self.targets().iter().peekable();
198        if targets.peek().is_some() {
199            writeln!(f, " Targets:")?;
200            for target in targets {
201                writeln!(f, "  - {target}")?;
202            }
203        }
204        let mut property_shapes = self.property_shapes().iter().peekable();
205        if property_shapes.peek().is_some() {
206            writeln!(
207                f,
208                " Property Shapes: [{}]",
209                property_shapes.map(|ps| ps.to_string()).collect::<Vec<_>>().join(", ")
210            )?;
211        }
212        Ok(())
213    }
214}