lsp_core/systems/
properties.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
use std::borrow::Cow;

use bevy_ecs::prelude::*;
use completion::{CompletionRequest, SimpleCompletion};
use hover::HoverRequest;
use lsp_types::{CompletionItemKind, TextEdit};
use sophia_api::{
    ns::rdfs,
    prelude::{Any, Dataset},
    quad::Quad,
    term::Term,
};
use systems::OntologyExtractor;
use tracing::{debug, info, instrument};

use crate::{
    prelude::*,
    util::{ns::*, triple::MyTerm},
};

pub struct DefinedClass {
    pub term: MyTerm<'static>,
    pub label: String,
    pub comment: String,
    pub reason: &'static str,
}

fn derive_class(
    subject: <MyTerm<'_> as Term>::BorrowTerm<'_>,
    triples: &Triples,
    source: &'static str,
) -> Option<DefinedClass> {
    let label = triples
        .object([subject], [rdfs::label])?
        .to_owned()
        .as_str()
        .to_string();
    let comment = triples
        .object([subject], [rdfs::comment])?
        .to_owned()
        .as_str()
        .to_string();
    Some(DefinedClass {
        label,
        comment,
        term: subject.to_owned(),
        reason: source,
    })
}

pub fn derive_classes(
    query: Query<(Entity, &Triples, &Label), (Changed<Triples>, Without<Dirty>)>,
    mut commands: Commands,
    extractor: Res<OntologyExtractor>,
) {
    for (e, triples, label) in &query {
        let classes: Vec<_> = triples
            .0
            .quads_matching(Any, [rdf::type_], extractor.classes(), Any)
            .flatten()
            .flat_map(|x| derive_class(x.s(), &triples, "owl_class"))
            .collect();

        info!(
            "({} classes) Found {} classes for {} ({} triples)",
            extractor.classes().len(),
            classes.len(),
            label.0,
            triples.0.len()
        );
        commands.entity(e).insert(Wrapped(classes));
    }
}

#[instrument(skip(query, other))]
pub fn complete_class(
    mut query: Query<(
        &TokenComponent,
        &TripleComponent,
        &Prefixes,
        &DocumentLinks,
        &Label,
        &mut CompletionRequest,
    )>,
    other: Query<(&Label, &Wrapped<Vec<DefinedClass>>)>,
) {
    for (token, triple, prefixes, links, this_label, mut request) in &mut query {
        if triple.triple.predicate.value == "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"
            && triple.target == TripleTarget::Object
        {
            for (label, classes) in &other {
                // Check if this thing is actually linked
                if links
                    .iter()
                    .find(|link| link.0.as_str().starts_with(label.0.as_str()))
                    .is_none()
                    && label.0 != this_label.0
                {
                    info!(
                        "Not looking for defined classes in {} (not linked)",
                        label.0
                    );
                    continue;
                }
                info!("Looking for defined classes in {}", label.0);

                for class in classes.0.iter() {
                    let to_beat = prefixes
                        .shorten(&class.term.value)
                        .map(|x| Cow::Owned(x))
                        .unwrap_or(class.term.value.clone());

                    if to_beat.starts_with(&token.text) {
                        request.push(
                            SimpleCompletion::new(
                                CompletionItemKind::CLASS,
                                format!("{}", to_beat),
                                TextEdit {
                                    range: token.range.clone(),
                                    new_text: to_beat.to_string(),
                                },
                            )
                            .documentation(&class.comment),
                        );
                    }
                }
            }
        }
    }
}

pub fn hover_class(
    mut query: Query<(
        &TokenComponent,
        &Prefixes,
        &DocumentLinks,
        &mut HoverRequest,
    )>,
    other: Query<(&Label, &Wrapped<Vec<DefinedClass>>)>,
) {
    for (token, prefixes, links, mut request) in &mut query {
        if let Some(target) = prefixes.expand(token.token.value()) {
            for (label, classes) in &other {
                // Check if this thing is actually linked
                if links.iter().find(|link| link.0 == label.0).is_none() {
                    continue;
                }

                for c in classes.iter().filter(|c| c.term.value == target) {
                    request.0.push(format!("{}: {}", c.label, c.comment));
                }
            }
        }
    }
}

pub struct DefinedProperty {
    pub predicate: MyTerm<'static>,
    pub comment: String,
    pub label: String,
    pub range: Vec<String>,
    pub domain: Vec<String>,
    pub reason: &'static str,
}

fn derive_property(
    subject: <MyTerm<'_> as Term>::BorrowTerm<'_>,
    triples: &Triples,
    source: &'static str,
) -> Option<DefinedProperty> {
    let label = triples
        .object([subject], [rdfs::label])?
        .to_owned()
        .as_str()
        .to_string();
    let comment = triples
        .object([subject], [rdfs::comment])?
        .to_owned()
        .as_str()
        .to_string();
    let domain: Vec<_> = triples
        .objects([subject], [rdfs::domain])
        .map(|x| x.as_str().to_string())
        .collect();

    let range: Vec<_> = triples
        .objects([subject], [rdfs::range])
        .map(|x| x.as_str().to_string())
        .collect();

    Some(DefinedProperty {
        predicate: subject.to_owned(),
        range,
        domain,
        label,
        comment,
        reason: source,
    })
}

pub fn derive_properties(
    query: Query<(Entity, &Triples, &Label), (Changed<Triples>, Without<Dirty>)>,
    mut commands: Commands,
    extractor: Res<OntologyExtractor>,
) {
    for (e, triples, label) in &query {
        let classes: Vec<_> = triples
            .0
            .quads_matching(Any, [rdf::type_], extractor.properties(), Any)
            .flatten()
            .flat_map(|x| derive_property(x.s(), &triples, "owl_property"))
            .collect();

        info!(
            "({} properties) Found {} properties for {} ({} triples)",
            extractor.properties().len(),
            classes.len(),
            label.0.as_str(),
            triples.0.len()
        );
        commands.entity(e).insert(Wrapped(classes));
    }
}

#[instrument(skip(query, other, hierarchy))]
pub fn complete_properties(
    mut query: Query<(
        &TokenComponent,
        &TripleComponent,
        &Prefixes,
        &DocumentLinks,
        &Label,
        &Types,
        &mut CompletionRequest,
    )>,
    other: Query<(&Label, &Wrapped<Vec<DefinedProperty>>)>,
    hierarchy: Res<TypeHierarchy<'static>>,
) {
    debug!("Complete properties");
    for (token, triple, prefixes, links, this_label, types, mut request) in &mut query {
        debug!("target {:?} text {}", triple.target, token.text);
        if triple.target == TripleTarget::Predicate {
            let tts = types.get(&triple.triple.subject.value);
            for (label, properties) in &other {
                // Check if this thing is actually linked
                if links
                    .iter()
                    .find(|link| link.0.as_str().starts_with(label.0.as_str()))
                    .is_none()
                    && label.0 != this_label.0
                {
                    continue;
                }

                for class in properties.0.iter() {
                    let to_beat = prefixes
                        .shorten(&class.predicate.value)
                        .map(|x| Cow::Owned(x))
                        .unwrap_or(class.predicate.value.clone());

                    debug!(
                        "{} starts with {} = {}",
                        to_beat,
                        token.text,
                        to_beat.starts_with(&token.text)
                    );

                    if to_beat.starts_with(&token.text) {
                        let correct_domain = class.domain.iter().any(|domain| {
                            if let Some(domain_id) = hierarchy.get_id_ref(&domain) {
                                if let Some(tts) = tts {
                                    tts.iter().any(|tt| *tt == domain_id)
                                } else {
                                    false
                                }
                            } else {
                                false
                            }
                        });

                        let mut completion = SimpleCompletion::new(
                            CompletionItemKind::PROPERTY,
                            format!("{}", to_beat),
                            TextEdit {
                                range: token.range.clone(),
                                new_text: to_beat.to_string(),
                            },
                        )
                        .label_description(&class.comment);

                        if correct_domain {
                            completion.kind = CompletionItemKind::FIELD;
                            debug!("Property has correct domain {}", to_beat);
                            request.push(completion.sort_text("1"));
                        } else {
                            request.push(completion);
                        }
                    }
                }
            }
        }
    }
}

#[instrument(skip(query, other))]
pub fn hover_property(
    mut query: Query<(
        &TokenComponent,
        &Prefixes,
        &DocumentLinks,
        &mut HoverRequest,
    )>,
    other: Query<(&Label, Option<&Prefixes>, &Wrapped<Vec<DefinedProperty>>)>,
) {
    for (token, prefixes, links, mut request) in &mut query {
        if let Some(target) = prefixes.expand(token.token.value()) {
            for (label, p2, classes) in &other {
                // Check if this thing is actually linked
                if links.iter().find(|link| link.0 == label.0).is_none() {
                    continue;
                }

                let shorten = |from: &str| {
                    if let Some(x) = prefixes.shorten(from) {
                        return Some(x);
                    }

                    if let Some(p) = p2 {
                        return p.shorten(from);
                    }

                    None
                };

                for c in classes.iter().filter(|c| c.predicate.value == target) {
                    request.0.push(format!("{}: {}", c.label, c.comment));
                    for r in &c.range {
                        let range = shorten(&r);
                        request.0.push(format!(
                            "Range {}",
                            range.as_ref().map(|x| x.as_str()).unwrap_or(r.as_str())
                        ));
                    }

                    for d in &c.domain {
                        let domain = shorten(&d);
                        request.0.push(format!(
                            "Domain {}",
                            domain.as_ref().map(|x| x.as_str()).unwrap_or(d.as_str())
                        ));
                    }
                }
            }
        }
    }
}