sdml_core/model/
values.rs

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