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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
use crate::constraint::Constraint;
use crate::isl::isl_constraint::IslConstraint;
use crate::isl::isl_range::Range;
use crate::isl::isl_type::IslTypeImpl;
use crate::result::{IonSchemaResult, ValidationResult};
use crate::system::{PendingTypes, TypeId, TypeStore};
use crate::violation::{Violation, ViolationCode};
use crate::IonSchemaElement;
use ion_rs::value::owned::{text_token, OwnedElement};
use ion_rs::value::{Builder, Element};
use ion_rs::IonType;
use std::rc::Rc;

/// Provides validation for [`TypeDefinition`]
pub trait TypeValidator {
    /// If the specified value violates one or more of this type's constraints,
    /// returns `false`, otherwise `true`
    fn is_valid(&self, value: &IonSchemaElement, type_store: &TypeStore) -> bool;

    /// Returns `Err(violation)` with details as to which constraints were violated,
    /// otherwise returns `Ok(())` indicating no violations were found during the validation
    fn validate(&self, value: &IonSchemaElement, type_store: &TypeStore) -> ValidationResult;
}

// Provides a public facing schema type which has a reference to TypeStore
// to get the underlying TypeDefinition from TypeStore
#[derive(Debug, Clone)]
pub struct TypeRef {
    id: TypeId,
    type_store: Rc<TypeStore>,
}

impl TypeRef {
    pub fn new(id: TypeId, type_store: Rc<TypeStore>) -> Self {
        Self { id, type_store }
    }

    pub fn id(&self) -> TypeId {
        self.id
    }

    /// Provides the validation for the given value based on this schema type
    /// ```
    /// use ion_rs::value::owned::OwnedElement;
    /// use ion_schema::IonSchemaElement;
    /// use ion_schema::authority::{FileSystemDocumentAuthority, DocumentAuthority};
    /// use ion_schema::system::SchemaSystem;
    /// use ion_schema::result::IonSchemaResult;
    /// use std::path::Path;
    ///
    /// fn main() -> IonSchemaResult<()> {
    ///     // create an IonSchemaElement from an OwnedElement
    ///     use ion_schema::authority::MapDocumentAuthority;
    ///     let owned_element: OwnedElement = 4.into();
    ///     let document: Vec<OwnedElement> = vec![4.into(), "hello".to_string().into(), true.into()];
    ///
    ///     let map_authority = [
    ///         (
    ///            "sample.isl",
    ///             r#"
    ///                 type::{
    ///                     name: "my_int",
    ///                     type: int,
    ///                 }
    ///             "#
    ///         )   
    ///     ];
    ///
    ///     // create a vector of authorities and construct schema system
    ///     // this example uses above mentioned map as the authority
    ///     let authorities: Vec<Box<dyn DocumentAuthority>> = vec![Box::new(
    ///             MapDocumentAuthority::new(map_authority),
    ///         )];
    ///     let mut schema_system = SchemaSystem::new(authorities);
    ///
    ///     // use this schema_system to load a schema as following
    ///     let schema = schema_system.load_schema("sample.isl")?;
    ///
    ///     // unwrap() here because we know that the `my_int` type exists in sample.isl
    ///     let type_ref = schema.get_type("my_int").unwrap();
    ///
    ///     assert!(type_ref.validate(&owned_element).is_ok()); // 4 is valid for `my_int`
    ///     assert!(type_ref.validate(&document).is_err()); // document type is invalid for `my_int` type
    ///     Ok(())
    /// }
    /// ```
    pub fn validate<I: Into<IonSchemaElement>>(&self, value: I) -> ValidationResult {
        let mut violations: Vec<Violation> = vec![];
        let type_def = self.type_store.get_type_by_id(self.id).unwrap();
        let type_name = match type_def {
            TypeDefinition::Named(named_type) => named_type.name().as_ref().unwrap().to_owned(),
            TypeDefinition::Anonymous(anonymous_type) => "".to_owned(),
            TypeDefinition::BuiltIn(builtin_isl_type) => match builtin_isl_type {
                BuiltInTypeDefinition::Atomic(ion_type, is_nullable) => match is_nullable {
                    Nullability::Nullable => format!("${}", ion_type),
                    Nullability::NotNullable => format!("{}", ion_type),
                },
                BuiltInTypeDefinition::Derived(other_type) => other_type.name().to_owned().unwrap(),
            },
        };

        // convert given IonSchemaElement to an OwnedElement
        let schema_element: IonSchemaElement = value.into();

        for constraint in type_def.constraints() {
            if let Err(violation) = constraint.validate(&schema_element, &self.type_store) {
                violations.push(violation);
            }
        }

        if violations.is_empty() {
            return Ok(());
        }
        Err(Violation::with_violations(
            type_name.as_str(),
            ViolationCode::TypeConstraintsUnsatisfied,
            "value didn't satisfy type constraint(s)",
            violations,
        ))
    }
}

/// Represents a [`BuiltInTypeDefinition`] which stores a resolved builtin ISl type using [`TypeStore`]
#[derive(Debug, Clone, PartialEq)]
pub enum BuiltInTypeDefinition {
    Atomic(IonType, Nullability),
    Derived(TypeDefinitionImpl),
}

/// Represents whether an atomic built-in type is nullable or not
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Nullability {
    Nullable,
    NotNullable,
}

impl BuiltInTypeDefinition {
    pub fn parse_from_isl_type(
        isl_type: &IslTypeImpl,
        type_store: &mut TypeStore,
        pending_types: &mut PendingTypes,
    ) -> IonSchemaResult<Self> {
        let mut constraints = vec![];

        // parses an isl_type to a TypeDefinition
        let type_name = isl_type.name();

        // convert IslConstraint to Constraint
        for isl_constraint in isl_type.constraints() {
            // For built in types, open_content is set as true as Ion Schema by default allows open content
            let constraint = Constraint::resolve_from_isl_constraint(
                isl_constraint,
                type_store,
                pending_types,
                true,
            )?;
            constraints.push(constraint);
        }

        let builtin_type_def = BuiltInTypeDefinition::Derived(TypeDefinitionImpl::new(
            type_name.to_owned(),
            constraints,
        ));
        Ok(builtin_type_def)
    }
}

/// Represents a [`TypeDefinition`] which stores a resolved ISL type using [`TypeStore`]
#[derive(Debug, Clone, PartialEq)]
pub enum TypeDefinition {
    Named(TypeDefinitionImpl),
    Anonymous(TypeDefinitionImpl),
    BuiltIn(BuiltInTypeDefinition),
}

impl TypeDefinition {
    /// Creates a named [`TypeDefinition`] using the [`IslConstraint`] defined within it
    pub fn named<A: Into<String>, B: Into<Vec<Constraint>>>(
        name: A,
        constraints: B,
    ) -> TypeDefinition {
        TypeDefinition::Named(TypeDefinitionImpl::new(
            Some(name.into()),
            constraints.into(),
        ))
    }

    /// Creates an anonymous [`TypeDefinition`] using the [`IslConstraint`] defined within it
    pub fn anonymous<A: Into<Vec<Constraint>>>(constraints: A) -> TypeDefinition {
        TypeDefinition::Anonymous(TypeDefinitionImpl::new(None, constraints.into()))
    }

    /// Provides the underlying constraints of [`TypeDefinitionImpl`]
    pub fn constraints(&self) -> &[Constraint] {
        match &self {
            TypeDefinition::Named(named_type) => named_type.constraints(),
            TypeDefinition::Anonymous(anonymous_type) => anonymous_type.constraints(),
            _ => &[],
        }
    }

    /// Returns an occurs constraint as range if it exists in the [`TypeDefinition`] otherwise returns `occurs: required`
    pub fn get_occurs_constraint(&self, validation_constraint_name: &str) -> Range {
        // verify if the type_def contains `occurs` constraint and fill occurs_range
        // Otherwise if there is no `occurs` constraint specified then use `occurs: required`
        if let Some(Constraint::Occurs(occurs)) = self
            .constraints()
            .iter()
            .find(|c| matches!(c, Constraint::Occurs(_)))
        {
            return occurs.occurs_range().to_owned();
        }
        // by default, if there is no `occurs` constraint for given type_def
        // then use `occurs:optional` if its `fields` constraint validation
        // otherwise, use `occurs: required` if its `ordered_elements` constraint validation
        if validation_constraint_name == "fields" {
            return Range::optional();
        }
        Range::required()
    }
}

impl TypeValidator for TypeDefinition {
    fn is_valid(&self, value: &IonSchemaElement, type_store: &TypeStore) -> bool {
        let violation = self.validate(value, type_store);
        violation.is_ok()
    }

    fn validate(&self, value: &IonSchemaElement, type_store: &TypeStore) -> ValidationResult {
        match self {
            TypeDefinition::Named(named_type) => named_type.validate(value, type_store),
            TypeDefinition::Anonymous(anonymous_type) => anonymous_type.validate(value, type_store),
            TypeDefinition::BuiltIn(built_in_type) => match built_in_type {
                BuiltInTypeDefinition::Atomic(ion_type, is_nullable) => {
                    // atomic types doesn't include document type
                    match value {
                        IonSchemaElement::SingleElement(element) => {
                            if *is_nullable == Nullability::NotNullable && element.is_null() {
                                return Err(Violation::new(
                                    "type_constraint",
                                    ViolationCode::InvalidNull,
                                    &format!("expected type {:?} doesn't allow null", ion_type),
                                ));
                            }
                            if element.ion_type() != *ion_type {
                                return Err(Violation::new(
                                    "type_constraint",
                                    ViolationCode::TypeMismatched,
                                    &format!(
                                        "expected type {:?}, found {:?}",
                                        ion_type,
                                        element.ion_type()
                                    ),
                                ));
                            }

                            Ok(())
                        }
                        IonSchemaElement::Document(document) => Err(Violation::new(
                            "type_constraint",
                            ViolationCode::TypeMismatched,
                            &format!("expected type {:?}, found document", ion_type),
                        )),
                    }
                }
                BuiltInTypeDefinition::Derived(other_type) => {
                    if other_type.name() == &Some("document".to_owned()) {
                        // Verify whether the given derived type is document
                        // And check if it is using enum variant IonSchemaElement::Document
                        if value.as_document() == None {
                            return Err(Violation::new(
                                "type_constraint",
                                ViolationCode::TypeMismatched,
                                &format!(
                                    "expected type document found {:?}",
                                    value.as_element().unwrap().ion_type()
                                ),
                            ));
                        }
                        return Ok(());
                    }
                    // if it is not a document type do validation using the type definition
                    other_type.validate(value, type_store)
                }
            },
        }
    }
}

/// A [`TypeDefinitionImpl`] consists of an optional name and zero or more constraints.
#[derive(Debug, Clone)]
pub struct TypeDefinitionImpl {
    name: Option<String>,
    constraints: Vec<Constraint>,
}

impl TypeDefinitionImpl {
    pub fn new(name: Option<String>, constraints: Vec<Constraint>) -> Self {
        Self { name, constraints }
    }

    pub fn name(&self) -> &Option<String> {
        &self.name
    }

    pub fn with_name(self, alias: String) -> Self {
        Self {
            name: Some(alias),
            constraints: self.constraints,
        }
    }

    pub fn constraints(&self) -> &[Constraint] {
        &self.constraints
    }

    /// Parse constraints inside an [`IslTypeImpl`] to a schema type definition, update the [`PendingTypes`]
    /// and return its [`TypeId`] if the conversion was successful, otherwise return an [`IonSchemaError`]
    ///
    /// [`IonSchemaError`]: crate::result::IonSchemaError
    pub fn parse_from_isl_type_and_update_pending_types(
        isl_type: &IslTypeImpl,
        type_store: &mut TypeStore,
        pending_types: &mut PendingTypes,
    ) -> IonSchemaResult<TypeId> {
        let mut constraints = vec![];

        // parses an isl_type to a TypeDefinition
        let type_name = isl_type.name();

        // add parent information for named type
        if type_name.is_some() {
            pending_types.add_parent(type_name.to_owned().unwrap(), type_store);
        }

        // add this unresolved type to context for type_id
        let type_id = pending_types.add_type(type_store);

        // convert IslConstraint to Constraint
        let mut found_type_constraint = false;
        for isl_constraint in isl_type.constraints() {
            if let IslConstraint::Type(_) = isl_constraint {
                found_type_constraint = true;
            }

            let constraint = Constraint::resolve_from_isl_constraint(
                isl_constraint,
                type_store,
                pending_types,
                isl_type.open_content(),
            )?;
            constraints.push(constraint);
        }

        // add `type: any` as a default type constraint if there is no type constraint found
        if !found_type_constraint {
            // set the isl type name for any error that is returned while parsing its constraints
            let isl_type_name = match type_name.to_owned() {
                Some(name) => name,
                None => "".to_owned(),
            };

            let isl_constraint = IslConstraint::from_ion_element(
                "type",
                &OwnedElement::new_symbol(text_token("any")),
                &isl_type_name,
                &mut vec![],
            )?;
            let constraint = Constraint::resolve_from_isl_constraint(
                &isl_constraint,
                type_store,
                pending_types,
                true, // by default Ion Schema allows open content
            )?;
            constraints.push(constraint);
        }

        let type_def = TypeDefinitionImpl::new(type_name.to_owned(), constraints);

        // actual type id is the type id with respect to type store length
        let actual_type_id;

        if type_name.is_some() {
            // update with this resolved type_def to context for type_id
            actual_type_id = pending_types.update_named_type(
                type_id,
                type_name.as_ref().unwrap(),
                type_def,
                type_store,
            );

            // clear parent information from type_store as the type is already added in the type_store now
            pending_types.clear_parent();
        } else {
            // update with this resolved type_def to context for type_id
            actual_type_id = pending_types.update_anonymous_type(type_id, type_def, type_store);
        }

        Ok(actual_type_id)
    }
}

impl PartialEq for TypeDefinitionImpl {
    fn eq(&self, other: &Self) -> bool {
        self.name() == other.name() && self.constraints == other.constraints()
    }
}

impl TypeValidator for TypeDefinitionImpl {
    fn is_valid(&self, value: &IonSchemaElement, type_store: &TypeStore) -> bool {
        let violation = self.validate(value, type_store);
        violation.is_ok()
    }

    fn validate(&self, value: &IonSchemaElement, type_store: &TypeStore) -> ValidationResult {
        let mut violations: Vec<Violation> = vec![];
        let type_name = match self.name() {
            None => "",
            Some(name) => name,
        };
        for constraint in self.constraints() {
            if let Err(violation) = constraint.validate(value, type_store) {
                violations.push(violation);
            }
        }
        if violations.is_empty() {
            return Ok(());
        }
        Err(Violation::with_violations(
            type_name,
            ViolationCode::TypeConstraintsUnsatisfied,
            "value didn't satisfy type constraint(s)",
            violations,
        ))
    }
}

#[cfg(test)]
mod type_definition_tests {
    use super::*;
    use crate::constraint::Constraint;
    use crate::isl::isl_constraint::IslConstraint;
    use crate::isl::isl_range::Number;
    use crate::isl::isl_range::NumberRange;
    use crate::isl::isl_type::IslType;
    use crate::isl::isl_type_reference::IslTypeRef;
    use crate::system::PendingTypes;
    use ion_rs::Decimal;
    use ion_rs::Integer;
    use rstest::*;

    // TODO: Remove type ids for assertion to make tests more readable
    #[rstest(
    isl_type, type_def,
    case::type_constraint_with_anonymous_type(
        /* For a schema with single anonymous type as below:
            { type: int }
         */
        IslType::anonymous([IslConstraint::type_constraint(IslTypeRef::named("int"))]),
        TypeDefinition::anonymous([Constraint::type_constraint(0)])
    ),
    case::type_constraint_with_named_type(
        /* For a schema with named type as below:
            { name: my_int, type: int }
         */
        IslType::named("my_int", [IslConstraint::type_constraint(IslTypeRef::named("int"))]),
        TypeDefinition::named("my_int", [Constraint::type_constraint(0)])
    ),
    case::type_constraint_with_self_reference_type(
        /* For a schema with self reference type as below:
            { name: my_int, type: my_int }
         */
        IslType::named("my_int", [IslConstraint::type_constraint(IslTypeRef::named("my_int"))]),
        TypeDefinition::named("my_int", [Constraint::type_constraint(35)])
    ),
    case::type_constraint_with_nested_self_reference_type(
        /* For a schema with nested self reference type as below:
            { name: my_int, type: { type: my_int } }
         */
        IslType::named("my_int", [IslConstraint::type_constraint(IslTypeRef::anonymous([IslConstraint::type_constraint(IslTypeRef::named("my_int"))]))]),
        TypeDefinition::named("my_int", [Constraint::type_constraint(36)]) // 0-35 are built-in types which are preloaded to the type_store
    ),
    case::type_constraint_with_nested_type(
        /* For a schema with nested types as below:
            { name: my_int, type: { type: int } }
         */
        IslType::named("my_int", [IslConstraint::type_constraint(IslTypeRef::anonymous([IslConstraint::type_constraint(IslTypeRef::named("int"))]))]),
        TypeDefinition::named("my_int", [Constraint::type_constraint(36)])
    ),
    case::type_constraint_with_nested_multiple_types(
        /* For a schema with nested multiple types as below:
            { name: my_int, type: { type: int }, type: { type: my_int } }
         */
        IslType::named("my_int", [IslConstraint::type_constraint(IslTypeRef::anonymous([IslConstraint::type_constraint(IslTypeRef::named("int"))])), IslConstraint::type_constraint(IslTypeRef::anonymous([IslConstraint::type_constraint(IslTypeRef::named("my_int"))]))]),
        TypeDefinition::named("my_int", [Constraint::type_constraint(36), Constraint::type_constraint(37)])
    ),
    case::all_of_constraint(
        /* For a schema with all_of type as below:
            { all_of: [{ type: int }] }
        */
        IslType::anonymous([IslConstraint::all_of([IslTypeRef::anonymous([IslConstraint::type_constraint(IslTypeRef::named("int"))])])]),
        TypeDefinition::anonymous([Constraint::all_of([36]), Constraint::type_constraint(34)])
    ),
    case::any_of_constraint(
        /* For a schema with any_of constraint as below:
            { any_of: [{ type: int }, { type: decimal }] }
        */
        IslType::anonymous([IslConstraint::any_of([IslTypeRef::anonymous([IslConstraint::type_constraint(IslTypeRef::named("int"))]), IslTypeRef::anonymous([IslConstraint::type_constraint(IslTypeRef::named("decimal"))])])]),
        TypeDefinition::anonymous([Constraint::any_of([36, 37]), Constraint::type_constraint(34)])
    ),
    case::one_of_constraint(
        /* For a schema with one_of constraint as below:
            { any_of: [{ type: int }, { type: decimal }] }
        */
        IslType::anonymous([IslConstraint::one_of([IslTypeRef::anonymous([IslConstraint::type_constraint(IslTypeRef::named("int"))]), IslTypeRef::anonymous([IslConstraint::type_constraint(IslTypeRef::named("decimal"))])])]),
        TypeDefinition::anonymous([Constraint::one_of([36, 37]), Constraint::type_constraint(34)])
    ),
    case::not_constraint(
        /* For a schema with not constraint as below:
            { not: { type: int } }
        */
        IslType::anonymous([IslConstraint::not(IslTypeRef::anonymous([IslConstraint::type_constraint(IslTypeRef::named("int"))]))]),
        TypeDefinition::anonymous([Constraint::not(36), Constraint::type_constraint(34)])
    ),
    case::ordered_elements_constraint(
        /* For a schema with ordered_elements constraint as below:
            { ordered_elements: [ symbol, { type: int, occurs: optional }, ] }
        */
        IslType::anonymous([IslConstraint::ordered_elements([IslTypeRef::named("symbol"), IslTypeRef::anonymous([IslConstraint::type_constraint(IslTypeRef::named("int")), IslConstraint::Occurs(Range::optional())])])]),
        TypeDefinition::anonymous([Constraint::ordered_elements([5, 36]), Constraint::type_constraint(34)])
    ),
    case::fields_constraint(
        /* For a schema with fields constraint as below:
            { fields: { name: string, id: int} }
        */
        IslType::anonymous([IslConstraint::fields(vec![("name".to_owned(), IslTypeRef::named("string")), ("id".to_owned(), IslTypeRef::named("int"))].into_iter())]),
        TypeDefinition::anonymous([Constraint::fields(vec![("name".to_owned(), 4), ("id".to_owned(), 0)].into_iter()), Constraint::type_constraint(34)])
    ),
    case::contains_constraint(
        /* For a schema with contains constraint as below:
            { contains: [true, 1, "hello"] }
        */
        IslType::anonymous([IslConstraint::contains([true.into(), 1.into(), "hello".to_owned().into()])]),
        TypeDefinition::anonymous([Constraint::contains([true.into(), 1.into(), "hello".to_owned().into()]), Constraint::type_constraint(34)])
        ),
    case::container_length_constraint(
        /* For a schema with container_length constraint as below:
            { container_length: 3 }
        */
        IslType::anonymous([IslConstraint::container_length(3.into())]),
        TypeDefinition::anonymous([Constraint::container_length(3.into()), Constraint::type_constraint(34)])
    ),
    case::byte_length_constraint(
        /* For a schema with byte_length constraint as below:
            { byte_length: 3 }
        */
        IslType::anonymous([IslConstraint::byte_length(3.into())]),
        TypeDefinition::anonymous([Constraint::byte_length(3.into()), Constraint::type_constraint(34)])
    ),
    case::codepoint_length_constraint(
        /* For a schema with codepoint_length constraint as below:
            { codepoint_length: 3 }
        */
        IslType::anonymous([IslConstraint::codepoint_length(3.into())]),
        TypeDefinition::anonymous([Constraint::codepoint_length(3.into()), Constraint::type_constraint(34)])
    ),
    case::element_constraint(
        /* For a schema with element constraint as below:
            { element: int }
        */
        IslType::anonymous([IslConstraint::element(IslTypeRef::named("int"))]),
        TypeDefinition::anonymous([Constraint::element(0), Constraint::type_constraint(34)])
    ),
    case::annotations_constraint(
        /* For a schema with annotations constraint as below:
            { annotations: closed::[red, blue, green] }
        */
        IslType::anonymous([IslConstraint::annotations(vec!["closed"], vec![text_token("red").into(), text_token("blue").into(), text_token("green").into()])]),
        TypeDefinition::anonymous([Constraint::annotations(vec!["closed"], vec![text_token("red").into(), text_token("blue").into(), text_token("green").into()]), Constraint::type_constraint(34)])
    ),
    case::precision_constraint(
        /* For a schema with precision constraint as below:
            { precision: 3 }
        */
        IslType::anonymous([IslConstraint::precision(3.into())]),
        TypeDefinition::anonymous([Constraint::precision(3.into()), Constraint::type_constraint(34)])
    ),
    case::scale_constraint(
        /* For a schema with scale constraint as below:
            { scale: 2 }
        */
        IslType::anonymous([IslConstraint::scale(Integer::I64(2).into())]),
        TypeDefinition::anonymous([Constraint::scale(Integer::I64(2).into()), Constraint::type_constraint(34)])
    ),
    case::timestamp_precision_constraint(
        /* For a schema with timestamp_precision constraint as below:
            { timestamp_precision: month }
        */
        IslType::anonymous([IslConstraint::timestamp_precision("month".try_into().unwrap())]),
        TypeDefinition::anonymous([Constraint::timestamp_precision("month".try_into().unwrap()), Constraint::type_constraint(34)])
    ),
    case::valid_values_constraint(
        /* For a schema with valid_values constraint as below:
            { valid_values: [2, 3.5, 5e7, "hello", hi] }
        */
        IslType::anonymous([IslConstraint::valid_values_with_values(vec![2.into(), Decimal::new(35, -1).into(), 5e7.into(), "hello".to_owned().into(), text_token("hi").into()]).unwrap()]),
        TypeDefinition::anonymous([Constraint::valid_values_with_values(vec![2.into(), Decimal::new(35, -1).into(), 5e7.into(), "hello".to_owned().into(), text_token("hi").into()]).unwrap(), Constraint::type_constraint(34)])
    ),
    case::valid_values_with_range_constraint(
        /* For a schema with valid_values constraint as below:
            { valid_values: range::[1, 5.5] }
        */
        IslType::anonymous(
            [IslConstraint::valid_values_with_range(
                NumberRange::new(
                    Number::from(&Integer::I64(1)),
                    Number::from(&Decimal::new(55, -1))
                ).unwrap().into())
            ]
        ),
        TypeDefinition::anonymous([
            Constraint::valid_values_with_range(
            NumberRange::new(
                Number::from(&Integer::I64(1)),
                Number::from(&Decimal::new(55, -1))
            ).unwrap().into()),
            Constraint::type_constraint(34)
        ])
    ),
    case::regex_constraint(
        /* For a schema with regex constraint as below:
            { regex: "[abc]" }
        */
        IslType::anonymous(
            [IslConstraint::regex(
                false, // case insensitive
                false, // multiline
                "[abc]".to_string()
            )]
        ),
        TypeDefinition::anonymous([
            Constraint::regex(
                false, // case insensitive
                false, // multiline
                "[abc]".to_string()
            ).unwrap(),
            Constraint::type_constraint(34)
        ])
    )
    )]
    fn isl_type_to_type_definition(isl_type: IslType, type_def: TypeDefinition) {
        // assert if both the TypeDefinition are same in terms of constraints and name
        let type_store = &mut TypeStore::default();
        let pending_types = &mut PendingTypes::default();
        let this_type_def = match isl_type {
            IslType::Named(named_isl_type) => {
                let type_id = TypeDefinitionImpl::parse_from_isl_type_and_update_pending_types(
                    &named_isl_type,
                    type_store,
                    pending_types,
                )
                .unwrap();
                pending_types.update_type_store(type_store, None).unwrap();
                type_store.get_type_by_id(type_id).unwrap()
            }
            IslType::Anonymous(anonymous_isl_type) => {
                let type_id = TypeDefinitionImpl::parse_from_isl_type_and_update_pending_types(
                    &anonymous_isl_type,
                    type_store,
                    pending_types,
                )
                .unwrap();
                pending_types.update_type_store(type_store, None).unwrap();
                type_store.get_type_by_id(type_id).unwrap()
            }
        };
        assert_eq!(this_type_def, &type_def);
    }
}