lsp_core/systems/
shapes.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
use std::{cell::OnceCell, collections::HashMap};

use bevy_ecs::prelude::*;
use lsp_types::{DiagnosticSeverity, TextDocumentItem};
use ropey::Rope;
use rudof_lib::{
    shacl_ast::{
        compiled::{schema::CompiledSchema, shape::CompiledShape},
        ShaclParser,
    },
    shacl_validation::{
        shacl_processor::{GraphValidation, ShaclProcessor},
        shape::Validate,
        store::graph::Graph,
        validation_report::result::ValidationResult,
    },
    srdf::{Object, SRDFGraph},
    RdfData,
};
use sophia_api::prelude::Quad as _;
use tracing::{info, instrument};

use crate::prelude::*;

fn get_reader<'a>(rope: &'a Rope) -> impl std::io::Read + 'a {
    use std::io::prelude::*;
    let reader: Box<dyn Read> = rope
        .chunks()
        .map(|x| std::io::Cursor::new(x.as_bytes()))
        .fold(Box::new(std::io::Cursor::new(&[])), |acc, chunk| {
            Box::new(acc.chain(chunk))
        });
    reader
}

type ShaclSchema = CompiledSchema<RdfData>;
pub fn derive_shapes(
    query: Query<
        (
            Entity,
            &RopeC,
            &Label,
            Option<&Wrapped<CompiledSchema<RdfData>>>,
        ),
        (Changed<Triples>, Without<Dirty>),
    >,
    mut commands: Commands,
) {
    for (e, rope, label, schema) in &query {
        if let Some(compiled) = SRDFGraph::from_reader(
            get_reader(&rope),
            &rudof_lib::RDFFormat::Turtle,
            Some(label.0.as_str()),
            &rudof_lib::ReaderMode::Lax,
        )
        .ok()
        .and_then(|data| RdfData::from_graph(data).ok())
        .and_then(|data| ShaclParser::new(data.clone()).parse().ok())
        .and_then(|shacl| ShaclSchema::try_from(shacl).ok())
        {
            let is_some = compiled.iter().next().is_some();
            info!(
                "Compiled shapes for {} (is some {})",
                label.as_str(),
                is_some
            );
            match (is_some, schema.is_some()) {
                (true, _) => {
                    commands.entity(e).insert(Wrapped(compiled));
                }
                (_, true) => {
                    commands
                        .entity(e)
                        .remove::<Wrapped<CompiledSchema<RdfData>>>();
                }
                _ => {}
            };
        } else {
            info!("Failed to compile shapes for {}", label.as_str());
        }
    }
}

fn get_path(
    source: Option<&Object>,
    s: &CompiledShape<RdfData>,
    prefixes: &Prefixes,
) -> Option<String> {
    let source = source?;
    let property = s
        .property_shapes()
        .iter()
        .find(|x| match (x.id(), source) {
            (rudof_lib::oxrdf::Term::NamedNode(named_node), Object::Iri(iri_s)) => {
                named_node.as_str() == iri_s.as_str()
            }
            (rudof_lib::oxrdf::Term::BlankNode(blank_node), Object::BlankNode(st)) => {
                blank_node.as_str() == st.as_str()
            }
            _ => false,
        })?;
    let path = property.path_str()?;
    Some(prefixes.shorten(&path).unwrap_or(path))
}

fn group_per_fn_per_path(
    res: &Vec<ValidationResult>,
    s: &CompiledShape<RdfData>,
    triples: &Triples,
    prefixes: &Prefixes,
) -> HashMap<std::ops::Range<usize>, HashMap<String, Vec<String>>> {
    let mut per_fn_per_path = HashMap::new();
    for r in res {
        info!("Res {:?}", r);
        let foc = r.focus_node().to_string();

        let mut done = std::collections::HashSet::new();
        for t in &triples.0 {
            if t.s().as_str() == &foc && !done.contains(t.s()) {
                done.insert(t.s().to_owned());

                let entry: &mut HashMap<String, Vec<String>> =
                    per_fn_per_path.entry(t.s().span.clone()).or_default();

                let path = get_path(r.source(), s, prefixes).unwrap_or(String::new());
                let entry = entry.entry(path).or_default();

                let component = r.component().to_string();
                let component = prefixes.shorten(&component).unwrap_or(component);

                entry.push(component);
            }
        }
    }

    per_fn_per_path
}

fn push_diagnostics(
    rope: &Rope,
    res: &Vec<ValidationResult>,
    s: &CompiledShape<RdfData>,
    triples: &Triples,
    prefixes: &Prefixes,
    diagnostics: &mut Vec<lsp_types::Diagnostic>,
) {
    for (range, per_path) in group_per_fn_per_path(&res, s, triples, prefixes) {
        if let Some(range) = range_to_range(&range, &rope) {
            for (path, components) in per_path {
                let mut comps = components[0].clone();
                for c in components.into_iter().skip(1) {
                    comps += ", ";
                    comps += &c;
                }

                diagnostics.push(lsp_types::Diagnostic {
                    range: range.clone(),
                    severity: Some(DiagnosticSeverity::ERROR),
                    source: Some(String::from("SWLS")),
                    message: format!("Path {} violates {}", path, comps),
                    related_information: None,
                    ..Default::default()
                });
            }
        }
    }
}

fn derive_shapes_diagnostics_for(
    rope: &RopeC,
    label: &Label,
    links: &DocumentLinks,
    item: &Wrapped<TextDocumentItem>,
    triples: &Triples,
    other: &Query<(&Label, &Wrapped<ShaclSchema>, &Prefixes)>,
    client: &mut DiagnosticPublisher,
) {
    let mut diagnostics: Vec<lsp_types::Diagnostic> = Vec::new();

    let build_validator = || {
        SRDFGraph::from_reader(
            get_reader(&rope),
            &rudof_lib::RDFFormat::Turtle,
            Some(label.0.as_str()),
            &rudof_lib::ReaderMode::Lax,
        )
        .ok()
        .and_then(|data| RdfData::from_graph(data).ok())
        .map(|data| {
            info!("Created graph validator for {}", label.as_str());
            GraphValidation::from_graph(
                Graph::from_data(data),
                rudof_lib::ShaclValidationMode::Native,
            )
        })
    };

    // Delayed building, maybe no shapes are linked to this document, and we don't need to build a
    // validator
    let validator = OnceCell::<Option<GraphValidation>>::new();
    for (other_label, schema, prefixes) in other {
        if links
            .iter()
            .find(|link| link.0.as_str().starts_with(other_label.0.as_str()))
            .is_none()
            && label.0 != other_label.0
        {
            continue;
        }

        if let Some(validator) = validator.get_or_init(build_validator) {
            info!("Schema {}", other_label.as_str());
            for (_, s) in schema.iter() {
                if let Ok(res) = s.validate(validator.store(), validator.runner(), None) {
                    if !res.is_empty() {
                        info!("Validations for {:?}", s);
                        push_diagnostics(rope, &res, s, triples, prefixes, &mut diagnostics);
                    }
                }
            }
        } else {
            break;
        }
    }

    let _ = client.publish(&item.0, diagnostics, "shacl_validation");
}

/// System evaluates linked shapes
#[instrument(skip(query, other, client))]
pub fn validate_shapes(
    query: Query<
        (
            &RopeC,
            &Label,
            &DocumentLinks,
            &Wrapped<TextDocumentItem>,
            &Triples,
        ),
        (Changed<Triples>, Without<Dirty>, With<Open>),
    >,
    other: Query<(&Label, &Wrapped<ShaclSchema>, &Prefixes)>,
    mut client: ResMut<DiagnosticPublisher>,
) {
    for (rope, label, links, item, triples) in &query {
        info!("Validate shapes {}", label.as_str());
        derive_shapes_diagnostics_for(rope, label, links, item, triples, &other, &mut client);
    }
}

/// System checks what entities should retrigger a shape evaluation when a shape changes
#[instrument(skip(changed_schemas, query, other, client))]
pub fn validate_with_updated_shapes(
    changed_schemas: Query<&Label, (Changed<Wrapped<ShaclSchema>>, With<Open>)>,
    query: Query<
        (
            &RopeC,
            &Label,
            &DocumentLinks,
            &Wrapped<TextDocumentItem>,
            &Triples,
        ),
        With<Open>,
    >,
    other: Query<(&Label, &Wrapped<ShaclSchema>, &Prefixes)>,
    mut client: ResMut<DiagnosticPublisher>,
) {
    for l in &changed_schemas {
        info!("Changed schema {}", l.as_str());
        for (rope, label, links, item, triples) in &query {
            if links
                .iter()
                .find(|(url, _)| url.as_str().starts_with(l.as_str()))
                .is_some()
            {
                info!("Found reverse linked document! {}", label.as_str());
                derive_shapes_diagnostics_for(
                    rope,
                    label,
                    links,
                    item,
                    triples,
                    &other,
                    &mut client,
                );
            }
        }
    }
}