Skip to main content

swls_core/systems/shapes/
describe.rs

1//! Documentation from SHACL property shapes, for the predicates of a subject.
2//!
3//! When a property shape applies to the subject (see [`super::model`]) and
4//! constrains a predicate, hover and completion for that predicate show:
5//!
6//! - `sh:name` and `sh:description`,
7//! - `rdfs:label` and `rdfs:comment` of the property shape,
8//! - a summary of its constraints (cardinality, node kind, datatype, class,
9//!   allowed values, nested shapes, patterns, ranges, severity).
10//!
11//! Texts are shown in the preferred language (see [`crate::util::lang_text`]).
12
13use std::collections::HashMap;
14
15use bevy_ecs::prelude::*;
16use sophia_api::term::{Term as _, TermKind};
17
18use super::model::*;
19use crate::{
20    feature::{
21        completion::{CompletionRequest, CursorContext, SimpleCompletion},
22        hover::HoverRequest,
23    },
24    lsp_types::{CompletionItemKind, TextEdit},
25    prelude::*,
26    systems::shapes::visible::{visible_shapes, ShapeDocs},
27    util::lang_text::normalize_ws,
28};
29
30/// Shortens IRIs for display: with the document's prefixes, else with those
31/// the shape documents declare (so `xsd:string` reads well even when the
32/// document does not declare `xsd:`).
33pub(crate) struct Names<'a> {
34    document: &'a Prefixes,
35    /// Every prefix the shape documents declare, as one set, so the choice
36    /// between them does not depend on the order the documents are visited.
37    shapes: Prefixes,
38}
39
40impl<'a> Names<'a> {
41    pub(crate) fn new(document: &'a Prefixes, shapes: Vec<&'a Prefixes>) -> Self {
42        let declared = shapes.iter().flat_map(|p| p.0.iter().cloned()).collect();
43        Self {
44            document,
45            shapes: Prefixes(declared, document.1.clone()),
46        }
47    }
48
49    /// `iri` as a prefixed name from the document's prefixes, else from the
50    /// shape documents' prefixes, else in full.
51    fn iri(&self, iri: &str) -> String {
52        self.document
53            .shorten(iri)
54            .or_else(|| self.shapes.shorten(iri))
55            .unwrap_or_else(|| format!("<{}>", iri))
56    }
57}
58
59fn term(names: &Names<'_>, node: Node<'_>) -> String {
60    match node.term.kind() {
61        TermKind::Iri => names.iri(&node.term.value),
62        TermKind::Literal => format!("\"{}\"", node.term.value),
63        _ => String::from("[ … ]"),
64    }
65}
66
67fn code(s: &str) -> String {
68    format!("`{}`", s.replace('`', "'"))
69}
70
71/// Name of a shape for display: its IRI, or a description of an anonymous one.
72fn shape_name(names: &Names<'_>, node: Node<'_>) -> String {
73    match node.term.kind() {
74        TermKind::Iri => code(&names.iri(&node.term.value)),
75        _ => String::from("an anonymous shape"),
76    }
77}
78
79fn number(graph: &ShapeGraph, node: Node<'_>, local: &str) -> Option<String> {
80    let v = graph.object(node, &sh(local))?;
81    Some(v.term.value.trim().to_string())
82}
83
84/// One-line summary of the constraints of property shape `prop`.
85pub(crate) fn constraints(graph: &ShapeGraph, prop: Node<'_>, names: &Names<'_>) -> Vec<String> {
86    let mut out = Vec::new();
87    let list = |local: &str| -> Vec<String> {
88        graph
89            .objects(prop, &sh(local))
90            .into_iter()
91            .flat_map(|l| graph.list(l))
92            .map(|t| code(&term(names, t)))
93            .collect()
94    };
95    let values = |local: &str| -> Vec<String> {
96        graph
97            .objects(prop, &sh(local))
98            .into_iter()
99            .map(|t| code(&term(names, t)))
100            .collect()
101    };
102
103    let min: f64 = graph.number(prop, &sh("minCount")).unwrap_or(0.0);
104    match min as u64 {
105        0 => {}
106        1 => out.push(String::from("required")),
107        n => out.push(format!("at least {n}")),
108    }
109    if let Some(max) = graph.number(prop, &sh("maxCount")) {
110        out.push(format!("at most {}", max as u64));
111    }
112
113    for kind in graph.objects(prop, &sh("nodeKind")) {
114        let kind = kind.term.value.strip_prefix(SH).unwrap_or(&kind.term.value);
115        out.push(String::from(match kind {
116            "IRI" => "IRI",
117            "BlankNode" => "blank node",
118            "Literal" => "literal",
119            "BlankNodeOrIRI" => "IRI or blank node",
120            "BlankNodeOrLiteral" => "blank node or literal",
121            "IRIOrLiteral" => "IRI or literal",
122            other => other,
123        }));
124    }
125    for dt in values("datatype") {
126        out.push(format!("datatype {dt}"));
127    }
128    for class in values("class") {
129        out.push(format!("instance of {class}"));
130    }
131    let allowed = list("in");
132    if !allowed.is_empty() {
133        out.push(format!("one of {}", allowed.join(", ")));
134    }
135    for v in values("hasValue") {
136        out.push(format!("value {v}"));
137    }
138    for node in graph.objects(prop, &sh("node")) {
139        out.push(format!("conforms to {}", shape_name(names, node)));
140    }
141    for (local, word) in [("or", "one of"), ("xone", "exactly one of")] {
142        for l in graph.objects(prop, &sh(local)) {
143            let branches: Vec<String> = graph
144                .list(l)
145                .into_iter()
146                .flat_map(|b| {
147                    if b.term.kind() == TermKind::Iri {
148                        return Some(shape_name(names, b));
149                    }
150                    graph
151                        .object(b, &sh("node"))
152                        .map(|n| shape_name(names, n))
153                        .or_else(|| graph.object(b, &sh("class")).map(|c| code(&term(names, c))))
154                        .or_else(|| {
155                            graph
156                                .object(b, &sh("datatype"))
157                                .map(|d| code(&term(names, d)))
158                        })
159                })
160                .collect();
161            if !branches.is_empty() {
162                out.push(format!("conforms to {} {}", word, branches.join(", ")));
163            }
164        }
165    }
166    if let Some(pattern) = graph.object(prop, &sh("pattern")) {
167        let p = &pattern.term.value;
168        let shown: String = p.chars().take(40).collect();
169        let ellipsis = if p.chars().count() > 40 { "…" } else { "" };
170        out.push(format!("matches {}{}", code(&shown), ellipsis));
171    }
172    for (local, sign) in [
173        ("minLength", "length ≥"),
174        ("maxLength", "length ≤"),
175        ("minInclusive", "≥"),
176        ("maxInclusive", "≤"),
177        ("minExclusive", ">"),
178        ("maxExclusive", "<"),
179    ] {
180        if let Some(v) = number(graph, prop, local) {
181            out.push(format!("{sign} {v}"));
182        }
183    }
184    let languages = list("languageIn");
185    if !languages.is_empty() {
186        out.push(format!("language one of {}", languages.join(", ")));
187    }
188    if graph.has(prop, &sh("uniqueLang"), "true") {
189        out.push(String::from("one value per language"));
190    }
191    if let Some(sev) = graph.object(prop, &sh("severity")) {
192        if sev.term.value != sh("Violation") {
193            let sev = sev.term.value.strip_prefix(SH).unwrap_or(&sev.term.value);
194            out.push(format!("severity {}", sev.to_lowercase()));
195        }
196    }
197    out
198}
199
200/// Markdown documenting property shape `applied` for a hover or completion.
201pub(crate) fn describe(
202    graph: &ShapeGraph,
203    applied: AppliedPropertyShape<'_>,
204    names: &Names<'_>,
205) -> String {
206    let prop = applied.node;
207    let texts = |p: &str| -> Vec<String> {
208        graph
209            .texts(prop, p)
210            .preferred()
211            .into_iter()
212            .map(|t| normalize_ws(t).into_owned())
213            .collect()
214    };
215    let shacl_names = texts(&sh("name"));
216    let descriptions = texts(&sh("description"));
217    // Shown as well, unless they repeat the SHACL text word for word.
218    let labels: Vec<_> = texts(RDFS_LABEL)
219        .into_iter()
220        .filter(|l| !shacl_names.contains(l))
221        .collect();
222    let comments: Vec<_> = texts(RDFS_COMMENT)
223        .into_iter()
224        .filter(|c| !descriptions.contains(c))
225        .collect();
226
227    let mut md = format!("**Shape** {}", shape_name(names, applied.owner));
228    if prop.term.kind() == TermKind::Iri {
229        md.push_str(&format!(" · property shape {}", shape_name(names, prop)));
230    }
231
232    let mut section = |title: &str, items: &[String]| {
233        if !items.is_empty() {
234            md.push_str(&format!("\n\n**{}:** {}", title, items.join(" / ")));
235        }
236    };
237    section("Name", &shacl_names);
238    section("Description", &descriptions);
239    section("Label", &labels);
240    section("Comment", &comments);
241
242    if let Some(paths) = property_paths(graph, prop).filter(|p| p.len() > 1) {
243        let paths: Vec<_> = paths.iter().map(|p| code(&names.iri(p))).collect();
244        md.push_str(&format!("\n\n**Any one of:** {}", paths.join(", ")));
245    }
246    let summary = constraints(graph, prop, names);
247    if !summary.is_empty() {
248        md.push_str(&format!("\n\n**Constraints:** {}", summary.join(" · ")));
249    }
250    md
251}
252
253/// Documentation of every property shape that applies to `focus`, per predicate.
254/// How much the shapes need a predicate on the subject, ordered from least to
255/// most urgent.
256#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
257enum Need {
258    /// Allowed, or already present often enough.
259    Optional,
260    /// One of the alternatives of a required `sh:alternativePath`, none of
261    /// which the subject has yet.
262    OneOfRequired,
263    /// Required (`sh:minCount >= 1`) and the subject does not have it yet.
264    Required,
265}
266
267impl Need {
268    /// Sort key prefix: required predicates come before every other
269    /// suggestion (`!` sorts before digits, letters and `@`).
270    fn sort_prefix(self) -> Option<&'static str> {
271        match self {
272            Need::Required => Some("!0"),
273            Need::OneOfRequired => Some("!1"),
274            Need::Optional => None,
275        }
276    }
277
278    fn label(self) -> Option<&'static str> {
279        match self {
280            Need::Required => Some("required by shape"),
281            Need::OneOfRequired => Some("one of required by shape"),
282            Need::Optional => None,
283        }
284    }
285}
286
287/// A predicate the shapes describe for the subject.
288struct ShapePredicate {
289    path: String,
290    docs: Vec<String>,
291    need: Need,
292}
293
294/// Documentation of every property shape that applies to `focus`, per
295/// predicate, with how much the shapes still need it.
296fn docs_per_predicate(
297    graph: &ShapeGraph,
298    focus: &Focus<'_>,
299    names: &Names<'_>,
300) -> Vec<ShapePredicate> {
301    let mut out: Vec<ShapePredicate> = Vec::new();
302    for applied in applied_property_shapes(graph, focus) {
303        let Some(paths) = property_paths(graph, applied.node) else {
304            continue;
305        };
306        let min = graph.number(applied.node, &sh("minCount")).unwrap_or(0.0);
307        let missing = !paths.iter().any(|p| focus.has_predicate(p));
308        let need = match (min >= 1.0 && missing, paths.len()) {
309            (false, _) => Need::Optional,
310            (true, 1) => Need::Required,
311            (true, _) => Need::OneOfRequired,
312        };
313        let doc = describe(graph, applied, names);
314        for path in paths {
315            match out.iter_mut().find(|p| p.path == path) {
316                Some(p) => {
317                    p.docs.push(doc.clone());
318                    p.need = p.need.max(need);
319                }
320                None => out.push(ShapePredicate {
321                    path,
322                    docs: vec![doc.clone()],
323                    need,
324                }),
325            }
326        }
327    }
328    out
329}
330
331/// Hover system: document a predicate with the property shapes that apply to
332/// it for this subject.
333pub fn hover_shape_property(
334    mut query: Query<(
335        &TripleComponent,
336        &Triples,
337        &Prefixes,
338        &Label,
339        &DocumentLinks,
340        &mut HoverRequest,
341    )>,
342    shapes: ShapeDocs,
343    mut cache: Local<ShapeCache>,
344    hierarchy: Res<TypeHierarchy>,
345    config: Res<ServerConfig>,
346) {
347    let local = &config.config.local;
348    if local.is_disabled(Disabled::HoverShapeProperty) || local.is_disabled(Disabled::Shapes) {
349        return;
350    }
351    for (triple, triples, prefixes, label, links, mut request) in &mut query {
352        if triple.target != TripleTarget::Predicate {
353            continue;
354        }
355        let predicate = &triple.triple.predicate;
356        if predicate.kind() != TermKind::Iri {
357            continue;
358        }
359        let (docs, shape_prefixes) = visible_shapes(&shapes, label, links);
360        if docs.is_empty() {
361            continue;
362        }
363        let graph = cache.graph(docs);
364        let names = Names::new(prefixes, shape_prefixes);
365        let focus = Focus::new(&triple.triple.subject, &triples.0, &hierarchy);
366        for applied in applied_property_shapes(&graph, &focus) {
367            let applies = property_paths(&graph, applied.node)
368                .is_some_and(|paths| paths.iter().any(|p| *p == predicate.value));
369            if applies {
370                request.0.push(describe(&graph, applied, &names));
371            }
372        }
373    }
374}
375
376/// Completion system: add shape documentation to property completions, and
377/// offer predicates that only the shapes declare.
378///
379/// Runs after [`complete_properties`](crate::systems::complete_properties).
380pub fn shape_property_completions(
381    mut query: Query<(
382        &CursorContext,
383        &Prefixes,
384        &Triples,
385        &Label,
386        &DocumentLinks,
387        &DynLang,
388        &mut CompletionRequest,
389    )>,
390    shapes: ShapeDocs,
391    mut cache: Local<ShapeCache>,
392    hierarchy: Res<TypeHierarchy>,
393    config: Res<ServerConfig>,
394) {
395    let local = &config.config.local;
396    if local.is_disabled(Disabled::CompletionProperty) || local.is_disabled(Disabled::Shapes) {
397        return;
398    }
399    for (cursor, prefixes, triples, label, links, lang, mut request) in &mut query {
400        if !cursor.at_predicate() {
401            continue;
402        }
403        let Some(subject) = cursor.subject.as_ref() else {
404            continue;
405        };
406        let (docs, shape_prefixes) = visible_shapes(&shapes, label, links);
407        if docs.is_empty() {
408            continue;
409        }
410        let graph = cache.graph(docs);
411        let names = Names::new(prefixes, shape_prefixes);
412        let focus = Focus::new(subject, &triples.0, &hierarchy);
413        let per_predicate = docs_per_predicate(&graph, &focus, &names);
414        if per_predicate.is_empty() {
415            continue;
416        }
417
418        let shortened: HashMap<String, usize> = per_predicate
419            .iter()
420            .enumerate()
421            .flat_map(|(i, p)| [(p.path.clone(), i), (names.iri(&p.path), i)])
422            .chain(
423                per_predicate
424                    .iter()
425                    .enumerate()
426                    .flat_map(|(i, p)| prefixes.shorten(&p.path).map(|s| (s, i))),
427            )
428            .collect();
429
430        // Document (and rank) the property suggestions that already exist.
431        let mut documented = vec![false; per_predicate.len()];
432        for item in request.0.iter_mut() {
433            if item.kind != CompletionItemKind::FIELD
434                && item.kind != CompletionItemKind::ENUM_MEMBER
435            {
436                continue;
437            }
438            let Some(&i) = shortened.get(&item.label) else {
439                continue;
440            };
441            documented[i] = true;
442            let predicate = &per_predicate[i];
443            let shape_docs = predicate.docs.join("\n\n---\n\n");
444            item._documentation = Some(match item._documentation.take() {
445                Some(d) if !d.is_empty() => format!("{d}\n\n---\n\n{shape_docs}"),
446                _ => shape_docs,
447            });
448            if let (Some(sort), Some(need)) = (predicate.need.sort_prefix(), predicate.need.label())
449            {
450                item._sort_text = Some(format!("{}{}", sort, item.label));
451                let title = item
452                    ._label_details
453                    .as_ref()
454                    .and_then(|d| d.description.clone())
455                    .filter(|t| !t.is_empty());
456                let description = match title {
457                    Some(title) => format!("{need} · {title}"),
458                    None => need.to_string(),
459                };
460                item.set_label_description(description);
461                item.kind = CompletionItemKind::FIELD;
462            }
463        }
464
465        // Predicates only the shapes know about.
466        let typed = lang.unquote(&cursor.typed);
467        for (i, predicate) in per_predicate.iter().enumerate() {
468            if documented[i] || focus_has(subject, &triples.0, &predicate.path) {
469                continue;
470            }
471            let short = lang.write_iri(prefixes, &predicate.path);
472            if !short.starts_with(typed) {
473                continue;
474            }
475            let sort = predicate.need.sort_prefix().unwrap_or("0");
476            let mut item = SimpleCompletion::new(
477                CompletionItemKind::FIELD,
478                short.clone(),
479                TextEdit {
480                    range: cursor.range,
481                    new_text: cursor.spaced(&lang.quote(&short)),
482                },
483            )
484            .documentation(predicate.docs.join("\n\n---\n\n"))
485            .sort_text(format!("{}{}", sort, short));
486            if let Some(need) = predicate.need.label() {
487                item = item.label_description(need);
488            }
489            request.0.push(item);
490        }
491    }
492}
493
494fn focus_has(subject: &MyTerm<'_>, triples: &[MyQuad<'static>], predicate: &str) -> bool {
495    triples
496        .iter()
497        .any(|t| t.subject == *subject && t.predicate.value == predicate)
498}