1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
use crate::cache::ModuleCache;
use crate::error::Error;
use crate::load::ModuleLoader;
use crate::model::check::Validate;
use crate::model::modules::Module;
use crate::model::Span;
use crate::syntax::{
    KW_ORDERING_ORDERED, KW_ORDERING_UNORDERED, KW_UNIQUENESS_NONUNIQUE, KW_UNIQUENESS_UNIQUE,
};
use std::fmt::{Debug, Display};
use std::str::FromStr;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

// ------------------------------------------------------------------------------------------------
// Public Types ❱ Members ❱ Cardinality
// ------------------------------------------------------------------------------------------------

pub trait HasCardinality {
    fn target_cardinality(&self) -> &Cardinality;

    fn set_target_cardinality(&mut self, target_cardinality: Cardinality);
}

/// Corresponds to the grammar rule `cardinality`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct Cardinality {
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    span: Option<Span>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    ordering: Option<Ordering>,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    uniqueness: Option<Uniqueness>,
    range: CardinalityRange,
}

pub const DEFAULT_CARDINALITY: Cardinality = Cardinality::one();

pub const TYPE_BAG_CARDINALITY: Cardinality = Cardinality::zero_or_more();
pub const TYPE_LIST_CARDINALITY: Cardinality =
    Cardinality::zero_or_more().with_ordering(Some(Ordering::Ordered));
pub const TYPE_SET_CARDINALITY: Cardinality =
    Cardinality::zero_or_more().with_uniqueness(Some(Uniqueness::Unique));
pub const TYPE_ORDERED_SET_CARDINALITY: Cardinality = Cardinality::zero_or_more()
    .with_ordering(Some(Ordering::Ordered))
    .with_uniqueness(Some(Uniqueness::Unique));
pub const TYPE_MAYBE_CARDINALITY: Cardinality = Cardinality::zero_or_one();

#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct CardinalityRange {
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    span: Option<Span>,
    min: u32,
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    max: Option<u32>,
}

pub const DEFAULT_CARDINALITY_RANGE: CardinalityRange = CardinalityRange::one();

/// Corresponds to the grammar rule `sequence_ordering`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum Ordering {
    Ordered,
    Unordered,
}

/// Corresponds to the grammar rule `sequence_uniqueness`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum Uniqueness {
    Unique,
    Nonunique,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PseudoSequenceType {
    Maybe,
    Bag,
    List,
    Set,
    UnorderedSet,
}

// ------------------------------------------------------------------------------------------------
// Implementations ❱ Members ❱ Cardinality
// ------------------------------------------------------------------------------------------------

impl Display for Cardinality {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{{{}{}{}..{}}}",
            self.ordering.map(|c| format!("{} ", c)).unwrap_or_default(),
            self.uniqueness
                .map(|c| format!("{} ", c))
                .unwrap_or_default(),
            self.min_occurs(),
            self.max_occurs().map(|i| i.to_string()).unwrap_or_default()
        )
    }
}

impl From<u32> for Cardinality {
    fn from(value: u32) -> Self {
        Self::new_single(value)
    }
}

impl From<CardinalityRange> for Cardinality {
    fn from(range: CardinalityRange) -> Self {
        Self {
            span: Default::default(),
            ordering: Default::default(),
            uniqueness: Default::default(),
            range,
        }
    }
}

impl_has_source_span_for!(Cardinality);

impl Validate for Cardinality {
    fn validate(
        &self,
        top: &Module,
        cache: &ModuleCache,
        loader: &impl ModuleLoader,
        check_constraints: bool,
    ) {
        self.range.validate(top, cache, loader, check_constraints);
    }
}

impl Cardinality {
    // --------------------------------------------------------------------------------------------
    // Cardinality :: Constructors
    // --------------------------------------------------------------------------------------------

    pub const fn new(
        ordering: Option<Ordering>,
        uniqueness: Option<Uniqueness>,
        range: CardinalityRange,
    ) -> Self {
        Self {
            span: None,
            ordering,
            uniqueness,
            range,
        }
    }

    pub const fn new_range(min: u32, max: u32) -> Self {
        Self {
            span: None,
            ordering: None,
            uniqueness: None,
            range: CardinalityRange::new_range(min, max),
        }
    }

    pub const fn new_unbounded(min: u32) -> Self {
        Self {
            span: None,
            ordering: None,
            uniqueness: None,
            range: CardinalityRange::new_unbounded(min),
        }
    }

    pub const fn new_single(min_and_max: u32) -> Self {
        Self {
            span: None,
            ordering: None,
            uniqueness: None,
            range: CardinalityRange::new_single(min_and_max),
        }
    }

    #[inline(always)]
    pub const fn one() -> Self {
        Self::new_single(1)
    }

    #[inline(always)]
    pub const fn zero_or_one() -> Self {
        Self::new_range(0, 1)
    }

    #[inline(always)]
    pub const fn one_or_more() -> Self {
        Self::new_unbounded(1)
    }

    #[inline(always)]
    pub const fn zero_or_more() -> Self {
        Self::new_unbounded(0)
    }

    // --------------------------------------------------------------------------------------------
    // Cardinality :: Fields
    // --------------------------------------------------------------------------------------------

    pub const fn with_ordering(self, ordering: Option<Ordering>) -> Self {
        Self { ordering, ..self }
    }

    #[inline(always)]
    pub fn ordering(&self) -> Option<Ordering> {
        self.ordering
    }

    #[inline(always)]
    pub fn set_ordering(&mut self, ordering: Ordering) {
        self.ordering = Some(ordering);
    }

    #[inline(always)]
    pub fn unset_ordering(&mut self) {
        self.ordering = None;
    }

    #[inline(always)]
    pub fn is_ordered(&self) -> Option<bool> {
        self.ordering().map(|o| o == Ordering::Ordered)
    }

    // --------------------------------------------------------------------------------------------

    #[inline(always)]
    pub const fn with_uniqueness(self, uniqueness: Option<Uniqueness>) -> Self {
        Self { uniqueness, ..self }
    }

    #[inline(always)]
    pub fn uniqueness(&self) -> Option<Uniqueness> {
        self.uniqueness
    }

    #[inline(always)]
    pub fn set_uniqueness(&mut self, uniqueness: Uniqueness) {
        self.uniqueness = Some(uniqueness);
    }

    #[inline(always)]
    pub fn unset_uniqueness(&mut self) {
        self.uniqueness = None;
    }

    #[inline(always)]
    pub fn is_unique(&self) -> Option<bool> {
        self.uniqueness().map(|u| u == Uniqueness::Unique)
    }

    // --------------------------------------------------------------------------------------------

    pub fn range(&self) -> &CardinalityRange {
        &self.range
    }

    pub fn set_range(&mut self, range: CardinalityRange) {
        self.range = range;
    }

    // --------------------------------------------------------------------------------------------

    #[inline(always)]
    pub fn min_occurs(&self) -> u32 {
        self.range.min_occurs()
    }

    #[inline(always)]
    pub fn set_min_occurs(&mut self, min: u32) {
        self.range.set_min_occurs(min);
    }

    // --------------------------------------------------------------------------------------------

    #[inline(always)]
    pub fn max_occurs(&self) -> Option<u32> {
        self.range.max_occurs()
    }

    #[inline(always)]
    pub fn set_max_occurs(&mut self, max: u32) {
        self.range.set_max_occurs(max);
    }

    #[inline(always)]
    pub fn unset_max_occurs(&mut self) {
        self.range.unset_max_occurs();
    }

    // --------------------------------------------------------------------------------------------
    // Cardinality :: Helpers
    // --------------------------------------------------------------------------------------------

    #[inline(always)]
    pub fn is_optional(&self) -> bool {
        self.range.is_optional()
    }

    #[inline(always)]
    pub fn is_required(&self) -> bool {
        !self.range.is_optional()
    }

    #[inline(always)]
    pub fn is_range(&self) -> bool {
        self.range.is_range()
    }

    #[inline(always)]
    pub fn is_unbounded(&self) -> bool {
        self.range.is_unbounded()
    }

    #[inline(always)]
    pub fn is_exactly(&self, value: u32) -> bool {
        self.range.is_exactly(value)
    }

    pub fn sequence_type(&self) -> PseudoSequenceType {
        match (
            self.is_ordered(),
            self.is_unique(),
            self.range.min_occurs(),
            self.range.max_occurs().unwrap_or(self.range.min_occurs()),
        ) {
            (_, _, 0, 1) => PseudoSequenceType::Maybe,
            (Some(true), Some(true), _, _) => PseudoSequenceType::UnorderedSet,
            (Some(false), Some(true), _, _) => PseudoSequenceType::Set,
            (Some(true), Some(false), _, _) => PseudoSequenceType::List,
            _ => PseudoSequenceType::Bag,
        }
    }
}

// ------------------------------------------------------------------------------------------------

impl Display for CardinalityRange {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}..{}",
            self.min,
            self.max.map(|i| i.to_string()).unwrap_or_default()
        )
    }
}

impl From<u32> for CardinalityRange {
    fn from(value: u32) -> Self {
        Self::new_single(value)
    }
}

impl_has_source_span_for!(CardinalityRange);

impl Validate for CardinalityRange {
    fn validate(
        &self,
        _: &Module,
        _: &ModuleCache,
        _loader: &impl ModuleLoader,
        _check_constraints: bool,
    ) {
        if let Some(max) = self.max {
            if max < self.min {
                panic!();
            }
        }
    }
}

impl CardinalityRange {
    // --------------------------------------------------------------------------------------------
    // Cardinality :: Constructors
    // --------------------------------------------------------------------------------------------

    pub const fn new_range(min: u32, max: u32) -> Self {
        assert!(max > 0 && max >= min);
        Self {
            span: None,
            min,
            max: Some(max),
        }
    }

    pub const fn new_unbounded(min: u32) -> Self {
        Self {
            span: None,
            min,
            max: None,
        }
    }

    pub const fn new_single(min_and_max: u32) -> Self {
        assert!(min_and_max > 0);
        Self {
            span: None,
            min: min_and_max,
            max: Some(min_and_max),
        }
    }

    #[inline(always)]
    pub const fn one() -> Self {
        Self::new_single(1)
    }

    #[inline(always)]
    pub const fn zero_or_one() -> Self {
        Self::new_range(0, 1)
    }

    #[inline(always)]
    pub const fn one_or_more() -> Self {
        Self::new_unbounded(1)
    }

    #[inline(always)]
    pub const fn zero_or_more() -> Self {
        Self::new_unbounded(0)
    }

    // --------------------------------------------------------------------------------------------
    // Cardinality :: Fields
    // --------------------------------------------------------------------------------------------

    #[inline(always)]
    pub const fn min_occurs(&self) -> u32 {
        self.min
    }

    #[inline(always)]
    pub fn set_min_occurs(&mut self, min: u32) {
        if let Some(max) = self.max {
            assert!(min <= max);
        }
        self.min = min;
    }

    // --------------------------------------------------------------------------------------------

    #[inline(always)]
    pub const fn max_occurs(&self) -> Option<u32> {
        self.max
    }

    #[inline(always)]
    pub fn set_max_occurs(&mut self, max: u32) {
        assert!(max > 0 && max >= self.min);
        self.max = Some(max);
    }

    #[inline(always)]
    pub fn unset_max_occurs(&mut self) {
        self.max = None;
    }

    // --------------------------------------------------------------------------------------------
    // Cardinality :: Helpers
    // --------------------------------------------------------------------------------------------

    #[inline(always)]
    pub const fn is_optional(&self) -> bool {
        self.min_occurs() == 0
    }

    #[inline(always)]
    pub const fn is_required(&self) -> bool {
        !self.is_optional()
    }

    #[inline(always)]
    pub fn is_range(&self) -> bool {
        self.max.map(|i| i != self.min).unwrap_or(true)
    }

    #[inline(always)]
    pub const fn is_unbounded(&self) -> bool {
        self.max_occurs().is_none()
    }

    #[inline(always)]
    pub fn is_exactly(&self, value: u32) -> bool {
        self.min_occurs() == value && self.max_occurs().map(|i| i == value).unwrap_or(false)
    }

    // --------------------------------------------------------------------------------------------

    #[inline(always)]
    pub fn to_uml_string(&self) -> String {
        if self.is_range() {
            format!(
                "{}..{}",
                self.min_occurs(),
                self.max_occurs()
                    .map(|i| i.to_string())
                    .unwrap_or_else(|| "*".to_string())
            )
        } else {
            self.min.to_string()
        }
    }
}

// ------------------------------------------------------------------------------------------------

impl Default for Ordering {
    fn default() -> Self {
        Self::Unordered
    }
}

impl Display for Ordering {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Ordered => KW_ORDERING_ORDERED,
                Self::Unordered => KW_ORDERING_UNORDERED,
            }
        )
    }
}

impl FromStr for Ordering {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            KW_ORDERING_ORDERED => Ok(Self::Ordered),
            KW_ORDERING_UNORDERED => Ok(Self::Unordered),
            _ => panic!(),
        }
    }
}

// ------------------------------------------------------------------------------------------------

impl Default for Uniqueness {
    fn default() -> Self {
        Self::Nonunique
    }
}

impl Display for Uniqueness {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Unique => KW_UNIQUENESS_UNIQUE,
                Self::Nonunique => KW_UNIQUENESS_NONUNIQUE,
            }
        )
    }
}

impl FromStr for Uniqueness {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            KW_UNIQUENESS_UNIQUE => Ok(Self::Unique),
            KW_UNIQUENESS_NONUNIQUE => Ok(Self::Nonunique),
            _ => panic!(),
        }
    }
}