sdml_core/model/
values.rs

1/*!
2Provide the Rust types that implement *value*-related components of the SDML Grammar.
3*/
4use crate::{
5    model::{
6        identifiers::{Identifier, IdentifierReference, QualifiedIdentifier},
7        members::{Ordering, Uniqueness},
8        HasSourceSpan, Span,
9    },
10    syntax::grammar::{VALUE_BOOLEAN_FALSITY_SYMBOL, VALUE_BOOLEAN_TRUTH_SYMBOL},
11};
12use lazy_static::lazy_static;
13use ordered_float::OrderedFloat;
14use regex::Regex;
15use rust_decimal::Decimal;
16use sdml_errors::diagnostics::functions::invalid_language_tag;
17use std::{
18    fmt::{Debug, Display},
19    str::FromStr,
20};
21use url::Url;
22
23#[cfg(feature = "serde")]
24use serde::{Deserialize, Serialize};
25
26// ------------------------------------------------------------------------------------------------
27// Public Types ❱ Values
28// ------------------------------------------------------------------------------------------------
29
30/// Corresponds to the grammar rule `value`.
31#[derive(Clone, Debug)]
32#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
33pub enum Value {
34    Simple(SimpleValue),
35    ValueConstructor(ValueConstructor),
36    Mapping(MappingValue),
37    Reference(IdentifierReference),
38    Sequence(SequenceOfValues),
39}
40
41#[derive(Clone, Debug, PartialEq, Eq, Hash)]
42#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
43pub enum ValueType {
44    Simple(SimpleValueType),
45    ValueConstructor(SimpleValueType),
46    Mapping(SimpleValueType, Box<ValueType>),
47    Reference,
48    Sequence(Vec<ValueType>),
49}
50
51/// Corresponds to the grammar rule `simple_value`.
52#[derive(Clone, Debug)]
53#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
54pub enum SimpleValue {
55    /// Corresponds to the grammar rule `boolean`.
56    Boolean(bool),
57    /// Corresponds to the grammar rule `double`.
58    Double(OrderedFloat<f64>),
59    /// Corresponds to the grammar rule `decimal`.
60    Decimal(Decimal),
61    /// Corresponds to the grammar rule `integer`.
62    Integer(i64),
63    /// Corresponds to the grammar rule `unsigned`.
64    Unsigned(u64),
65    /// Corresponds to the grammar rule `string`.
66    String(LanguageString),
67    /// Corresponds to the grammar rule `iri_reference`.
68    IriReference(Url),
69    /// Corresponds to the grammar rule `binary`.
70    Binary(Binary),
71}
72
73#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
74#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
75pub enum SimpleValueType {
76    Boolean,
77    Double,
78    Decimal,
79    Integer,
80    Unsigned,
81    String,
82    IriReference,
83    Binary,
84}
85
86/// Corresponds to the grammar rule `binary`.
87#[derive(Clone, Debug)]
88#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
89pub struct Binary(Vec<u8>);
90
91/// Corresponds to the grammar rule `string`.
92#[derive(Clone, Debug)]
93#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
94pub struct LanguageString {
95    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
96    span: Option<Span>,
97    /// Corresponds to the grammar rule `quoted_string`.
98    value: String,
99    language: Option<LanguageTag>,
100}
101
102/// Corresponds to the grammar rule `language_tag`.
103#[derive(Clone, Debug)]
104#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
105pub struct LanguageTag {
106    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
107    span: Option<Span>,
108    value: language_tags::LanguageTag,
109}
110
111/// Corresponds to the grammar rule `mapping_value`.
112#[derive(Clone, Debug)]
113#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
114pub struct MappingValue {
115    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
116    span: Option<Span>,
117    domain: SimpleValue,
118    range: Box<Value>,
119}
120
121/// Corresponds to the grammar rule `list_of_values`.
122#[derive(Clone, Debug, Default)]
123#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
124pub struct SequenceOfValues {
125    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
126    span: Option<Span>,
127    ordering: Option<Ordering>,
128    uniqueness: Option<Uniqueness>,
129    values: Vec<SequenceMember>,
130}
131
132/// Corresponds to the grammar rule `name`.
133#[derive(Clone, Debug)]
134#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
135pub enum SequenceMember {
136    Simple(SimpleValue),
137    ValueConstructor(ValueConstructor),
138    Reference(IdentifierReference),
139    Mapping(MappingValue),
140}
141
142/// Corresponds to the grammar rule `value_constructor`.
143#[derive(Clone, Debug)]
144#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
145pub struct ValueConstructor {
146    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
147    span: Option<Span>,
148    type_name: IdentifierReference,
149    value: SimpleValue,
150}
151
152// ------------------------------------------------------------------------------------------------
153// Implementations
154// ------------------------------------------------------------------------------------------------
155
156lazy_static! {
157    static ref LANGUAGE_TAG: Regex =
158        Regex::new(r"^[a-z]{2,3}(-[A-Z]{3})?(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$").unwrap();
159}
160
161// ------------------------------------------------------------------------------------------------
162// Implementations ❱ Value
163// ------------------------------------------------------------------------------------------------
164
165impl<T: Into<SimpleValue>> From<T> for Value {
166    fn from(v: T) -> Self {
167        Self::Simple(v.into())
168    }
169}
170
171impl From<&ValueConstructor> for Value {
172    fn from(v: &ValueConstructor) -> Self {
173        Self::ValueConstructor(v.clone())
174    }
175}
176
177impl From<ValueConstructor> for Value {
178    fn from(v: ValueConstructor) -> Self {
179        Self::ValueConstructor(v)
180    }
181}
182
183impl From<&Identifier> for Value {
184    fn from(value: &Identifier) -> Self {
185        Self::Reference(value.clone().into())
186    }
187}
188
189impl From<Identifier> for Value {
190    fn from(value: Identifier) -> Self {
191        Self::Reference(value.into())
192    }
193}
194
195impl From<&QualifiedIdentifier> for Value {
196    fn from(value: &QualifiedIdentifier) -> Self {
197        Self::Reference(value.clone().into())
198    }
199}
200
201impl From<QualifiedIdentifier> for Value {
202    fn from(value: QualifiedIdentifier) -> Self {
203        Self::Reference(value.into())
204    }
205}
206
207impl From<&IdentifierReference> for Value {
208    fn from(value: &IdentifierReference) -> Self {
209        Self::Reference(value.clone())
210    }
211}
212
213impl From<IdentifierReference> for Value {
214    fn from(value: IdentifierReference) -> Self {
215        Self::Reference(value)
216    }
217}
218
219impl From<&MappingValue> for Value {
220    fn from(v: &MappingValue) -> Self {
221        Self::Mapping(v.clone())
222    }
223}
224
225impl From<MappingValue> for Value {
226    fn from(v: MappingValue) -> Self {
227        Self::Mapping(v)
228    }
229}
230
231impl From<&SequenceOfValues> for Value {
232    fn from(v: &SequenceOfValues) -> Self {
233        Self::Sequence(v.clone())
234    }
235}
236
237impl From<SequenceOfValues> for Value {
238    fn from(v: SequenceOfValues) -> Self {
239        Self::Sequence(v)
240    }
241}
242
243impl Display for Value {
244    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
245        write!(
246            f,
247            "{}",
248            match self {
249                Self::Simple(v) => v.to_string(),
250                Self::ValueConstructor(v) => v.to_string(),
251                Self::Reference(v) => v.to_string(),
252                Self::Mapping(v) => v.to_string(),
253                Self::Sequence(v) => v.to_string(),
254            }
255        )
256    }
257}
258
259impl Value {
260    // --------------------------------------------------------------------------------------------
261    // Variants
262    // --------------------------------------------------------------------------------------------
263
264    pub const fn is_simple(&self) -> bool {
265        matches!(self, Self::Simple(_))
266    }
267
268    pub const fn as_simple(&self) -> Option<&SimpleValue> {
269        match self {
270            Self::Simple(v) => Some(v),
271            _ => None,
272        }
273    }
274
275    pub const fn is_value_constructor(&self) -> bool {
276        matches!(self, Self::ValueConstructor(_))
277    }
278
279    pub const fn as_value_constructor(&self) -> Option<&ValueConstructor> {
280        match self {
281            Self::ValueConstructor(v) => Some(v),
282            _ => None,
283        }
284    }
285
286    pub const fn is_mapping_value(&self) -> bool {
287        matches!(self, Self::Mapping(_))
288    }
289
290    pub const fn as_mapping_value(&self) -> Option<&MappingValue> {
291        match self {
292            Self::Mapping(v) => Some(v),
293            _ => None,
294        }
295    }
296
297    pub const fn is_reference(&self) -> bool {
298        matches!(self, Self::Reference(_))
299    }
300
301    pub const fn as_reference(&self) -> Option<&IdentifierReference> {
302        match self {
303            Self::Reference(v) => Some(v),
304            _ => None,
305        }
306    }
307    pub const fn is_sequence(&self) -> bool {
308        matches!(self, Self::Sequence(_))
309    }
310
311    pub const fn as_sequence(&self) -> Option<&SequenceOfValues> {
312        match self {
313            Self::Sequence(v) => Some(v),
314            _ => None,
315        }
316    }
317
318    // --------------------------------------------------------------------------------------------
319    // Variants ❱ SimpleTypes
320    // --------------------------------------------------------------------------------------------
321
322    pub const fn is_boolean(&self) -> bool {
323        matches!(self, Self::Simple(SimpleValue::Boolean(_)))
324    }
325
326    pub const fn as_boolean(&self) -> Option<bool> {
327        match self {
328            Self::Simple(SimpleValue::Boolean(v)) => Some(*v),
329            _ => None,
330        }
331    }
332
333    pub const fn is_double(&self) -> bool {
334        matches!(self, Self::Simple(SimpleValue::Double(_)))
335    }
336
337    pub const fn as_double(&self) -> Option<OrderedFloat<f64>> {
338        match self {
339            Self::Simple(SimpleValue::Double(v)) => Some(*v),
340            _ => None,
341        }
342    }
343
344    pub const fn is_decimal(&self) -> bool {
345        matches!(self, Self::Simple(SimpleValue::Decimal(_)))
346    }
347
348    pub const fn as_decimal(&self) -> Option<Decimal> {
349        match self {
350            Self::Simple(SimpleValue::Decimal(v)) => Some(*v),
351            _ => None,
352        }
353    }
354
355    pub const fn is_integer(&self) -> bool {
356        matches!(self, Self::Simple(SimpleValue::Integer(_)))
357    }
358
359    pub fn as_integer(&self) -> Option<i64> {
360        match self {
361            Self::Simple(SimpleValue::Integer(v)) => Some(*v),
362            _ => None,
363        }
364    }
365
366    pub const fn is_unsigned(&self) -> bool {
367        matches!(self, Self::Simple(SimpleValue::Unsigned(_)))
368    }
369
370    pub const fn as_unsigned(&self) -> Option<u64> {
371        match self {
372            Self::Simple(SimpleValue::Unsigned(v)) => Some(*v),
373            _ => None,
374        }
375    }
376
377    pub const fn is_string(&self) -> bool {
378        matches!(self, Self::Simple(SimpleValue::String(_)))
379    }
380
381    pub const fn as_string(&self) -> Option<&LanguageString> {
382        match self {
383            Self::Simple(SimpleValue::String(v)) => Some(v),
384            _ => None,
385        }
386    }
387
388    pub const fn is_iri(&self) -> bool {
389        matches!(self, Self::Simple(SimpleValue::IriReference(_)))
390    }
391
392    pub const fn as_iri(&self) -> Option<&Url> {
393        match self {
394            Self::Simple(SimpleValue::IriReference(v)) => Some(v),
395            _ => None,
396        }
397    }
398
399    pub const fn is_binary(&self) -> bool {
400        matches!(self, Self::Simple(SimpleValue::Binary(_)))
401    }
402
403    pub const fn as_binary(&self) -> Option<&Binary> {
404        match self {
405            Self::Simple(SimpleValue::Binary(v)) => Some(v),
406            _ => None,
407        }
408    }
409}
410
411// ------------------------------------------------------------------------------------------------
412// Implementations ❱ SimpleValue
413// ------------------------------------------------------------------------------------------------
414
415impl From<&bool> for SimpleValue {
416    fn from(v: &bool) -> Self {
417        Self::Boolean(*v)
418    }
419}
420
421impl From<bool> for SimpleValue {
422    fn from(v: bool) -> Self {
423        Self::Boolean(v)
424    }
425}
426
427impl From<&f64> for SimpleValue {
428    fn from(v: &f64) -> Self {
429        Self::Double(OrderedFloat::from(*v))
430    }
431}
432
433impl From<f64> for SimpleValue {
434    fn from(v: f64) -> Self {
435        Self::Double(OrderedFloat::from(v))
436    }
437}
438
439impl From<&OrderedFloat<f64>> for SimpleValue {
440    fn from(v: &OrderedFloat<f64>) -> Self {
441        Self::Double(*v)
442    }
443}
444
445impl From<OrderedFloat<f64>> for SimpleValue {
446    fn from(v: OrderedFloat<f64>) -> Self {
447        Self::Double(v)
448    }
449}
450
451impl From<&Decimal> for SimpleValue {
452    fn from(v: &Decimal) -> Self {
453        Self::Decimal(*v)
454    }
455}
456
457impl From<Decimal> for SimpleValue {
458    fn from(v: Decimal) -> Self {
459        Self::Decimal(v)
460    }
461}
462
463impl From<&i64> for SimpleValue {
464    fn from(v: &i64) -> Self {
465        Self::Integer(*v)
466    }
467}
468
469impl From<i64> for SimpleValue {
470    fn from(v: i64) -> Self {
471        Self::Integer(v)
472    }
473}
474
475impl From<&u64> for SimpleValue {
476    fn from(v: &u64) -> Self {
477        Self::Unsigned(*v)
478    }
479}
480
481impl From<u64> for SimpleValue {
482    fn from(v: u64) -> Self {
483        Self::Unsigned(v)
484    }
485}
486
487impl From<&i32> for SimpleValue {
488    fn from(v: &i32) -> Self {
489        Self::Integer(*v as i64)
490    }
491}
492
493impl From<i32> for SimpleValue {
494    fn from(v: i32) -> Self {
495        Self::Integer(v as i64)
496    }
497}
498
499impl From<&u32> for SimpleValue {
500    fn from(v: &u32) -> Self {
501        Self::Unsigned(*v as u64)
502    }
503}
504
505impl From<u32> for SimpleValue {
506    fn from(v: u32) -> Self {
507        Self::Unsigned(v as u64)
508    }
509}
510
511impl From<&i16> for SimpleValue {
512    fn from(v: &i16) -> Self {
513        Self::Integer(*v as i64)
514    }
515}
516
517impl From<i16> for SimpleValue {
518    fn from(v: i16) -> Self {
519        Self::Integer(v as i64)
520    }
521}
522
523impl From<&u16> for SimpleValue {
524    fn from(v: &u16) -> Self {
525        Self::Unsigned(*v as u64)
526    }
527}
528
529impl From<u16> for SimpleValue {
530    fn from(v: u16) -> Self {
531        Self::Unsigned(v as u64)
532    }
533}
534
535impl From<&str> for SimpleValue {
536    fn from(v: &str) -> Self {
537        Self::plain(v)
538    }
539}
540
541impl From<String> for SimpleValue {
542    fn from(v: String) -> Self {
543        Self::plain(&v)
544    }
545}
546
547impl From<&LanguageString> for SimpleValue {
548    fn from(v: &LanguageString) -> Self {
549        Self::String(v.clone())
550    }
551}
552
553impl From<LanguageString> for SimpleValue {
554    fn from(v: LanguageString) -> Self {
555        Self::String(v)
556    }
557}
558
559impl From<&Url> for SimpleValue {
560    fn from(v: &Url) -> Self {
561        Self::IriReference(v.clone())
562    }
563}
564
565impl From<Url> for SimpleValue {
566    fn from(v: Url) -> Self {
567        Self::IriReference(v)
568    }
569}
570
571impl From<&Binary> for SimpleValue {
572    fn from(v: &Binary) -> Self {
573        Self::Binary(v.clone())
574    }
575}
576
577impl From<Binary> for SimpleValue {
578    fn from(v: Binary) -> Self {
579        Self::Binary(v)
580    }
581}
582
583impl Display for SimpleValue {
584    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
585        write!(
586            f,
587            "{}",
588            match self {
589                Self::Double(v) => format!("{:e}", v),
590                Self::Decimal(v) => v.to_string(),
591                Self::Integer(v) => v.to_string(),
592                Self::Unsigned(v) => v.to_string(),
593                Self::Boolean(v) =>
594                    if f.alternate() {
595                        if *v {
596                            VALUE_BOOLEAN_TRUTH_SYMBOL.to_string()
597                        } else {
598                            VALUE_BOOLEAN_FALSITY_SYMBOL.to_string()
599                        }
600                    } else {
601                        v.to_string()
602                    },
603                Self::IriReference(v) => format!("<{v}>"),
604                Self::String(v) => v.to_string(),
605                Self::Binary(v) => v.to_string(),
606            }
607        )
608    }
609}
610
611impl SimpleValue {
612    pub fn plain<S>(content: S) -> Self
613    where
614        S: AsRef<str>,
615    {
616        LanguageString::plain(content.as_ref()).into()
617    }
618
619    // --------------------------------------------------------------------------------------------
620    // Variants
621    // --------------------------------------------------------------------------------------------
622
623    pub const fn is_boolean(&self) -> bool {
624        matches!(self, Self::Boolean(_))
625    }
626
627    pub const fn as_boolean(&self) -> Option<&bool> {
628        match self {
629            Self::Boolean(v) => Some(v),
630            _ => None,
631        }
632    }
633
634    pub const fn is_double(&self) -> bool {
635        matches!(self, Self::Double(_))
636    }
637
638    pub const fn as_double(&self) -> Option<&OrderedFloat<f64>> {
639        match self {
640            Self::Double(v) => Some(v),
641            _ => None,
642        }
643    }
644
645    pub const fn is_decimal(&self) -> bool {
646        matches!(self, Self::Decimal(_))
647    }
648
649    pub const fn as_decimal(&self) -> Option<&Decimal> {
650        match self {
651            Self::Decimal(v) => Some(v),
652            _ => None,
653        }
654    }
655
656    pub const fn is_integer(&self) -> bool {
657        matches!(self, Self::Integer(_))
658    }
659
660    pub const fn as_integer(&self) -> Option<&i64> {
661        match self {
662            Self::Integer(v) => Some(v),
663            _ => None,
664        }
665    }
666
667    pub const fn is_unsigned(&self) -> bool {
668        matches!(self, Self::Unsigned(_))
669    }
670
671    pub const fn as_unsigned(&self) -> Option<&u64> {
672        match self {
673            Self::Unsigned(v) => Some(v),
674            _ => None,
675        }
676    }
677
678    pub const fn is_string(&self) -> bool {
679        matches!(self, Self::String(_))
680    }
681
682    pub const fn as_string(&self) -> Option<&LanguageString> {
683        match self {
684            Self::String(v) => Some(v),
685            _ => None,
686        }
687    }
688
689    pub const fn is_iri(&self) -> bool {
690        matches!(self, Self::IriReference(_))
691    }
692
693    pub const fn as_iri(&self) -> Option<&Url> {
694        match self {
695            Self::IriReference(v) => Some(v),
696            _ => None,
697        }
698    }
699
700    pub const fn is_binary(&self) -> bool {
701        matches!(self, Self::Binary(_))
702    }
703
704    pub const fn as_binary(&self) -> Option<&Binary> {
705        match self {
706            Self::Binary(v) => Some(v),
707            _ => None,
708        }
709    }
710}
711
712// ------------------------------------------------------------------------------------------------
713// Implementations ❱ LanguageString
714// ------------------------------------------------------------------------------------------------
715
716impl From<String> for LanguageString {
717    fn from(v: String) -> Self {
718        Self::new(&v, None)
719    }
720}
721
722impl From<&str> for LanguageString {
723    fn from(v: &str) -> Self {
724        Self::new(v, None)
725    }
726}
727
728impl PartialEq for LanguageString {
729    fn eq(&self, other: &Self) -> bool {
730        self.value == other.value && self.language == other.language
731    }
732}
733
734impl Eq for LanguageString {}
735
736impl HasSourceSpan for LanguageString {
737    fn with_source_span(self, span: Span) -> Self {
738        let mut self_mut = self;
739        self_mut.span = Some(span);
740        self_mut
741    }
742
743    fn source_span(&self) -> Option<&Span> {
744        self.span.as_ref()
745    }
746
747    fn set_source_span(&mut self, span: Span) {
748        self.span = Some(span);
749    }
750
751    fn unset_source_span(&mut self) {
752        self.span = None;
753    }
754}
755
756impl Display for LanguageString {
757    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
758        write!(
759            f,
760            "{:?}{}",
761            self.value,
762            if let Some(language) = &self.language {
763                language.to_string()
764            } else {
765                String::new()
766            }
767        )
768    }
769}
770
771impl LanguageString {
772    // --------------------------------------------------------------------------------------------
773    // Constructors
774    // --------------------------------------------------------------------------------------------
775
776    pub fn new(value: &str, language: Option<LanguageTag>) -> Self {
777        Self {
778            span: None,
779            value: value.to_string(),
780            language,
781        }
782    }
783
784    pub fn plain(value: &str) -> Self {
785        Self::new(value, None)
786    }
787
788    // --------------------------------------------------------------------------------------------
789    // Fields
790    // --------------------------------------------------------------------------------------------
791
792    pub const fn value(&self) -> &String {
793        &self.value
794    }
795
796    pub fn set_value(&mut self, value: String) {
797        self.value = value;
798    }
799
800    pub const fn has_language(&self) -> bool {
801        self.language.is_some()
802    }
803
804    pub const fn language(&self) -> Option<&LanguageTag> {
805        self.language.as_ref()
806    }
807
808    pub fn set_language(&mut self, language: LanguageTag) {
809        self.language = Some(language);
810    }
811
812    pub fn unset_language(&mut self) {
813        self.language = None;
814    }
815
816    // --------------------------------------------------------------------------------------------
817    // Helpers
818    // --------------------------------------------------------------------------------------------
819
820    pub fn is_plain_literal(&self) -> bool {
821        !self.has_language()
822    }
823
824    pub fn eq_with_span(&self, other: &Self) -> bool {
825        self.span == other.span && self.value == other.value && self.language == other.language
826    }
827}
828
829// ------------------------------------------------------------------------------------------------
830// Implementations ❱ LanguageTag
831// ------------------------------------------------------------------------------------------------
832
833impl From<LanguageTag> for language_tags::LanguageTag {
834    fn from(value: LanguageTag) -> Self {
835        value.value
836    }
837}
838
839impl From<LanguageTag> for String {
840    fn from(value: LanguageTag) -> Self {
841        value.value.to_string()
842    }
843}
844
845impl FromStr for LanguageTag {
846    type Err = crate::error::Error;
847
848    fn from_str(s: &str) -> Result<Self, Self::Err> {
849        if Self::is_valid_str(s) {
850            Ok(Self {
851                span: None,
852                value: language_tags::LanguageTag::parse(s)?,
853            })
854        } else {
855            Err(invalid_language_tag(0, None, s).into())
856        }
857    }
858}
859
860impl AsRef<language_tags::LanguageTag> for LanguageTag {
861    fn as_ref(&self) -> &language_tags::LanguageTag {
862        &self.value
863    }
864}
865
866impl AsRef<str> for LanguageTag {
867    fn as_ref(&self) -> &str {
868        self.value.as_str()
869    }
870}
871
872impl PartialEq for LanguageTag {
873    fn eq(&self, other: &Self) -> bool {
874        self.value == other.value
875    }
876}
877
878impl PartialEq<language_tags::LanguageTag> for LanguageTag {
879    fn eq(&self, other: &language_tags::LanguageTag) -> bool {
880        self.value == *other
881    }
882}
883
884impl PartialEq<str> for LanguageTag {
885    fn eq(&self, other: &str) -> bool {
886        self.value.as_str() == other
887    }
888}
889
890impl Eq for LanguageTag {}
891
892impl Display for LanguageTag {
893    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
894        write!(f, "@{}", self.value)
895    }
896}
897
898impl HasSourceSpan for LanguageTag {
899    fn with_source_span(self, span: Span) -> Self {
900        let mut self_mut = self;
901        self_mut.span = Some(span);
902        self_mut
903    }
904
905    fn source_span(&self) -> Option<&Span> {
906        self.span.as_ref()
907    }
908
909    fn set_source_span(&mut self, span: Span) {
910        self.span = Some(span);
911    }
912
913    fn unset_source_span(&mut self) {
914        self.span = None;
915    }
916}
917
918impl LanguageTag {
919    // --------------------------------------------------------------------------------------------
920    // Constructors
921    // --------------------------------------------------------------------------------------------
922
923    pub fn new(value: language_tags::LanguageTag) -> Self {
924        Self { span: None, value }
925    }
926
927    pub fn new_unchecked(s: &str) -> Self {
928        Self {
929            span: None,
930            value: language_tags::LanguageTag::parse(s).unwrap(),
931        }
932    }
933
934    // --------------------------------------------------------------------------------------------
935    // Helpers
936    // --------------------------------------------------------------------------------------------
937
938    pub fn is_valid_str(s: &str) -> bool {
939        language_tags::LanguageTag::parse(s).is_ok()
940    }
941
942    pub fn eq_with_span(&self, other: &Self) -> bool {
943        self.span == other.span && self.value == other.value
944    }
945
946    pub fn inner(&self) -> &language_tags::LanguageTag {
947        &self.value
948    }
949
950    pub fn into_inner(self) -> language_tags::LanguageTag {
951        self.value
952    }
953}
954
955// ------------------------------------------------------------------------------------------------
956// Implementations ❱ Binary
957// ------------------------------------------------------------------------------------------------
958
959impl Display for Binary {
960    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
961        write!(f, "#[ ")?;
962        for byte in self.as_bytes() {
963            write!(f, "{:02X} ", byte)?;
964        }
965        write!(f, "]")
966    }
967}
968
969impl From<Vec<u8>> for Binary {
970    fn from(v: Vec<u8>) -> Self {
971        Self(v)
972    }
973}
974
975impl FromIterator<u8> for Binary {
976    fn from_iter<T: IntoIterator<Item = u8>>(iter: T) -> Self {
977        Self(Vec::from_iter(iter))
978    }
979}
980
981impl AsRef<Vec<u8>> for Binary {
982    fn as_ref(&self) -> &Vec<u8> {
983        &self.0
984    }
985}
986
987impl Binary {
988    // --------------------------------------------------------------------------------------------
989    // Helpers
990    // --------------------------------------------------------------------------------------------
991    pub fn as_bytes(&self) -> &[u8] {
992        self.0.as_slice()
993    }
994
995    pub fn to_sdml_string(&self) -> String {
996        self.to_string()
997    }
998
999    pub fn to_hex_string(&self) -> String {
1000        self.as_bytes()
1001            .iter()
1002            .fold(String::with_capacity(self.0.len() * 2), |mut result, b| {
1003                result.push_str(&format!("{b:02X}"));
1004                result
1005            })
1006    }
1007
1008    pub fn to_base64_string(&self) -> String {
1009        self.to_base64_string_with(&base64::engine::general_purpose::STANDARD_NO_PAD)
1010    }
1011
1012    pub fn to_base64_string_with<T: base64::Engine>(&self, engine: &T) -> String {
1013        engine.encode(self.as_bytes())
1014    }
1015}
1016
1017// ------------------------------------------------------------------------------------------------
1018// Implementations ❱ MappingValue
1019// ------------------------------------------------------------------------------------------------
1020
1021impl Display for MappingValue {
1022    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1023        write!(f, "{} -> {}", self.domain, self.range)
1024    }
1025}
1026
1027impl HasSourceSpan for MappingValue {
1028    fn with_source_span(self, span: Span) -> Self {
1029        let mut self_mut = self;
1030        self_mut.span = Some(span);
1031        self_mut
1032    }
1033
1034    fn source_span(&self) -> Option<&Span> {
1035        self.span.as_ref()
1036    }
1037
1038    fn set_source_span(&mut self, span: Span) {
1039        self.span = Some(span);
1040    }
1041
1042    fn unset_source_span(&mut self) {
1043        self.span = None;
1044    }
1045}
1046
1047impl MappingValue {
1048    // --------------------------------------------------------------------------------------------
1049    // Constructors
1050    // --------------------------------------------------------------------------------------------
1051
1052    pub fn new(domain: SimpleValue, range: Value) -> Self {
1053        Self {
1054            span: None,
1055            domain,
1056            range: Box::new(range),
1057        }
1058    }
1059
1060    // --------------------------------------------------------------------------------------------
1061    // Fields
1062    // --------------------------------------------------------------------------------------------
1063
1064    pub const fn domain(&self) -> &SimpleValue {
1065        &self.domain
1066    }
1067
1068    pub fn set_domain<T>(&mut self, domain: T)
1069    where
1070        T: Into<SimpleValue>,
1071    {
1072        self.domain = domain.into();
1073    }
1074
1075    pub const fn range(&self) -> &Value {
1076        &self.range
1077    }
1078
1079    pub fn set_range<T>(&mut self, range: T)
1080    where
1081        T: Into<Value>,
1082    {
1083        self.range = Box::new(range.into());
1084    }
1085}
1086
1087// ------------------------------------------------------------------------------------------------
1088// Implementations ❱ SequenceOfValues
1089// ------------------------------------------------------------------------------------------------
1090
1091impl From<Vec<SequenceMember>> for SequenceOfValues {
1092    fn from(values: Vec<SequenceMember>) -> Self {
1093        Self {
1094            span: None,
1095            ordering: None,
1096            uniqueness: None,
1097            values,
1098        }
1099    }
1100}
1101
1102impl FromIterator<SequenceMember> for SequenceOfValues {
1103    fn from_iter<T: IntoIterator<Item = SequenceMember>>(iter: T) -> Self {
1104        Self::from(Vec::from_iter(iter))
1105    }
1106}
1107
1108impl Display for SequenceOfValues {
1109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1110        write!(
1111            f,
1112            "[ {} ]",
1113            self.values
1114                .iter()
1115                .map(|v| v.to_string())
1116                .collect::<Vec<String>>()
1117                .join(" ")
1118        )
1119    }
1120}
1121
1122impl HasSourceSpan for SequenceOfValues {
1123    fn with_source_span(self, span: Span) -> Self {
1124        let mut self_mut = self;
1125        self_mut.span = Some(span);
1126        self_mut
1127    }
1128
1129    fn source_span(&self) -> Option<&Span> {
1130        self.span.as_ref()
1131    }
1132
1133    fn set_source_span(&mut self, span: Span) {
1134        self.span = Some(span);
1135    }
1136
1137    fn unset_source_span(&mut self) {
1138        self.span = None;
1139    }
1140}
1141
1142impl SequenceOfValues {
1143    // --------------------------------------------------------------------------------------------
1144    // Constructors
1145    // --------------------------------------------------------------------------------------------
1146
1147    pub fn with_ordering(self, ordering: Ordering) -> Self {
1148        Self {
1149            ordering: Some(ordering),
1150            ..self
1151        }
1152    }
1153
1154    pub fn with_uniqueness(self, uniqueness: Uniqueness) -> Self {
1155        Self {
1156            uniqueness: Some(uniqueness),
1157            ..self
1158        }
1159    }
1160
1161    // --------------------------------------------------------------------------------------------
1162    // Values
1163    // --------------------------------------------------------------------------------------------
1164
1165    pub fn is_empty(&self) -> bool {
1166        self.values.is_empty()
1167    }
1168
1169    pub fn len(&self) -> usize {
1170        self.values.len()
1171    }
1172
1173    pub fn iter(&self) -> impl Iterator<Item = &SequenceMember> {
1174        self.values.iter()
1175    }
1176
1177    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut SequenceMember> {
1178        self.values.iter_mut()
1179    }
1180
1181    pub fn push<I>(&mut self, value: I)
1182    where
1183        I: Into<SequenceMember>,
1184    {
1185        self.values.push(value.into())
1186    }
1187
1188    pub fn extend<I>(&mut self, extension: I)
1189    where
1190        I: IntoIterator<Item = SequenceMember>,
1191    {
1192        self.values.extend(extension)
1193    }
1194
1195    // --------------------------------------------------------------------------------------------
1196    // Fields
1197    // --------------------------------------------------------------------------------------------
1198
1199    pub const fn has_ordering(&self) -> bool {
1200        self.ordering.is_some()
1201    }
1202
1203    pub const fn ordering(&self) -> Option<&Ordering> {
1204        self.ordering.as_ref()
1205    }
1206
1207    pub fn set_ordering(&mut self, ordering: Ordering) {
1208        self.ordering = Some(ordering);
1209    }
1210
1211    pub fn unset_ordering(&mut self) {
1212        self.ordering = None;
1213    }
1214
1215    // --------------------------------------------------------------------------------------------
1216
1217    pub const fn has_uniqueness(&self) -> bool {
1218        self.uniqueness.is_some()
1219    }
1220
1221    pub const fn uniqueness(&self) -> Option<&Uniqueness> {
1222        self.uniqueness.as_ref()
1223    }
1224
1225    pub fn set_uniqueness(&mut self, uniqueness: Uniqueness) {
1226        self.uniqueness = Some(uniqueness);
1227    }
1228
1229    pub fn unset_uniqueness(&mut self) {
1230        self.uniqueness = None;
1231    }
1232}
1233
1234// ------------------------------------------------------------------------------------------------
1235// Implementations ❱ SequenceMember
1236// ------------------------------------------------------------------------------------------------
1237
1238impl<T: Into<SimpleValue>> From<T> for SequenceMember {
1239    fn from(value: T) -> Self {
1240        Self::Simple(value.into())
1241    }
1242}
1243
1244impl From<&ValueConstructor> for SequenceMember {
1245    fn from(v: &ValueConstructor) -> Self {
1246        Self::ValueConstructor(v.clone())
1247    }
1248}
1249
1250impl From<ValueConstructor> for SequenceMember {
1251    fn from(v: ValueConstructor) -> Self {
1252        Self::ValueConstructor(v)
1253    }
1254}
1255
1256impl From<&Identifier> for SequenceMember {
1257    fn from(value: &Identifier) -> Self {
1258        Self::Reference(value.clone().into())
1259    }
1260}
1261
1262impl From<Identifier> for SequenceMember {
1263    fn from(value: Identifier) -> Self {
1264        Self::Reference(value.into())
1265    }
1266}
1267
1268impl From<&QualifiedIdentifier> for SequenceMember {
1269    fn from(value: &QualifiedIdentifier) -> Self {
1270        Self::Reference(value.clone().into())
1271    }
1272}
1273
1274impl From<QualifiedIdentifier> for SequenceMember {
1275    fn from(value: QualifiedIdentifier) -> Self {
1276        Self::Reference(value.into())
1277    }
1278}
1279
1280impl From<&IdentifierReference> for SequenceMember {
1281    fn from(value: &IdentifierReference) -> Self {
1282        Self::Reference(value.clone())
1283    }
1284}
1285
1286impl From<IdentifierReference> for SequenceMember {
1287    fn from(value: IdentifierReference) -> Self {
1288        Self::Reference(value)
1289    }
1290}
1291
1292impl From<&MappingValue> for SequenceMember {
1293    fn from(v: &MappingValue) -> Self {
1294        Self::Mapping(v.clone())
1295    }
1296}
1297
1298impl From<MappingValue> for SequenceMember {
1299    fn from(v: MappingValue) -> Self {
1300        Self::Mapping(v)
1301    }
1302}
1303
1304impl Display for SequenceMember {
1305    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1306        write!(
1307            f,
1308            "{}",
1309            match self {
1310                Self::Simple(v) => v.to_string(),
1311                Self::ValueConstructor(v) => v.to_string(),
1312                Self::Reference(v) => v.to_string(),
1313                Self::Mapping(v) => v.to_string(),
1314            }
1315        )
1316    }
1317}
1318
1319impl SequenceMember {
1320    // --------------------------------------------------------------------------------------------
1321    // Variants
1322    // --------------------------------------------------------------------------------------------
1323
1324    pub fn is_simple(&self) -> bool {
1325        matches!(self, Self::Simple(_))
1326    }
1327
1328    pub fn as_simple(&self) -> Option<&SimpleValue> {
1329        match self {
1330            Self::Simple(v) => Some(v),
1331            _ => None,
1332        }
1333    }
1334
1335    pub fn is_value_constructor(&self) -> bool {
1336        matches!(self, Self::ValueConstructor(_))
1337    }
1338
1339    pub fn as_value_constructor(&self) -> Option<&ValueConstructor> {
1340        match self {
1341            Self::ValueConstructor(v) => Some(v),
1342            _ => None,
1343        }
1344    }
1345
1346    pub fn is_reference(&self) -> bool {
1347        matches!(self, Self::Reference(_))
1348    }
1349
1350    pub fn as_reference(&self) -> Option<&IdentifierReference> {
1351        match self {
1352            Self::Reference(v) => Some(v),
1353            _ => None,
1354        }
1355    }
1356
1357    pub fn is_mapping(&self) -> bool {
1358        matches!(self, Self::Mapping(_))
1359    }
1360
1361    pub fn as_mapping(&self) -> Option<&MappingValue> {
1362        match self {
1363            Self::Mapping(v) => Some(v),
1364            _ => None,
1365        }
1366    }
1367}
1368
1369// ------------------------------------------------------------------------------------------------
1370// Implementations ❱ ValueConstructor
1371// ------------------------------------------------------------------------------------------------
1372
1373impl Display for ValueConstructor {
1374    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1375        write!(f, "{}({})", self.type_name, self.value)
1376    }
1377}
1378
1379impl HasSourceSpan for ValueConstructor {
1380    fn with_source_span(self, span: Span) -> Self {
1381        let mut self_mut = self;
1382        self_mut.span = Some(span);
1383        self_mut
1384    }
1385
1386    fn source_span(&self) -> Option<&Span> {
1387        self.span.as_ref()
1388    }
1389
1390    fn set_source_span(&mut self, span: Span) {
1391        self.span = Some(span);
1392    }
1393
1394    fn unset_source_span(&mut self) {
1395        self.span = None;
1396    }
1397}
1398
1399impl ValueConstructor {
1400    // --------------------------------------------------------------------------------------------
1401    // Constructors
1402    // --------------------------------------------------------------------------------------------
1403
1404    pub const fn new(type_name: IdentifierReference, value: SimpleValue) -> Self {
1405        Self {
1406            span: None,
1407            type_name,
1408            value,
1409        }
1410    }
1411
1412    // --------------------------------------------------------------------------------------------
1413    // Fields
1414    // --------------------------------------------------------------------------------------------
1415
1416    pub const fn type_name(&self) -> &IdentifierReference {
1417        &self.type_name
1418    }
1419
1420    pub fn set_type_name(&mut self, type_name: IdentifierReference) {
1421        self.type_name = type_name;
1422    }
1423
1424    pub const fn value(&self) -> &SimpleValue {
1425        &self.value
1426    }
1427
1428    pub fn set_value(&mut self, value: SimpleValue) {
1429        self.value = value;
1430    }
1431}