1use std::{
2 borrow::{Borrow, Cow},
3 hash::Hash,
4 sync::Arc,
5};
6
7use bevy_ecs::prelude::*;
8use derive_more::{AsMut, AsRef, Deref, DerefMut};
9use sophia_api::{
10 prelude::{Any, Dataset},
11 quad::Quad,
12 term::{matcher::TermMatcher, BnodeId, GraphName, IriRef, Term, TermKind, VarName},
13 MownStr,
14};
15use tracing::{debug, instrument};
16
17use crate::{
18 components::{PositionComponent, RopeC},
19 prelude::DynLang,
20 util::{
21 ns::{owl, rdfs},
22 position_to_offset,
23 },
24};
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum TripleTarget {
30 Subject,
31 Predicate,
32 Object,
33 Graph,
34}
35
36#[derive(Component, Debug)]
38pub struct TripleComponent {
39 pub triple: MyQuad<'static>,
40 pub target: TripleTarget,
41}
42
43impl TripleComponent {
44 pub fn kind(&self) -> TermKind {
45 let target = match self.target {
46 TripleTarget::Subject => self.triple.s().kind(),
47 TripleTarget::Predicate => self.triple.p().kind(),
48 TripleTarget::Object => self.triple.o().kind(),
49 TripleTarget::Graph => self
50 .triple
51 .g()
52 .map(|x| x.kind())
53 .unwrap_or(sophia_api::term::TermKind::Triple),
54 };
55 target
56 }
57
58 pub fn term(&self) -> Option<&MyTerm<'static>> {
59 let target = match self.target {
60 TripleTarget::Subject => self.triple.s(),
61 TripleTarget::Predicate => self.triple.p(),
62 TripleTarget::Object => self.triple.o(),
63 TripleTarget::Graph => return None,
64 };
65 Some(target)
66 }
67}
68
69#[derive(Component, AsRef, Deref, AsMut, DerefMut, Debug)]
73pub struct Triples(pub Arc<Vec<MyQuad<'static>>>);
74
75impl Triples {
76 pub fn object<'s, S, P>(&'s self, subj: S, pred: P) -> Option<&'s MyTerm<'s>>
77 where
78 S: TermMatcher + 's,
79 P: TermMatcher + 's,
80 {
81 self.0
82 .quads_matching(
83 subj,
84 pred,
85 sophia_api::prelude::Any,
86 sophia_api::prelude::Any,
87 )
88 .flatten()
89 .next()
90 .map(|x| x.o())
91 }
92
93 pub fn objects<'s, S, P>(&'s self, subj: S, pred: P) -> impl Iterator<Item = &'s MyTerm<'s>>
94 where
95 S: TermMatcher + 's,
96 P: TermMatcher + 's,
97 {
98 self.0
99 .quads_matching(
100 subj,
101 pred,
102 sophia_api::prelude::Any,
103 sophia_api::prelude::Any,
104 )
105 .flatten()
106 .map(|x| x.o())
107 }
108}
109
110#[instrument(skip(query, commands))]
111pub fn get_current_triple(
112 query: Query<
113 (Entity, &PositionComponent, &Triples, &RopeC, &DynLang),
114 Changed<PositionComponent>,
115 >,
116 mut commands: Commands,
117) {
118 for (e, position, triples, rope, lang) in &query {
119 commands.entity(e).remove::<TripleComponent>();
120
121 let Some(offset) = position_to_offset(position.0, &rope.0) else {
122 debug!("Couldn't transform to an offset");
123 continue;
124 };
125
126 if let Some((target, _, t)) = triples
134 .iter()
135 .flat_map(|t| {
136 [
137 (TripleTarget::Subject, &t.subject, t),
138 (TripleTarget::Predicate, &t.predicate, t),
139 (TripleTarget::Object, &t.object, t),
140 ]
141 })
142 .filter(|(_, term, _)| {
143 let span = &term.span;
144 span.contains(&offset) || (span.end == offset && span.start < span.end)
145 })
146 .min_by_key(|(_, term, _)| {
147 (
148 term.span.start != offset,
149 term.span.end - term.span.start,
150 term.ty == Some(TermKind::BlankNode),
151 )
152 })
153 {
154 tracing::debug!(
155 "Narrowest triple at {} Component {:?} {} {:?} {} {:?} {} {:?} .",
156 offset,
157 target,
158 t.subject,
159 t.subject.span,
160 t.predicate,
161 t.predicate.span,
162 t.object,
163 t.object.span
164 );
165 commands.entity(e).insert(TripleComponent {
166 triple: t.clone(),
167 target,
168 });
169 } else {
170 let found = triples
171 .0
172 .iter()
173 .filter(|triple| triple.span.start <= offset && offset <= triple.span.end)
174 .min_by_key(|x| x.span.end - x.span.start);
175
176 if let Some(t) = found.or_else(|| {
181 triples
182 .0
183 .iter()
184 .filter(|triple| triple.span.end <= offset)
185 .max_by_key(|x| x.span.end)
186 }) {
187 let object_written = t.object.span.start < t.object.span.end;
188 let predicate_written = t.predicate.span.start < t.predicate.span.end;
189 let target = if object_written && offset > t.object.span.end {
190 TripleTarget::Predicate
192 } else if predicate_written && offset >= t.predicate.span.end {
193 TripleTarget::Object
194 } else if offset >= t.subject.span.end {
195 TripleTarget::Predicate
196 } else {
197 lang.default_position()
198 };
199 tracing::debug!(
200 "Triple at {} Component {:?} {} {:?} {} {:?} {} {:?} .",
201 offset,
202 target,
203 t.subject,
204 t.subject.span,
205 t.predicate,
206 t.predicate.span,
207 t.object,
208 t.object.span
209 );
210 commands.entity(e).insert(TripleComponent {
211 triple: t.clone(),
212 target,
213 });
214 } else {
215 commands.entity(e).remove::<TripleComponent>();
216 debug!("No current triple found");
217 }
218 }
219 }
220}
221
222#[derive(Debug, Clone)]
223pub struct MyQuad<'a> {
224 pub subject: MyTerm<'a>,
225 pub predicate: MyTerm<'a>,
226 pub object: MyTerm<'a>,
227 pub span: std::ops::Range<usize>,
228}
229impl<'b, 'a> TryFrom<&'b MyQuad<'a>> for oxigraph::model::Quad {
230 type Error = ();
231
232 fn try_from(value: &'b MyQuad<'a>) -> std::result::Result<Self, Self::Error> {
233 let subject = oxigraph::model::Term::try_from(&value.subject)?;
234 let predicate = oxigraph::model::Term::try_from(&value.predicate)?;
235 let object = oxigraph::model::Term::try_from(&value.object)?;
236
237 let subject = oxigraph::model::NamedOrBlankNode::try_from(subject).map_err(|_| ())?;
238 let predicate = oxigraph::model::NamedNode::try_from(predicate).map_err(|_| ())?;
239
240 Ok(oxigraph::model::Quad::new(
241 subject,
242 predicate,
243 object,
244 oxigraph::model::GraphName::default(),
245 ))
246 }
247}
248
249impl<'a> MyQuad<'a> {
250 pub fn into_oxi_graph(
253 &self,
254 graph: impl TryInto<oxigraph::model::Term>,
255 ) -> Option<oxigraph::model::Quad> {
256 let graph = graph.try_into().ok()?;
257 let graph = oxigraph::model::NamedOrBlankNode::try_from(graph).ok()?;
258 let graph = oxigraph::model::GraphName::from(graph);
259
260 self.into_oxi(Some(graph))
261 }
262
263 pub fn into_oxi(
266 &self,
267 graph: Option<oxigraph::model::GraphName>,
268 ) -> Option<oxigraph::model::Quad> {
269 let subject = oxigraph::model::Term::try_from(&self.subject).ok()?;
270 let predicate = oxigraph::model::Term::try_from(&self.predicate).ok()?;
271 let object = oxigraph::model::Term::try_from(&self.object).ok()?;
272 let graph = graph.unwrap_or_default();
273
274 let subject = oxigraph::model::NamedOrBlankNode::try_from(subject).ok()?;
275 let predicate = oxigraph::model::NamedNode::try_from(predicate).ok()?;
276
277 Some(oxigraph::model::Quad::new(
278 subject, predicate, object, graph,
279 ))
280 }
281}
282
283impl<'a> std::fmt::Display for MyQuad<'a> {
284 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
285 write!(
286 f,
287 "{} {} {}. # {:?}",
288 self.subject, self.predicate, self.object, self.span
289 )
290 }
291}
292
293impl<'a> MyQuad<'a> {
294 pub fn to_owned(&self) -> MyQuad<'static> {
295 MyQuad {
296 subject: self.subject.to_owned(),
297 predicate: self.predicate.to_owned(),
298 object: self.object.to_owned(),
299 span: self.span.clone(),
300 }
301 }
302}
303impl<'a, 'b> TryFrom<&'b MyTerm<'a>> for oxigraph::model::Term {
304 type Error = ();
305
306 fn try_from(value: &'b MyTerm<'a>) -> std::result::Result<Self, Self::Error> {
307 use oxigraph::{model as M, model::Term as T};
308 let output = match &value.ty {
309 Some(TermKind::Iri) => T::NamedNode(M::NamedNode::new(value.as_str()).map_err(|_| ())?),
310 Some(TermKind::Literal) => {
311 if let Some(lang) = value.language_tag() {
315 T::Literal(
316 M::Literal::new_language_tagged_literal(
317 value.value.as_ref(),
318 lang.as_str(),
319 )
320 .map_err(|_| ())?,
321 )
322 } else if let Some(dt) = value.datatype() {
323 let dt = M::NamedNode::new(dt.as_str()).map_err(|_| ())?;
324 T::Literal(M::Literal::new_typed_literal(value.value.as_ref(), dt))
325 } else {
326 T::Literal(M::Literal::new_simple_literal(value.value.as_ref()))
327 }
328 }
329 Some(TermKind::BlankNode) => {
330 T::BlankNode(M::BlankNode::new(value.value.as_ref()).map_err(|_| ())?)
331 }
332 _ => {
333 return Err(());
334 }
335 };
336 Ok(output)
337 }
338}
339
340impl<'a> Quad for MyQuad<'a> {
341 type Term = MyTerm<'a>;
342
343 fn s(&self) -> sophia_api::quad::QBorrowTerm<'_, Self> {
344 self.subject.borrow_term()
345 }
346
347 fn p(&self) -> sophia_api::quad::QBorrowTerm<'_, Self> {
348 self.predicate.borrow_term()
349 }
350
351 fn o(&self) -> sophia_api::quad::QBorrowTerm<'_, Self> {
352 self.object.borrow_term()
353 }
354
355 fn g(&self) -> GraphName<sophia_api::quad::QBorrowTerm<'_, Self>> {
356 None
357 }
358
359 fn to_spog(self) -> sophia_api::quad::Spog<Self::Term> {
360 ([self.subject, self.predicate, self.object], None)
361 }
362}
363#[derive(Debug, Clone, PartialEq, Hash, Eq)]
366pub enum TermContext<'a> {
367 None,
368 DataType(Cow<'a, str>),
369 LangTag(Cow<'a, str>),
370}
371impl<'a> TermContext<'a> {
372 pub fn to_owned(&self) -> TermContext<'static> {
373 match self {
374 TermContext::None => TermContext::None,
375 TermContext::DataType(cow) => TermContext::DataType(Cow::Owned(cow.to_string())),
376 TermContext::LangTag(cow) => TermContext::LangTag(Cow::Owned(cow.to_string())),
377 }
378 }
379}
380
381#[derive(Debug, Clone, Eq)]
382pub struct MyTerm<'a> {
383 pub value: Cow<'a, str>,
384 pub ty: Option<TermKind>,
385 pub span: std::ops::Range<usize>,
386 pub context: TermContext<'a>,
387}
388impl<'a> PartialOrd for MyTerm<'a> {
389 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
390 Some(Ord::cmp(self, other))
391 }
392}
393impl<'a> Ord for MyTerm<'a> {
394 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
395 match self.value.cmp(&other.value) {
396 core::cmp::Ordering::Equal => {}
397 ord => return ord,
398 }
399 self.ty.cmp(&other.ty)
400 }
401}
402
403impl Hash for MyTerm<'_> {
404 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
405 self.value.hash(state);
407 self.ty.hash(state);
408 }
409}
410
411impl PartialEq for MyTerm<'_> {
412 fn eq(&self, other: &Self) -> bool {
413 other.value == self.value && other.ty == self.ty
415 }
416}
417
418impl<'a> std::fmt::Display for MyTerm<'a> {
419 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
420 match self.kind() {
421 TermKind::Iri => write!(f, "<{}>", self.value),
422 TermKind::Literal => write!(f, "\"{}\"", self.value),
423 TermKind::BlankNode => write!(f, "_:{}", self.value),
424 TermKind::Triple => write!(f, "<{}>", self.value),
425 TermKind::Variable => write!(f, "?{}", self.value),
426 }
427 }
428}
429
430impl<'a> MyTerm<'a> {
431 pub fn to_owned(&self) -> MyTerm<'static> {
432 let value = Cow::Owned(self.value.to_string());
433 MyTerm {
434 value,
435 ty: self.ty,
436 span: self.span.clone(),
437 context: self.context.to_owned(),
438 }
439 }
440 pub fn variable<T: Into<Cow<'a, str>>>(value: T, span: std::ops::Range<usize>) -> Self {
441 Self {
442 value: value.into(),
443 ty: TermKind::Variable.into(),
444 span,
445 context: TermContext::None,
446 }
447 }
448 pub fn named_node<T: Into<Cow<'a, str>>>(value: T, span: std::ops::Range<usize>) -> Self {
449 Self {
450 value: value.into(),
451 ty: TermKind::Iri.into(),
452 span,
453 context: TermContext::None,
454 }
455 }
456 pub fn blank_node<T: Into<Cow<'a, str>>>(value: T, span: std::ops::Range<usize>) -> Self {
457 Self {
458 value: value.into(),
459 ty: TermKind::BlankNode.into(),
460 span,
461 context: TermContext::None,
462 }
463 }
464 pub fn literal<T: Into<Cow<'a, str>>>(
465 value: T,
466 span: std::ops::Range<usize>,
467 context: TermContext<'a>,
468 ) -> Self {
469 Self {
470 value: value.into(),
471 ty: TermKind::Literal.into(),
472 span,
473 context,
474 }
475 }
476
477 pub fn invalid(span: std::ops::Range<usize>) -> Self {
478 Self {
479 value: Cow::default(),
480 ty: TermKind::Iri.into(),
481 span,
482
483 context: TermContext::None,
484 }
485 }
486
487 pub fn as_str(&'a self) -> &'a str {
488 &self.value
489 }
490}
491
492impl<'a> Term for MyTerm<'a> {
493 type BorrowTerm<'x>
494 = &'x Self
495 where
496 Self: 'x;
497
498 fn kind(&self) -> sophia_api::term::TermKind {
499 self.ty.unwrap_or(TermKind::Triple)
500 }
501
502 fn borrow_term(&self) -> Self::BorrowTerm<'_> {
503 self
504 }
505
506 fn iri(&self) -> Option<sophia_api::term::IriRef<sophia_api::MownStr<'_>>> {
507 self.is_iri()
508 .then(|| IriRef::new_unchecked(MownStr::from_ref(&self.value)))
509 }
510
511 fn bnode_id(&self) -> Option<sophia_api::term::BnodeId<sophia_api::MownStr<'_>>> {
512 self.is_blank_node()
513 .then(|| BnodeId::new_unchecked(MownStr::from_ref(&self.value)))
514 }
515
516 fn lexical_form(&self) -> Option<sophia_api::MownStr<'_>> {
517 self.is_literal().then(|| MownStr::from_ref(&self.value))
518 }
519
520 fn datatype(&self) -> Option<sophia_api::term::IriRef<sophia_api::MownStr<'_>>> {
521 if !self.is_literal() {
522 return None;
523 }
524 let dt: &str = match &self.context {
525 TermContext::DataType(dt) => dt,
526 TermContext::LangTag(_) => "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString",
527 TermContext::None => "http://www.w3.org/2001/XMLSchema#string",
528 };
529 Some(IriRef::new_unchecked(MownStr::from_ref(dt)))
530 }
531
532 fn language_tag(&self) -> Option<sophia_api::term::LanguageTag<sophia_api::MownStr<'_>>> {
533 match &self.context {
534 TermContext::LangTag(tag) if self.is_literal() => Some(
535 sophia_api::term::LanguageTag::new_unchecked(MownStr::from_ref(tag)),
536 ),
537 _ => None,
538 }
539 }
540
541 fn variable(&self) -> Option<sophia_api::term::VarName<sophia_api::MownStr<'_>>> {
542 self.is_variable()
543 .then(|| VarName::new_unchecked(MownStr::from_ref(&self.value)))
544 }
545
546 fn triple(&self) -> Option<[Self::BorrowTerm<'_>; 3]> {
547 panic!("MyTerm does not supported triples")
548 }
549
550 fn to_triple(self) -> Option<[Self; 3]>
551 where
552 Self: Sized,
553 {
554 panic!("MyTerm does not supported triples")
555 }
556}
557
558impl<'a> Borrow<str> for &MyTerm<'a> {
559 fn borrow(&self) -> &str {
560 &self.value
561 }
562}
563
564#[derive(Default, Debug)]
565pub struct Triples2<'a> {
566 pub base_url: String,
567 pub triples: Vec<MyQuad<'a>>,
568 pub base: Option<MyTerm<'a>>,
569}
570
571impl<'a> Triples2<'a> {
572 pub fn to_owned(&self) -> Triples2<'static> {
573 let triples = self.triples.iter().map(|q| q.to_owned()).collect();
574 let base: Option<MyTerm<'static>> = self.base.as_ref().map(|x| x.to_owned());
575
576 Triples2 {
577 base,
578 triples,
579 base_url: self.base_url.clone(),
580 }
581 }
582
583 pub fn imports(&self, cb: impl FnMut(IriRef<MownStr<'_>>)) {
584 if let Some(ref base) = self.base {
585 self.triples
586 .quads_matching([base], [owl::imports], Any, Any)
587 .flatten()
588 .flat_map(|s| s.o().iri())
589 .for_each(cb);
590 }
591 }
592
593 pub fn sub_class_of(&self, mut cb: impl FnMut(IriRef<MownStr<'_>>, IriRef<MownStr<'_>>)) {
594 self.triples
595 .quads_matching(Any, [rdfs::subClassOf], Any, Any)
596 .flatten()
597 .flat_map(|s| match (s.s().iri(), s.o().iri()) {
598 (Some(s), Some(o)) => Some((s, o)),
599 _ => None,
600 })
601 .for_each(|(x, y)| cb(x, y));
602 }
603}
604
605impl<'a> std::ops::Deref for Triples2<'a> {
606 type Target = Vec<MyQuad<'a>>;
607
608 fn deref(&self) -> &Self::Target {
609 &self.triples
610 }
611}
612
613impl<'a> PartialEq for MyQuad<'a> {
614 fn eq(&self, other: &Self) -> bool {
615 self.subject == other.subject
616 && self.predicate == other.predicate
617 && self.object == other.object
618 }
619}