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
// 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::IslConstraintValue;
use crate::isl::isl_type::IslType;
use crate::isl::WriteToIsl;
use crate::result::{invalid_schema_error, invalid_schema_error_raw, IonSchemaResult};
use crate::violation::{Violation, ViolationCode};
use ion_rs::element::{Element, Struct};
use ion_rs::{IonWriter, Symbol};
use regex::Regex;
use std::fmt::{Display, Formatter};
use std::sync::OnceLock;
/// 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;
pub(crate) mod ion_extension;
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;
}

static ISL_VERSION_MARKER_REGEX: OnceLock<Regex> = OnceLock::new();
static RESERVED_WORD_REGEX: OnceLock<Regex> = OnceLock::new();

/// Checks if a value is an ISL version marker.
fn is_isl_version_marker(text: &str) -> bool {
    ISL_VERSION_MARKER_REGEX
        .get_or_init(|| Regex::new(r"^\$ion_schema_\d.*$").unwrap())
        .is_match(text)
}

/// Checks is a value is reserved keyword ISL version maker.
fn is_reserved_word(text: &str) -> bool {
    RESERVED_WORD_REGEX
        .get_or_init(|| Regex::new(r"^(\$ion_schema(_.*)?|[a-z][a-z0-9]*(_[a-z0-9]+)*)$").unwrap())
        .is_match(text)
}

const ISL_2_0_KEYWORDS: [&str; 28] = [
    "all_of",
    "annotations",
    "any_of",
    "as",
    "byte_length",
    "codepoint_length",
    "container_length",
    "contains",
    "element",
    "exponent",
    "field_names",
    "fields",
    "id",
    "imports",
    "name",
    "not",
    "occurs",
    "one_of",
    "ordered_elements",
    "precision",
    "regex",
    "schema_footer",
    "schema_header",
    "timestamp_precision",
    "type",
    "user_reserved_fields",
    "utf8_byte_length",
    "valid_values",
];

/// 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) -> IonSchemaResult<Self> {
        if user_reserved_fields.fields().any(|(f, v)| {
            f.text() != Some("schema_header")
                && f.text() != Some("schema_footer")
                && f.text() != Some("type")
        }) {
            return invalid_schema_error(
                "User reserved fields can only have schema_header, schema_footer or type as the field names",
            );
        }
        Ok(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,
    ) -> IonSchemaResult<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()))
            .ok_or(invalid_schema_error_raw(
                "User reserved fields mut be non null",
            ))?;

        let user_reserved_fields = user_reserved_elements
            .iter()
            .filter(|e| e.annotations().is_empty() && !e.is_null())
            .map(|e| e.as_text().map(|s| s.to_owned()))
            .collect::<Option<Vec<String>>>()
            .unwrap_or(vec![]);

        if user_reserved_fields.len() != user_reserved_elements.len() {
            return invalid_schema_error("User reserved fields mut be unannotated");
        }

        if user_reserved_fields
            .iter()
            .any(|f| is_reserved_word(f) || ISL_2_0_KEYWORDS.binary_search(&f.as_str()).is_ok())
        {
            return invalid_schema_error(
                "ISl 2.0 keywords may not be declared as user reserved fields",
            );
        }

        Ok(user_reserved_fields)
    }

    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"
                    && f.text().unwrap() != "imports"
            })
            .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: &IslType) -> IonSchemaResult<()> {
        let unexpected_fields: &Vec<&String> = &isl_type
            .constraints()
            .iter()
            .filter(|c| matches!(c.constraint_value, IslConstraintValue::Unknown(_, _)))
            .map(|c| match &c.constraint_value {
                IslConstraintValue::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(())
    }
}

impl WriteToIsl for UserReservedFields {
    fn write_to<W: IonWriter>(&self, writer: &mut W) -> IonSchemaResult<()> {
        // this function assumes that we are already inside a schema header struct
        // writes `user_reserved_fields` in the schema header
        writer.set_field_name("user_reserved_fields");
        writer.step_in(IonType::Struct)?;

        // writes user reserved fields for `schema_header`
        writer.set_field_name("schema_header");
        writer.step_in(IonType::List)?;
        for value in &self.schema_header_fields {
            writer.write_symbol(value)?;
        }
        writer.step_out()?;

        // writes user reserved fields for `type`
        writer.set_field_name("type");
        writer.step_in(IonType::List)?;
        for value in &self.type_fields {
            writer.write_symbol(value)?;
        }
        writer.step_out()?;

        // writes user reserved fields for `schema_footer`
        writer.set_field_name("schema_footer");
        writer.step_in(IonType::List)?;
        for value in &self.schema_footer_fields {
            writer.write_symbol(value)?;
        }
        writer.step_out()?;

        writer.step_out()?;
        Ok(())
    }
}