flams_ontology/
lib.rs

1#![recursion_limit = "256"]
2//#![feature(box_patterns)]
3#![cfg_attr(docsrs, feature(doc_auto_cfg))]
4/*#![feature(adt_const_params)]
5
6#[derive(std::marker::ConstParamTy,PartialEq,Eq)]
7pub enum Test {
8    A,
9    B
10}
11
12pub struct Foo<const T:Test>(String);
13*/
14
15use std::borrow::Cow;
16
17use content::{
18    declarations::DeclarationTrait,
19    modules::{Module, Signature},
20    ContentReference, ModuleLike,
21};
22use flams_utils::sourcerefs::{ByteOffset, SourceRange};
23use languages::Language;
24use narration::documents::Document;
25use uris::{DocumentElementURI, DocumentURI, ModuleURI, SymbolURI};
26
27pub mod content;
28pub mod file_states;
29pub mod languages;
30pub mod narration;
31
32#[cfg(feature = "serde")]
33pub mod archive_json;
34pub mod ftml;
35#[cfg(feature = "rdf")]
36pub mod rdf;
37pub mod search;
38pub mod uris;
39
40mod sealed {
41    pub trait Sealed {}
42}
43
44#[cfg(not(feature = "serde"))]
45pub trait CheckingState: sealed::Sealed + std::fmt::Debug {
46    type ModuleLike: std::fmt::Debug;
47    type Module: std::fmt::Debug;
48    type Seq<A: std::fmt::Debug>: std::fmt::Debug;
49    type Decl<D: DeclarationTrait + Resolvable<From = SymbolURI>>: std::fmt::Debug;
50    type Doc: std::fmt::Debug;
51    type Sig: std::fmt::Debug;
52}
53#[cfg(feature = "serde")]
54pub trait CheckingState: sealed::Sealed + std::fmt::Debug {
55    //+serde::Serialize {
56    type ModuleLike: std::fmt::Debug + serde::Serialize;
57    type Module: std::fmt::Debug + serde::Serialize;
58    type Seq<A: std::fmt::Debug + serde::Serialize>: std::fmt::Debug + serde::Serialize;
59    type Decl<D: DeclarationTrait + Resolvable<From = SymbolURI>>: std::fmt::Debug
60        + serde::Serialize;
61    type Doc: std::fmt::Debug + serde::Serialize;
62    type Sig: std::fmt::Debug + serde::Serialize;
63}
64
65#[derive(Debug, Copy, Clone)]
66//#[cfg_attr(feature="serde",derive(serde::Serialize,serde::Deserialize))]
67pub struct Unchecked;
68impl sealed::Sealed for Unchecked {}
69impl CheckingState for Unchecked {
70    type ModuleLike = ModuleURI;
71    type Module = ModuleURI;
72    type Decl<D: DeclarationTrait + Resolvable<From = SymbolURI>> = SymbolURI;
73    #[cfg(feature = "serde")]
74    type Seq<A: std::fmt::Debug + serde::Serialize> = Vec<A>;
75    #[cfg(not(feature = "serde"))]
76    type Seq<A: std::fmt::Debug> = Vec<A>;
77    type Doc = DocumentURI;
78    type Sig = Language;
79}
80#[derive(Debug, Copy, Clone)]
81//#[cfg_attr(feature="serde",derive(serde::Serialize))]
82pub struct Checked;
83impl sealed::Sealed for Checked {}
84impl CheckingState for Checked {
85    type ModuleLike = MaybeResolved<ModuleLike>;
86    type Module = MaybeResolved<Module>;
87    type Decl<D: DeclarationTrait + Resolvable<From = SymbolURI>> =
88        MaybeResolved<ContentReference<D>>;
89    #[cfg(feature = "serde")]
90    type Seq<A: std::fmt::Debug + serde::Serialize> = Box<[A]>;
91    #[cfg(not(feature = "serde"))]
92    type Seq<A: std::fmt::Debug> = Box<[A]>;
93    type Doc = MaybeResolved<Document>;
94    type Sig = MaybeResolved<Signature>;
95}
96
97pub trait Resolvable: std::fmt::Debug {
98    type From: std::fmt::Debug + Clone;
99    fn id(&self) -> Cow<'_, Self::From>;
100}
101
102#[derive(Debug)]
103enum MaybeResolvedI<T: Resolvable> {
104    Resolved(T),
105    Unresolved(T::From),
106}
107
108#[derive(Debug)]
109pub struct MaybeResolved<T: Resolvable> {
110    inner: MaybeResolvedI<T>,
111}
112impl<T: Resolvable> MaybeResolved<T> {
113    #[inline]
114    pub fn id(&self) -> Cow<'_, T::From> {
115        match &self.inner {
116            MaybeResolvedI::Resolved(r) => r.id(),
117            MaybeResolvedI::Unresolved(i) => Cow::Borrowed(i),
118        }
119    }
120    #[inline]
121    pub const fn is_resolved(&self) -> bool {
122        matches!(self.inner, MaybeResolvedI::Resolved(_))
123    }
124    #[inline]
125    pub const fn get(&self) -> Option<&T> {
126        if let MaybeResolvedI::Resolved(i) = &self.inner {
127            Some(i)
128        } else {
129            None
130        }
131    }
132    #[inline]
133    pub const fn unresolved(id: T::From) -> Self {
134        Self {
135            inner: MaybeResolvedI::Unresolved(id),
136        }
137    }
138    #[inline]
139    pub const fn resolved(value: T) -> Self {
140        Self {
141            inner: MaybeResolvedI::Resolved(value),
142        }
143    }
144    #[inline]
145    pub fn resolve(id: T::From, resolve: impl FnOnce(&T::From) -> Option<T>) -> Self {
146        resolve(&id).map_or_else(|| Self::unresolved(id), Self::resolved)
147    }
148}
149
150#[cfg(feature = "serde")]
151mod serde_resolved {
152    use crate::{MaybeResolved, MaybeResolvedI, Resolvable};
153
154    impl<T: Resolvable> serde::Serialize for MaybeResolved<T>
155    where
156        T::From: serde::Serialize,
157    {
158        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
159        where
160            S: serde::Serializer,
161        {
162            match &self.inner {
163                MaybeResolvedI::Unresolved(t) => t.serialize(serializer),
164                MaybeResolvedI::Resolved(s) => {
165                    let id = s.id();
166                    let id = &*id;
167                    id.serialize(serializer)
168                }
169            }
170        }
171    }
172}
173
174#[derive(Copy, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
175#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
176#[cfg_attr(feature = "wasm", derive(tsify_next::Tsify))]
177#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
178pub struct DocumentRange {
179    pub start: usize,
180    pub end: usize,
181}
182impl From<SourceRange<ByteOffset>> for DocumentRange {
183    #[inline]
184    fn from(value: SourceRange<ByteOffset>) -> Self {
185        Self {
186            start: value.start.offset,
187            end: value.end.offset,
188        }
189    }
190}
191impl From<DocumentRange> for SourceRange<ByteOffset> {
192    #[inline]
193    fn from(value: DocumentRange) -> Self {
194        Self {
195            start: ByteOffset {
196                offset: value.start,
197            },
198            end: ByteOffset { offset: value.end },
199        }
200    }
201}
202/*
203pub enum DecodeError {
204    URIParse(URIParseError),
205    Io(flams_utils::binary::DecodeError),
206    UnknownDiscriminant,
207}
208impl From<URIParseError> for DecodeError {
209    #[inline]
210    fn from(value: URIParseError) -> Self {
211        Self::URIParse(value)
212    }
213}
214impl From<flams_utils::binary::DecodeError> for DecodeError {
215    #[inline]
216    fn from(value: flams_utils::binary::DecodeError) -> Self {
217        Self::Io(value)
218    }
219}
220impl From<std::io::Error> for DecodeError {
221    #[inline]
222    fn from(value: std::io::Error) -> Self {
223        Self::Io(value.into())
224    }
225}
226*/
227
228pub mod metatheory {
229    use crate::{
230        languages::Language,
231        uris::{BaseURI, DocumentURI, ModuleURI, SymbolURI},
232    };
233    use lazy_static::lazy_static;
234    lazy_static! {
235        pub static ref DOC_URI: DocumentURI = ((BaseURI::new_unchecked("https://mathhub.info")
236            & "FTML/meta")
237            & ("Metatheory", Language::English))
238            .unwrap_or_else(|_| unreachable!());
239        pub static ref URI: ModuleURI =
240            ((BaseURI::new_unchecked("https://mathhub.info") & "FTML/meta") | "Metatheory")
241                .unwrap_or_else(|_| unreachable!());
242        pub static ref FIELD_PROJECTION: SymbolURI =
243            (URI.clone() | "record field").unwrap_or_else(|_| unreachable!());
244        pub static ref OF_TYPE: SymbolURI =
245            (URI.clone() | "of type").unwrap_or_else(|_| unreachable!());
246        pub static ref SEQUENCE_EXPRESSION: SymbolURI =
247            (URI.clone() | "sequence expression").unwrap_or_else(|_| unreachable!());
248        pub(crate) static ref NOTATION_DUMMY: SymbolURI =
249            (URI.clone() | "notation dummy").unwrap_or_else(|_| unreachable!());
250    }
251}
252
253pub trait LocalBackend {
254    fn get_document(&mut self, uri: &DocumentURI) -> Option<Document>;
255
256    fn get_module(&mut self, uri: &ModuleURI) -> Option<ModuleLike>;
257
258    fn get_declaration<T: DeclarationTrait>(
259        &mut self,
260        uri: &SymbolURI,
261    ) -> Option<ContentReference<T>>;
262}
263
264#[cfg(feature = "serde")]
265pub trait Resourcable: serde::Serialize + for<'a> serde::Deserialize<'a> {}
266
267#[cfg(not(feature = "serde"))]
268pub trait Resourcable {}
269
270impl Resourcable for Box<str> {}
271
272#[derive(Debug, Clone)]
273#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
274#[cfg_attr(feature = "wasm", derive(tsify_next::Tsify))]
275#[cfg_attr(feature = "wasm", tsify(into_wasm_abi, from_wasm_abi))]
276#[cfg_attr(feature = "serde", serde(tag = "type"))]
277pub enum SlideElement {
278    Slide {
279        html: String,
280        uri: DocumentElementURI,
281    },
282    Paragraph {
283        html: String,
284        uri: DocumentElementURI,
285    },
286    Inputref {
287        uri: DocumentURI,
288    },
289    Section {
290        uri: DocumentElementURI,
291        title: Option<String>,
292        children: Vec<SlideElement>,
293    },
294}
295
296macro_rules! serde_impl {
297    (@i_count ) => { 0 };
298    (@i_count $r:ident $($rs:tt)* ) => { 1 + crate::serde_impl!(@i_count $($rs)*) };
299    (@count $($r:ident)*) => { crate::serde_impl!(@i_count $($r)*)};
300
301    (@caseI $f:ident) => {
302        Self::$f
303    };
304    (@caseII $ser:ident $s:ident $idx:literal $f:ident) => {
305        $ser.serialize_unit_variant(stringify!($s),$idx,stringify!($f))
306    };
307    (@caseIII $ser:ident $s:ident $idx:literal $f:ident) => {
308        {$ser.unit_variant()?;Ok(Self::$f)}
309    };
310
311    (@caseI $f:ident($nt:ident)) => {
312        Self::$f($nt)
313    };
314    (@caseII $ser:ident $s:ident $idx:literal $f:ident($nt:ident)) => {
315        $ser.serialize_newtype_variant(stringify!($s),$idx,stringify!($f),$nt)
316    };
317    (@caseIII $ser:ident $s:ident $idx:literal $f:ident($nt:ident)) => {
318        $ser.newtype_variant().map($s::$f)
319    };
320
321    (@caseI $f:ident{ $($n:ident),* }) => {
322        Self::$f{$($n),*}
323    };
324    (@caseII $ser:ident $s:ident $idx:literal $f:ident{ $($n:ident),* }) => {{
325        let mut s = $ser.serialize_struct_variant(stringify!($s),$idx,stringify!($f),
326            crate::serde_impl!(@count $($n)*)
327        )?;
328        $(
329            s.serialize_field(stringify!($n),$n)?;
330        )*
331        s.end()
332    }};
333    (@caseIII $ser:ident $s:ident $idx:literal $f:ident{ $($n:ident),* }) => {{
334        struct SVisitor;
335
336        #[derive(serde::Deserialize)]
337        #[allow(non_camel_case_types)]
338        enum Field { $($n),* }
339        impl<'de> serde::de::Visitor<'de> for SVisitor {
340            type Value = $s<Unchecked>;
341            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
342                formatter.write_str(stringify!($f))
343            }
344            #[allow(unused_assignments)]
345            fn visit_seq<V>(self, mut seq: V) -> Result<$s<Unchecked>, V::Error>
346            where
347                V: serde::de::SeqAccess<'de>,
348            {
349                let mut count = 0;
350                $(
351                    let $n = seq.next_element()?
352                        .ok_or_else(|| serde::de::Error::invalid_length(count, &self))?;
353                    count += 1;
354                )*
355                Ok($s::$f{ $($n),* })
356            }
357            fn visit_map<V>(self, mut map: V) -> Result<$s<Unchecked>, V::Error>
358            where
359                V: serde::de::MapAccess<'de>,
360            {
361                $(
362                    let mut $n = None;
363                )*
364                while let Some(key) = map.next_key()? {
365                    match key {
366                        $(
367                            Field::$n => {
368                                if $n.is_some() {
369                                    return Err(serde::de::Error::duplicate_field(stringify!($n)));
370                                }
371                                $n = Some(map.next_value()?);
372                            }
373                        )*
374                    }
375                }
376                $(
377                    let $n = $n.ok_or_else(|| serde::de::Error::missing_field(stringify!($n)))?;
378                )*
379                Ok($s::$f { $($n),* })
380            }
381        }
382
383        $ser.struct_variant(&[ $(stringify!($n)),* ],SVisitor)
384    }};
385
386    ($(mod $m:ident = )? struct $s:ident[$($f:ident),+] ) => {crate::serde_impl!{$(mod $m = )? $s : slf
387        s => {
388            let mut s = s.serialize_struct(
389                stringify!($s),
390                crate::serde_impl!(@count $($f)*)
391            )?;
392            $(
393                s.serialize_field(stringify!($f),&slf.$f)?;
394            )*
395            s.end()
396        }
397        d => {
398            #[derive(serde::Deserialize)]
399            #[allow(non_camel_case_types)]
400            enum Field { $($f),* }
401            struct Visitor;
402            impl<'de> serde::de::Visitor<'de> for Visitor {
403                type Value = $s<Unchecked>;
404                fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
405                    formatter.write_str(stringify!($s))
406                }
407                #[allow(unused_assignments)]
408                fn visit_seq<V>(self, mut seq: V) -> Result<$s<Unchecked>, V::Error>
409                where
410                    V: serde::de::SeqAccess<'de>,
411                {
412                    let mut count = 0;
413                    $(
414                        let $f = seq.next_element()?
415                            .ok_or_else(|| serde::de::Error::invalid_length(count, &self))?;
416                        count += 1;
417                    )*
418                    Ok($s{ $($f),* })
419                }
420                fn visit_map<V>(self, mut map: V) -> Result<$s<Unchecked>, V::Error>
421                where
422                    V: serde::de::MapAccess<'de>,
423                {
424                    $(
425                        let mut $f = None;
426                    )*
427                    while let Some(key) = map.next_key()? {
428                        match key {
429                            $(
430                                Field::$f => {
431                                    if $f.is_some() {
432                                        return Err(serde::de::Error::duplicate_field(stringify!($f)));
433                                    }
434                                    $f = Some(map.next_value()?);
435                                }
436                            )*
437                        }
438                    }
439                    $(
440                        let $f = $f.ok_or_else(|| serde::de::Error::missing_field(stringify!($f)))?;
441                    )*
442                    Ok($s { $($f),* })
443                }
444            }
445            d.deserialize_struct(stringify!($s),&[$(stringify!($f)),*],Visitor)
446
447        }
448    }};
449
450    ($(mod $m:ident = )? enum $s:ident{ $( {$idx:literal = $f:ident $($spec:tt)*} )+ } ) => {
451        crate::serde_impl!{$(mod $m = )? $s : slf
452            ser => {
453                match slf {
454                    $(
455                        crate::serde_impl!(@caseI $f $($spec)*) =>
456                        crate::serde_impl!{@caseII ser $s $idx $f $($spec)* }
457                    ),*
458                }
459            }
460            de => {
461                #[derive(serde::Deserialize)]
462                enum Fields {
463                    $(
464                        $f = $idx
465                    ),*
466                }
467                struct Visitor;
468                impl<'de> serde::de::Visitor<'de> for Visitor {
469                    type Value = $s<Unchecked>;
470                    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
471                        formatter.write_str(stringify!($s))
472                    }
473                    fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
474                    where
475                        A: EnumAccess<'de>,
476                    {
477                        let (v,var) = data.variant()?;
478                        match v {
479                            $(
480                                Fields::$f => crate::serde_impl!{@caseIII var $s $idx $f $($spec)* },
481                            )*
482                            //s => Err(A::Error::unknown_variant(s, &[ $(stringify!($f)),* ]))
483                        }
484
485                    }
486
487                }
488
489                de.deserialize_enum(
490                    stringify!($s),
491                    &[ $( stringify!($f) ),* ],
492                    Visitor
493                )
494            }
495        }
496    };
497
498    ($s:ident : $slf:ident $ser:ident => {$($ser_impl:tt)*} $de:ident => {$($de_impl:tt)*}) => {
499        crate::serde_impl!{mod serde_impl = $s : $slf $ser => {$($ser_impl)*} $de => {$($de_impl)*}}
500    };
501
502    (mod $m:ident = $s:ident : $slf:ident $ser:ident => {$($ser_impl:tt)*} $de:ident => {$($de_impl:tt)*}) => {
503        #[cfg(feature="serde")]#[allow(unused_imports)]
504        mod $m {
505            use super::$s;
506            use crate::Unchecked;
507            use ::serde::ser::{SerializeStruct,SerializeStructVariant};
508            use ::serde::de::{EnumAccess,VariantAccess,Error};
509            impl<State:$crate::CheckingState> ::serde::Serialize for $s<State> {
510                fn serialize<S: ::serde::Serializer>(&self,$ser:S) -> Result<S::Ok,S::Error> {
511                    let $slf = self;
512                    $($ser_impl)*
513                }
514            }
515            impl<'de> ::serde::Deserialize<'de> for $s<Unchecked> {
516                fn deserialize<D: ::serde::de::Deserializer<'de>>($de: D) -> Result<Self, D::Error> {
517                    $($de_impl)*
518                }
519            }
520        }
521    };
522}
523pub(crate) use serde_impl;