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
// TODO: remove the following line once we have a basic implementation ready
#![allow(dead_code, unused_variables)]

use crate::external::ion_rs::IonType;
use crate::ion_path::IonPath;
use crate::isl::isl_constraint::IslConstraintImpl;
use crate::isl::isl_type::IslTypeImpl;
use crate::result::{invalid_schema_error, IonSchemaResult};
use crate::violation::{Violation, ViolationCode};
use ion_rs::element::{Element, Struct};
use ion_rs::Symbol;
use std::fmt::{Display, Formatter};
/// A [`try`]-like macro to workaround the [`Option`]/[`Result`] nested APIs.
/// These API require checking the type and then calling the appropriate getter function
/// (which returns a None if you got it wrong). This macro turns the `None` into
/// an `IonSchemaError` which cannot be currently done with `?`.
macro_rules! try_to {
    ($getter:expr) => {
        match $getter {
            Some(value) => value,
            None => invalid_schema_error(format!("Missing a value: {}", stringify!($getter)))?,
        }
    };
}

// TODO: consider changing some of these modules to public if required
pub mod authority;
mod constraint;
mod import;
mod ion_path;
pub mod isl;
mod nfa;
pub mod result;
pub mod schema;
pub mod system;
mod type_reference;
pub mod types;
pub mod violation;

/// Re-export of the ion-rs dependency that is part of our public API.
pub mod external {
    pub use ion_rs;
}

/// Provide an Ion schema Element which includes all Elements and a document type
///
/// ## Example:
/// In general `TypeRef` `validate()` takes in IonSchemaElement as the value to be validated.
/// In order to create an `IonSchemaElement`:
///
/// ```
/// use ion_rs::element::Element;
/// use ion_schema::IonSchemaElement;
///
/// // create an IonSchemaElement from an Element
/// let owned_element: Element = 4.into();
/// let ion_schema_element: IonSchemaElement = (&owned_element).into();
///
/// // create an IonSchemaElement for document type based on vector of owned elements
/// let document: IonSchemaElement = IonSchemaElement::Document(vec![owned_element]);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum IonSchemaElement {
    SingleElement(Element),
    Document(Vec<Element>),
}

impl IonSchemaElement {
    pub fn as_element(&self) -> Option<&Element> {
        match self {
            IonSchemaElement::SingleElement(element) => Some(element),
            IonSchemaElement::Document(_) => None,
        }
    }

    pub fn as_document(&self) -> Option<&Vec<Element>> {
        match self {
            IonSchemaElement::SingleElement(_) => None,
            IonSchemaElement::Document(document) => Some(document),
        }
    }

    fn expect_element_of_type(
        &self,
        types: &[IonType],
        constraint_name: &str,
        ion_path: &mut IonPath,
    ) -> Result<&Element, Violation> {
        match self {
            IonSchemaElement::SingleElement(element) => {
                if !types.contains(&element.ion_type()) || element.is_null() {
                    // If it's an Element but the type isn't one of `types`,
                    // return a Violation with the constraint name.
                    return Err(Violation::new(
                        constraint_name,
                        ViolationCode::TypeMismatched,
                        format!("expected {:?} but found {}", types, element.ion_type()),
                        ion_path,
                    ));
                }
                // If it's an Element of an expected type, return a ref to it.
                Ok(element)
            }
            IonSchemaElement::Document(_) => {
                // If it's a Document, return a Violation with the constraint name
                Err(Violation::new(
                    constraint_name,
                    ViolationCode::TypeMismatched,
                    format!("expected {types:?} but found document"),
                    ion_path,
                ))
            }
        }
    }
}

impl Display for IonSchemaElement {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
        match self {
            IonSchemaElement::SingleElement(element) => {
                write!(f, "{element}")
            }
            IonSchemaElement::Document(document) => {
                write!(f, "/* Ion document */ ")?;
                for value in document {
                    write!(f, "{value} ")?;
                }
                write!(f, "/* end */")
            }
        }
    }
}

impl From<&Element> for IonSchemaElement {
    fn from(value: &Element) -> Self {
        if value.annotations().contains("document") {
            let sequence = match value.ion_type() {
                IonType::String => load(value.as_string().unwrap()),
                IonType::List | IonType::SExp => {
                    let ion_elements: Vec<Element> = value
                        .as_sequence()
                        .unwrap()
                        .elements()
                        .map(|oe| oe.to_owned())
                        .collect();
                    ion_elements
                }
                _ => {
                    panic!("invalid document")
                }
            };
            return IonSchemaElement::Document(sequence);
        }
        IonSchemaElement::SingleElement(value.to_owned())
    }
}

impl From<&Vec<Element>> for IonSchemaElement {
    fn from(value: &Vec<Element>) -> Self {
        IonSchemaElement::Document(value.to_owned())
    }
}

// helper function to be used by schema tests
fn load(text: &str) -> Vec<Element> {
    Element::read_all(text.as_bytes()).expect("parsing failed unexpectedly")
}

#[derive(Debug, Clone, Default, PartialEq)]
pub struct UserReservedFields {
    schema_header_fields: Vec<String>,
    schema_footer_fields: Vec<String>,
    type_fields: Vec<String>,
}

impl UserReservedFields {
    /// Parse use reserved fields inside a [Struct]
    pub(crate) fn from_ion_elements(user_reserved_fields: &Struct) -> Self {
        Self {
            schema_header_fields: UserReservedFields::field_names_from_ion_elements(
                "schema_header",
                user_reserved_fields,
            ),
            schema_footer_fields: UserReservedFields::field_names_from_ion_elements(
                "schema_footer",
                user_reserved_fields,
            ),
            type_fields: UserReservedFields::field_names_from_ion_elements(
                "type",
                user_reserved_fields,
            ),
        }
    }

    fn field_names_from_ion_elements(
        user_reserved_fields_type: &str,
        user_reserved_fields: &Struct,
    ) -> Vec<String> {
        let user_reserved_elements: Vec<&Element> = user_reserved_fields
            .get(user_reserved_fields_type)
            .and_then(|it| it.as_sequence().map(|s| s.elements().collect()))
            .unwrap_or(vec![]);

        user_reserved_elements
            .iter()
            .map(|e| e.as_string().map(|s| s.to_owned()))
            .collect::<Option<Vec<String>>>()
            .unwrap_or(vec![])
    }

    pub(crate) fn validate_field_names_in_header(
        &self,
        schema_header: &Struct,
    ) -> IonSchemaResult<()> {
        let unexpected_fields: Vec<(&Symbol, &Element)> = schema_header
            .fields()
            .filter(|(f, v)| {
                !self
                    .schema_header_fields
                    .contains(&f.text().unwrap().to_owned())
                    && f.text().unwrap() != "user_reserved_fields"
            })
            .collect();

        if !unexpected_fields.is_empty() {
            // for unexpected fields return invalid schema error
            return invalid_schema_error(format!(
                "schema header contains unexpected fields: {unexpected_fields:?}"
            ));
        }

        Ok(())
    }

    pub(crate) fn validate_field_names_in_type(
        &self,
        isl_type: &IslTypeImpl,
    ) -> IonSchemaResult<()> {
        let unexpected_fields: &Vec<&String> = &isl_type
            .constraints()
            .iter()
            .filter(|c| matches!(c, IslConstraintImpl::Unknown(_, _)))
            .map(|c| match c {
                IslConstraintImpl::Unknown(f, v) => f,
                _ => {
                    unreachable!("we have already filtered all other constraints")
                }
            })
            .filter(|f| !self.type_fields.contains(f))
            .collect();

        if !unexpected_fields.is_empty() {
            // for unexpected fields return invalid schema error
            return invalid_schema_error(format!(
                "schema type contains unexpected fields: {unexpected_fields:?}"
            ));
        }

        Ok(())
    }

    pub(crate) fn validate_field_names_in_footer(
        &self,
        schema_footer: &Struct,
    ) -> IonSchemaResult<()> {
        let unexpected_fields: Vec<(&Symbol, &Element)> = schema_footer
            .fields()
            .filter(|(f, v)| {
                !self
                    .schema_footer_fields
                    .contains(&f.text().unwrap().to_owned())
            })
            .collect();

        if !unexpected_fields.is_empty() {
            // for unexpected fields return invalid schema error
            return invalid_schema_error(format!(
                "schema footer contains unexpected fields: {unexpected_fields:?}"
            ));
        }
        Ok(())
    }
}