ion-schema 0.15.0

Implementation of Amazon Ion Schema
Documentation
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
use crate::ion_path::IonPath;
use std::fmt;
use std::fmt::Formatter;
use thiserror::Error;

/// Represents [Violation] found during validation with detailed error message, error code and the constraint for which the validation failed
/// Equivalence of `Violation` is not supported due to its tree structure of having children `Violation`s.
/// Please use macro `assert_equivalent_violations!(violation1, violation2)` for comparing if two violations are equal.
/// This macro uses `flattened_violations` and does not depend on the order of the children `Violation`s.
/// For non-equivalent violations use macro `assert_non_equivalent_violations!(violation1, violation2)`.
#[derive(Debug, Clone, Error)]
pub struct Violation {
    constraint: String,  // represents the constraint that created this violation
    code: ViolationCode, // represents an error code that indicates the type of the violation
    message: String,     // represents the detailed error message for this violation
    ion_path: IonPath,   // represents the path to Ion value for which violation occurred
    violations: Vec<Violation>,
}

impl Violation {
    pub fn new<A: AsRef<str>, B: AsRef<str>>(
        constraint: A,
        code: ViolationCode,
        message: B,
        ion_path: &mut IonPath,
    ) -> Self {
        Self {
            constraint: constraint.as_ref().to_owned(),
            code,
            message: message.as_ref().to_owned(),
            ion_path: ion_path.to_owned(),
            violations: Vec::new(),
        }
    }

    pub fn with_violations<A: AsRef<str>, B: AsRef<str>>(
        constraint: A,
        code: ViolationCode,
        message: B,
        ion_path: &mut IonPath,
        violations: Vec<Violation>,
    ) -> Self {
        Self {
            constraint: constraint.as_ref().to_owned(),
            code,
            message: message.as_ref().to_owned(),
            ion_path: ion_path.to_owned(),
            violations,
        }
    }

    pub fn ion_path(&self) -> &IonPath {
        &self.ion_path
    }

    pub fn message(&self) -> &String {
        &self.message
    }

    pub fn code(&self) -> &ViolationCode {
        &self.code
    }

    /// Provides flattened list of leaf violations which represent the root cause of the top-level violation.
    pub fn flattened_violations(&self) -> Vec<&Violation> {
        let mut flattened_violations = Vec::new();
        self.flatten_violations(&mut flattened_violations);
        flattened_violations
    }

    fn flatten_violations<'a>(&'a self, flattened: &mut Vec<&'a Violation>) {
        if self.violations.is_empty() {
            flattened.push(self);
        }
        for violation in &self.violations {
            if violation.violations.is_empty() {
                flattened.push(violation);
            } else {
                violation.flatten_violations(flattened)
            }
        }
    }

    pub fn violations(&self) -> impl Iterator<Item = &Violation> {
        self.violations.iter()
    }
}

impl fmt::Display for Violation {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(self.message.as_str())?;

        let mut stack = vec![];
        let mut violations_iter = self.violations.iter();
        let mut violation = violations_iter.next();

        let mut indent = "  ".to_string();

        while let Some(v) = violation {
            f.write_fmt(format_args!("\n{}- {}", &indent, v.message))?;

            if !v.violations.is_empty() {
                stack.push(violations_iter);
                violations_iter = v.violations.iter();
                indent.push_str("  ");
            }
            violation = violations_iter.next();
            while violation.is_none() && !stack.is_empty() {
                violations_iter = stack.pop().unwrap();
                indent.truncate(indent.len() - 2);
                violation = violations_iter.next();
            }
        }
        Ok(())
    }
}

/// Represents violation code that indicates the type of the violation
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ViolationCode {
    AllTypesNotMatched,
    AnnotationMismatched,
    ElementMismatched,     // this is used for mismatched elements in containers
    ElementNotDistinct,    // this is used for elements that are not distinct in containers
    FieldNamesMismatched,  // this is used for mismatched field names in a struct
    FieldNamesNotDistinct, // this is used for field names that are not distinct in a struct
    FieldsNotMatched,
    InvalidIeee754Float, // this is used for ieee754_float constraint
    InvalidLength, // this is used for any length related constraints (e.g. container_length, byte_length, codepoint_length)
    InvalidNull,   // if the value is a null for type references that doesn't allow null
    InvalidOpenContent, // if a container contains open content when `content: closed` is specified
    InvalidValue,  // this is used for valid_values constraint
    MissingAnnotation, // if the annotation is missing for annotations constraint
    MissingValue,  // if the ion value is missing for a particular constraint
    MoreThanOneTypeMatched,
    NoTypesMatched,
    RegexMismatched, // this is used for regex constraint
    TypeConstraintsUnsatisfied,
    TypeMatched,
    TypeMismatched,
    UnexpectedAnnotation, // if unexpected annotation is found for annotations constraint
}

impl fmt::Display for ViolationCode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                ViolationCode::AllTypesNotMatched => "all_types_not_matched",
                ViolationCode::AnnotationMismatched => "annotation_mismatched",
                ViolationCode::ElementMismatched => "element_mismatched",
                ViolationCode::ElementNotDistinct => "element_not_distinct",
                ViolationCode::FieldNamesMismatched => "field_names_mismatched",
                ViolationCode::FieldNamesNotDistinct => "field_names_not_distinct",
                ViolationCode::FieldsNotMatched => "fields_not_matched",
                ViolationCode::InvalidIeee754Float => "invalid_ieee754_float",
                ViolationCode::InvalidLength => "invalid_length",
                ViolationCode::InvalidNull => "invalid_null",
                ViolationCode::InvalidOpenContent => "invalid_open_content",
                ViolationCode::InvalidValue => "invalid_value",
                ViolationCode::MissingAnnotation => "missing_annotation",
                ViolationCode::MissingValue => "missing_value",
                ViolationCode::MoreThanOneTypeMatched => "more_than_one_type_matched",
                ViolationCode::NoTypesMatched => "no_types_matched",
                ViolationCode::RegexMismatched => "regex_mismatched",
                ViolationCode::TypeConstraintsUnsatisfied => "type_constraints_unsatisfied",
                ViolationCode::TypeMatched => "type_matched",
                ViolationCode::TypeMismatched => "type_mismatched",
                ViolationCode::UnexpectedAnnotation => "unexpected_annotation",
            }
        )
    }
}

#[macro_export]
/// Equivalence for `Violation`s is not supported due to its tree structure of having children violations.
/// This macro can be used for comparing if two violations are equal and uses `flattened_violations` for the comparison.
macro_rules! assert_equivalent_violations {
    ($left:expr, $right:expr $(,)?) => {
        let mut left_strings: Vec<String> = $left
                .flattened_violations()
                .into_iter()
                .map(|x| format!("{:?}", x))
                .collect();
        left_strings.sort();
        let mut right_strings: Vec<String> = $right
                .flattened_violations()
                .into_iter()
                .map(|x| format!("{:?}", x))
                .collect();
        right_strings.sort();
        assert_eq!(left_strings, right_strings);
    };
    ($left:expr, $right:expr, $($arg:tt)+) => {
        let mut left_strings: Vec<String> = $left
                .flattened_violations()
                .into_iter()
                .map(|x| format!("{:?}", x))
                .collect();
        left_strings.sort();
        let mut right_strings: Vec<String> = $right
                .flattened_violations()
                .into_iter()
                .map(|x| format!("{:?}", x))
                .collect();
        right_strings.sort();
        assert_eq!(left_strings, right_strings, $($arg)+);
    };
}

#[macro_export]

/// Equivalence for `Violation`s is not supported due to its tree structure of having children violations.
/// This macro can be used for comparing if two violations are not equal and uses `flattened_violations` for the comparison.
macro_rules! assert_non_equivalent_violations {
    ($left:expr, $right:expr $(,)?) => {
        let mut left_strings: Vec<String> = $left
                .flattened_violations()
                .into_iter()
                .map(|x| format!("{:?}", x))
                .collect();
        left_strings.sort();
        let mut right_strings: Vec<String> = $right
                .flattened_violations()
                .into_iter()
                .map(|x| format!("{:?}", x))
                .collect();
        right_strings.sort();
        assert_ne!(left_strings, right_strings);
    };
    ($left:expr, $right:expr, $($arg:tt)+) => {
        let mut left_strings: Vec<String> = $left
                .flattened_violations()
                .into_iter()
                .map(|x| format!("{:?}", x))
                .collect();
        left_strings.sort();
        let mut right_strings: Vec<String> = $right
                .flattened_violations()
                .into_iter()
                .map(|x| format!("{:?}", x))
                .collect();
        right_strings.sort();
        assert_ne!(left_strings, right_strings, $($arg)+);
    };
}

#[cfg(test)]
mod violation_tests {
    use crate::ion_path::{IonPath, IonPathElement};
    use crate::violation::{Violation, ViolationCode};
    use rstest::rstest;

    #[rstest(violation1, violation2,
    case::unordered_violations(Violation::with_violations(
            "type_constraint",
            ViolationCode::TypeMismatched,
            "type mismatched",
            &mut IonPath::default(),
            vec![
                Violation::new(
                    "regex",
                    ViolationCode::RegexMismatched,
                    "regex mismatched",
                    &mut IonPath::default(),
                ),
                Violation::new(
                    "container_length",
                    ViolationCode::InvalidLength,
                    "invalid length",
                    &mut IonPath::default(),
                ),
            ],
        ), Violation::with_violations(
            "type_constraint",
            ViolationCode::TypeMismatched,
            "type mismatched",
            &mut IonPath::default(),
            vec![
                Violation::new(
                    "container_length",
                    ViolationCode::InvalidLength,
                    "invalid length",
                    &mut IonPath::default(),
                ),
                Violation::new(
                    "regex",
                    ViolationCode::RegexMismatched,
                    "regex mismatched",
                    &mut IonPath::default(),
                ),
            ],
        )
    ),
    case::nested_violations(
        Violation::with_violations(
            "type_constraint",
            ViolationCode::TypeMismatched,
            "type mismatched",
            &mut IonPath::default(),
            vec![
                Violation::with_violations(
                    "regex",
                    ViolationCode::RegexMismatched,
                    "regex mismatched",
                    &mut IonPath::default(),
                    vec![
                        Violation::new(
                            "container_length",
                            ViolationCode::InvalidLength,
                            "invalid length",
                            &mut IonPath::default(),
                        ),
                        Violation::new(
                            "codepoint_length",
                            ViolationCode::InvalidLength,
                            "invalid length",
                            &mut IonPath::default(),
                        )
                    ]
                )
            ],
        ),
        Violation::with_violations(
            "type_constraint",
            ViolationCode::TypeMismatched,
            "type mismatched",
            &mut IonPath::default(),
            vec![
                Violation::with_violations(
                    "regex",
                    ViolationCode::RegexMismatched,
                    "regex mismatched",
                    &mut IonPath::default(),
                    vec![
                        Violation::new(
                            "codepoint_length",
                            ViolationCode::InvalidLength,
                            "invalid length",
                            &mut IonPath::default(),
                        ),
                        Violation::new(
                            "container_length",
                            ViolationCode::InvalidLength,
                            "invalid length",
                            &mut IonPath::default(),
                        )
                    ]
                )
            ],
        )
    ),
    case::empty_violations(
        Violation::with_violations(
            "type_constraint",
            ViolationCode::TypeMismatched,
            "type mismatched",
            &mut IonPath::default(),
            vec![],
        ),
        Violation::with_violations(
            "type_constraint",
            ViolationCode::TypeMismatched,
            "type mismatched",
            &mut IonPath::default(),
            vec![],
        )
    ),
    case::multiple_violations_from_one_constraint(
        Violation::with_violations(
        "type_constraint",
        ViolationCode::TypeMismatched,
        "type mismatched",
        &mut IonPath::default(),
        vec![
            Violation::new(
                "element",
                ViolationCode::ElementMismatched,
                "element mismatched",
                &mut IonPath::default(),
            ),
            Violation::new(
                "element",
                ViolationCode::ElementNotDistinct,
                "element not distinct",
                &mut IonPath::default(),
            ),
        ],
        ),
    Violation::with_violations(
        "type_constraint",
        ViolationCode::TypeMismatched,
        "type mismatched",
        &mut IonPath::default(),
        vec![
            Violation::new(
                "element",
                ViolationCode::ElementNotDistinct,
                "element not distinct",
                &mut IonPath::default(),
            ),
            Violation::new(
                "element",
                ViolationCode::ElementMismatched,
                "element mismatched",
                &mut IonPath::default(),
            ),
        ],
        ),
    )
    )]
    fn violation_equivalence(violation1: Violation, violation2: Violation) {
        assert_equivalent_violations!(violation1, violation2);
    }

    #[rstest(violation1, violation2,
    case::different_violations(
        Violation::with_violations(
            "type_constraint",
            ViolationCode::TypeMismatched,
            "type mismatched",
            &mut IonPath::default(),
            vec![
                Violation::new(
                    "regex",
                    ViolationCode::RegexMismatched,
                    "regex mismatched",
                    &mut IonPath::default(),
                ),
                Violation::new(
                    "container_length",
                    ViolationCode::InvalidLength,
                    "invalid length",
                    &mut IonPath::default(),
                ),
            ],
        ), Violation::with_violations(
            "type_constraint",
            ViolationCode::TypeMismatched,
            "type mismatched",
            &mut IonPath::default(),
            vec![
            Violation::new(
                "container_length",
                ViolationCode::InvalidLength,
                "invalid length",
                &mut IonPath::default(),
            ),
            ],
        )
    ),
    case::different_constraints(
        Violation::new(
            "type_constraint",
            ViolationCode::TypeMismatched,
            "type mismatched",
            &mut IonPath::default(),
        ),
        Violation::new(
            "regex",
            ViolationCode::TypeMismatched,
            "type mismatched",
            &mut IonPath::default(),
        )
    ),
    case::different_violation_code(
        Violation::new(
            "type_constraint",
            ViolationCode::TypeMismatched,
            "type mismatched",
            &mut IonPath::default(),
        ),
        Violation::new(
            "type_constraint",
            ViolationCode::RegexMismatched,
            "type mismatched",
            &mut IonPath::default(),
        )
    ),
    case::different_violation_message(
        Violation::new(
            "type_constraint",
            ViolationCode::TypeMismatched,
            "regex mismatched",
            &mut IonPath::default(),
        ),
        Violation::new(
            "type_constraint",
            ViolationCode::TypeMismatched,
            "type mismatched",
            &mut IonPath::default(),
        )
    ),
    case::different_ion_path(
        Violation::new(
            "type_constraint",
            ViolationCode::TypeMismatched,
            "type mismatched",
            &mut IonPath::new(vec![IonPathElement::Index(2)]),
        ),
        Violation::new(
            "type_constraint",
            ViolationCode::TypeMismatched,
            "type mismatched",
            &mut IonPath::default(),
        )
    ))]
    fn non_equivalent_violations(violation1: Violation, violation2: Violation) {
        assert_non_equivalent_violations!(violation1, violation2);
    }
}