Skip to main content

swls_core/systems/shapes/
template.rs

1//! Completion templates generated from SHACL shapes.
2//!
3//! At a predicate position, the node shapes that apply to the subject are
4//! collected and turned into two snippet completions:
5//!
6//! - **required properties**: every property with `sh:minCount >= 1`,
7//! - **all properties**: every property the shapes declare.
8//!
9//! Properties the subject already has are left out, so a template can also be
10//! used to complete a partially written resource.
11//!
12//! Which shapes apply follows SHACL targets, evaluated on the document:
13//! `sh:targetClass` (including superclasses known from the ontologies, and
14//! implicit class targets), `sh:targetSubjectsOf`, `sh:targetObjectsOf` and
15//! `sh:targetNode`. The properties of a shape include those of the shapes it
16//! refers to with `sh:node` and `sh:and`. Branches of `sh:or` / `sh:xone` are
17//! alternatives, so none of them is assumed.
18//!
19//! Values are placeholders shaped by the constraints of the property:
20//! `sh:hasValue` is filled in, `sh:in` becomes a choice, a nested `sh:node`
21//! becomes `[ … ]` with that shape's required properties, and `sh:nodeKind` /
22//! `sh:datatype` decide between `<…>`, `"…"` and plain placeholders.
23
24use bevy_ecs::prelude::*;
25
26use super::model::*;
27use crate::{
28    feature::completion::{CompletionRequest, CursorContext, SimpleCompletion},
29    lsp_types::{CompletionItemKind, Position, TextEdit},
30    prelude::*,
31    systems::shapes::visible::{visible_shapes, ShapeDocs},
32};
33
34// ─── Rendering ───────────────────────────────────────────────────────────────
35
36/// Escape text for use inside an LSP snippet.
37fn escape(text: &str) -> String {
38    text.replace('\\', "\\\\")
39        .replace('$', "\\$")
40        .replace('}', "\\}")
41}
42
43/// Escape a choice of an LSP snippet `${1|a,b|}`.
44fn escape_choice(text: &str) -> String {
45    escape(text).replace(',', "\\,").replace('|', "\\|")
46}
47
48struct Renderer<'a> {
49    prefixes: &'a Prefixes,
50    tabstop: usize,
51}
52
53impl Renderer<'_> {
54    fn iri(&self, iri: &str) -> String {
55        self.prefixes
56            .shorten(iri)
57            .unwrap_or_else(|| format!("<{}>", iri))
58    }
59
60    fn term(&self, term: &Term) -> String {
61        match term {
62            Term::Iri(iri) => self.iri(iri),
63            Term::Literal(l) => format!("\"{}\"", l.replace('"', "\\\"")),
64        }
65    }
66
67    fn next(&mut self) -> usize {
68        self.tabstop += 1;
69        self.tabstop
70    }
71
72    /// The predicate of `p`: a choice for an alternative path.
73    fn predicate(&mut self, p: &Property) -> String {
74        if p.is_group() {
75            let n = self.next();
76            let choices: Vec<_> = p
77                .alternatives
78                .iter()
79                .map(|a| escape_choice(&self.iri(a)))
80                .collect();
81            format!("${{{}|{}|}}", n, choices.join(","))
82        } else {
83            escape(&self.iri(&p.path))
84        }
85    }
86
87    /// `predicate value` for each property, values laid out for `indent`.
88    fn lines(&mut self, props: &[Property], indent: &str) -> Vec<String> {
89        props
90            .iter()
91            .map(|p| {
92                let predicate = self.predicate(p);
93                format!("{} {}", predicate, self.value(p, indent))
94            })
95            .collect()
96    }
97
98    fn placeholder(&mut self, name: &str) -> String {
99        let n = self.next();
100        format!("${{{}:{}}}", n, escape_choice(name))
101    }
102
103    /// The value of `p`, for a property written on a line indented by `indent`.
104    fn value(&mut self, p: &Property, indent: &str) -> String {
105        match &p.value {
106            Value::Fixed(t) => escape(&self.term(t)),
107            Value::OneOf(options) if !options.is_empty() => {
108                let n = self.next();
109                let choices: Vec<_> = options
110                    .iter()
111                    .map(|t| escape_choice(&self.term(t)))
112                    .collect();
113                format!("${{{}|{}|}}", n, choices.join(","))
114            }
115            Value::Nested(props) if props.len() == 1 => {
116                format!("[ {} ]", self.lines(props, indent).join(""))
117            }
118            Value::Nested(props) => {
119                // One property per line, indented one level deeper.
120                let inner = format!("{}    ", indent);
121                let lines = self.lines(props, &inner);
122                format!(
123                    "[\n{inner}{}\n{indent}]",
124                    lines.join(&format!(" ;\n{inner}"))
125                )
126            }
127            Value::Iri => format!("<{}>", self.placeholder(&p.name)),
128            Value::Literal(None) => format!("\"{}\"", self.placeholder(&p.name)),
129            Value::Literal(Some(dt)) => match dt.strip_prefix(XSD) {
130                Some("boolean") => {
131                    let n = self.next();
132                    format!("${{{}|true,false|}}", n)
133                }
134                Some("integer" | "int" | "long" | "decimal" | "double" | "float") => {
135                    self.placeholder(&p.name)
136                }
137                _ => format!(
138                    "\"{}\"^^{}",
139                    self.placeholder(&p.name),
140                    escape(&self.iri(dt))
141                ),
142            },
143            _ => self.placeholder(&p.name),
144        }
145    }
146}
147
148/// Snippet text for `props`: one `predicate value` per line, separated by `;`,
149/// with continuation lines indented by `indent`.
150pub fn render(props: &[Property], prefixes: &Prefixes, indent: &str) -> String {
151    let mut r = Renderer {
152        prefixes,
153        tabstop: 0,
154    };
155    let lines = r.lines(props, indent);
156    let mut out = lines.join(&format!(" ;\n{}", indent));
157    out.push_str("$0");
158    out
159}
160
161fn documentation(props: &[Property], prefixes: &Prefixes, preview: &str) -> String {
162    let r = Renderer {
163        prefixes,
164        tabstop: 0,
165    };
166    let mut md = String::new();
167    for p in props {
168        let names: Vec<_> = if p.is_group() {
169            p.alternatives
170                .iter()
171                .map(|a| format!("`{}`", r.iri(a)))
172                .collect()
173        } else {
174            vec![format!("`{}`", r.iri(&p.path))]
175        };
176        md.push_str(&format!(
177            "- {}{}",
178            names.join(" or "),
179            if p.required { " (required)" } else { "" }
180        ));
181        if let Some(d) = &p.description {
182            md.push_str(&format!(": {}", d));
183        }
184        md.push('\n');
185    }
186    md.push_str(&format!("\n```turtle\n{}\n```", preview));
187    md
188}
189
190/// Strip snippet syntax to show a template as plain text.
191fn plain(snippet: &str) -> String {
192    let mut out = String::new();
193    let mut chars = snippet.chars().peekable();
194    while let Some(c) = chars.next() {
195        match c {
196            '\\' => out.extend(chars.next()),
197            '$' if chars.peek() == Some(&'{') => {
198                chars.next();
199                let mut body = String::new();
200                let mut depth = 1;
201                while let Some(c) = chars.next() {
202                    match c {
203                        '\\' => body.extend(chars.next()),
204                        '{' => {
205                            depth += 1;
206                            body.push(c)
207                        }
208                        '}' => {
209                            depth -= 1;
210                            if depth == 0 {
211                                break;
212                            }
213                            body.push(c)
214                        }
215                        _ => body.push(c),
216                    }
217                }
218                let body = body.trim_start_matches(|c: char| c.is_ascii_digit());
219                if let Some(name) = body.strip_prefix(':') {
220                    out.push_str(name);
221                } else if let Some(choices) = body.strip_prefix('|') {
222                    out.push_str(
223                        choices
224                            .trim_end_matches('|')
225                            .split(',')
226                            .next()
227                            .unwrap_or(""),
228                    );
229                }
230            }
231            '$' if chars.peek() == Some(&'0') => {
232                chars.next();
233            }
234            _ => out.push(c),
235        }
236    }
237    out
238}
239
240// ─── Completion system ───────────────────────────────────────────────────────
241
242/// Indentation for continuation lines of a template inserted at `at`.
243fn indentation(rope: &RopeC, at: Position) -> String {
244    let line = rope.0.line_str(at.line as usize).unwrap_or_default();
245    let leading: String = line
246        .chars()
247        .take_while(|c| *c == ' ' || *c == '\t')
248        .collect();
249    let before: String = line.chars().take(at.character as usize).collect();
250    if before.trim().is_empty() {
251        leading
252    } else {
253        format!("{}    ", leading)
254    }
255}
256
257/// Completion system offering "required" and "all properties" templates from
258/// the SHACL shapes that apply to the subject at the cursor.
259pub fn complete_shape_templates(
260    mut query: Query<(
261        &CursorContext,
262        &Prefixes,
263        &Triples,
264        &Label,
265        &DocumentLinks,
266        &RopeC,
267        &DynLang,
268        &mut CompletionRequest,
269    )>,
270    shapes: ShapeDocs,
271    mut cache: Local<ShapeCache>,
272    hierarchy: Res<TypeHierarchy>,
273    config: Res<ServerConfig>,
274) {
275    let local = &config.config.local;
276    if local.is_disabled(Disabled::CompletionShapeTemplate) || local.is_disabled(Disabled::Shapes) {
277        return;
278    }
279
280    for (cursor, prefixes, triples, label, links, rope, lang, mut request) in &mut query {
281        if !lang.shape_templates() || !cursor.at_predicate() {
282            continue;
283        }
284        let Some(subject) = cursor.subject.as_ref() else {
285            continue;
286        };
287
288        let (docs, _) = visible_shapes(&shapes, label, links);
289        if docs.is_empty() {
290            continue;
291        }
292        let graph = cache.graph(docs);
293        let focus = Focus::new(subject, &triples.0, &hierarchy);
294        let all = missing_properties(&graph, &focus);
295        if all.is_empty() {
296            continue;
297        }
298        let required: Vec<_> = all.iter().filter(|p| p.required).cloned().collect();
299
300        let range = cursor.range;
301        let indent = indentation(rope, range.start);
302
303        let mut offer = |props: &[Property], label: &str, sort: &str| {
304            let snippet = render(props, prefixes, &indent);
305            let preview = plain(&snippet);
306            let names: Vec<_> = props.iter().map(|p| p.name.as_str()).collect();
307            request.push(
308                SimpleCompletion::new(
309                    CompletionItemKind::SNIPPET,
310                    label.to_string(),
311                    TextEdit {
312                        range,
313                        new_text: cursor.spaced(&snippet),
314                    },
315                )
316                .as_snippet()
317                .label_description(names.join(", "))
318                .documentation(documentation(props, prefixes, &preview))
319                .sort_text(sort)
320                // Clients filter on the typed word; keep the template visible.
321                .filter_text(format!("{}{}", cursor.typed, label)),
322            );
323        };
324
325        if !required.is_empty() {
326            offer(&required, "shape template: required properties", "00");
327        }
328        if all.len() > required.len() {
329            offer(&all, "shape template: all properties", "01");
330        }
331    }
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337
338    #[test]
339    fn plain_strips_snippet_syntax() {
340        assert_eq!(
341            plain("ex:a ${1:name} ;\n  ex:b ${2|ex:x,ex:y|} ;\n  ex:c \"\\$5\"$0"),
342            "ex:a name ;\n  ex:b ex:x ;\n  ex:c \"$5\""
343        );
344    }
345
346    #[test]
347    fn escapes_snippet_specials() {
348        assert_eq!(escape("a$b}c\\"), "a\\$b\\}c\\\\");
349        assert_eq!(escape_choice("a,b|c"), "a\\,b\\|c");
350    }
351
352    #[test]
353    fn local_names() {
354        assert_eq!(
355            local_name("http://w3id.org/rml/logicalSource"),
356            "logicalSource"
357        );
358        assert_eq!(local_name("http://ex.test/onto#name"), "name");
359    }
360}