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
// Copyright Amazon.com, Inc. or its affiliates.

//! Provides simple conversion from [Pest] grammar syntax to Amazon [Ion].
//!
//! ## Example
//!
//! The easiest way to convert [Pest] grammars to Ion is from a `str` slice:
//!
//! ```
//! use pest_ion::*;
//! use ion_rs::value::*;
//! use ion_rs::value::reader::*;
//!
//! fn main() -> PestToIonResult<()> {
//!     // parse a Pest grammar and convert it to Ion element
//!     let actual = r#"a = @{ "a" | "b" ~ "c" }"#.try_pest_to_element()?;
//!
//!     // here is the equivalent Ion element
//!     let ion_text = r#"{
//!         a: {
//!             type: atomic,
//!             expression:
//!                 (choice
//!                     (string exact "a")
//!                     (sequence
//!                         (string exact "b")
//!                         (string exact "c")
//!                     )
//!                 )
//!         }
//!     }"#;
//!     let expected = element_reader().read_one(ion_text.as_bytes())?;
//!
//!     // these should be equivalent
//!     assert_eq!(expected, actual);
//!     
//!     Ok(())
//! }
//! ```
//!
//! [Pest]: https://pest.rs/
//! [Ion]: https://amzn.github.io/ion-docs/

pub mod result;

pub use result::*;

use ion_rs::value::owned::{text_token, OwnedElement, OwnedValue};
use ion_rs::value::{Builder, Element};
use pest::Parser;
use pest_meta::ast::{Expr, Rule as AstRule, RuleType as AstRuleType, RuleType};
use pest_meta::parser::{consume_rules, PestParser, Rule};
use smallvec::{smallvec, SmallVec};

/// Converts representation of a Pest grammar (or part of a grammar) into Ion [`Element`].
pub trait TryPestToElement {
    type Element: Element;

    /// Converts this into [`Element`] which may imply parsing Pest syntax.
    ///
    /// This returns `Err` if the the conversion fails. For example, this can happen if the
    /// source is not a valid Pest grammar.
    fn try_pest_to_element(&self) -> PestToIonResult<Self::Element>;
}

/// Infallible conversion of a Pest grammar (or part of a grammar) into Ion [`Element`].
pub trait PestToElement {
    type Element: Element;

    /// Converts this into an [`Element`] representation.
    ///
    /// This operation cannot fail and therefore it is implied that it represents some
    /// well formed Pest grammar or component thereof.
    fn pest_to_element(&self) -> Self::Element;
}

impl TryPestToElement for &str {
    type Element = OwnedElement;

    /// Parses a `str` slice as a Pest grammar and serializes the AST into [`Element`].
    fn try_pest_to_element(&self) -> PestToIonResult<Self::Element> {
        let pairs = PestParser::parse(Rule::grammar_rules, *self)?;
        let ast = match consume_rules(pairs) {
            Ok(ast) => ast,
            Err(errors) => {
                return if errors.is_empty() {
                    invalid("Error converting Pest grammar to AST with no context")
                } else {
                    // TODO deal with more than one error..
                    let err = errors.into_iter().next().unwrap();
                    Err(err.into())
                };
            }
        };

        Ok(ast.pest_to_element())
    }
}

impl PestToElement for Vec<AstRule> {
    type Element = OwnedElement;

    /// Converts a body of rules into a `struct` that has a rule for each field.
    fn pest_to_element(&self) -> Self::Element {
        let fields = self.iter().map(|rule| {
            let rule_name = text_token(rule.name.clone());
            let rule_value = rule.pest_to_element();
            (rule_name, rule_value)
        });
        Self::Element::new_struct(fields)
    }
}

impl PestToElement for AstRule {
    type Element = OwnedElement;

    /// Converts a Pest Rule into a `struct` that has the field for [`RuleType`] as a symbol
    /// and a field for the [`Expr`].
    fn pest_to_element(&self) -> Self::Element {
        let fields = std::array::IntoIter::new([
            (text_token("type"), self.ty.pest_to_element()),
            (text_token("expression"), self.expr.pest_to_element()),
        ]);
        Self::Element::new_struct(fields)
    }
}

impl PestToElement for AstRuleType {
    type Element = OwnedElement;

    /// Serializes the enum into a symbolic value.
    fn pest_to_element(&self) -> Self::Element {
        let sym_tok = text_token(match self {
            RuleType::Normal => "normal",
            RuleType::Silent => "silent",
            RuleType::Atomic => "atomic",
            RuleType::CompoundAtomic => "compound_atomic",
            RuleType::NonAtomic => "non_atomic",
        });

        sym_tok.into()
    }
}

impl PestToElement for Expr {
    type Element = OwnedElement;

    /// Generates a `sexp` representation of the rule expression.
    fn pest_to_element(&self) -> Self::Element {
        use OwnedValue::*;

        const STACK_LEN: usize = 4;
        let values: SmallVec<[_; STACK_LEN]> = match self.clone() {
            Expr::Str(text) => smallvec![
                text_token("string").into(),
                text_token("exact").into(),
                String(text).into(),
            ],
            Expr::Insens(text) => smallvec![
                text_token("string").into(),
                text_token("insensitive").into(),
                String(text).into(),
            ],
            Expr::Range(begin, end) => smallvec![
                text_token("character_range").into(),
                String(begin).into(),
                String(end).into(),
            ],
            Expr::Ident(name) => smallvec![text_token("identifier").into(), String(name).into()],
            Expr::PosPred(expr) => smallvec![
                text_token("predicate").into(),
                text_token("positive").into(),
                expr.pest_to_element(),
            ],
            Expr::NegPred(expr) => smallvec![
                text_token("predicate").into(),
                text_token("negative").into(),
                expr.pest_to_element(),
            ],
            Expr::Seq(left, right) => smallvec![
                text_token("sequence").into(),
                left.pest_to_element(),
                right.pest_to_element(),
            ],
            Expr::Choice(left, right) => smallvec![
                text_token("choice").into(),
                left.pest_to_element(),
                right.pest_to_element(),
            ],
            Expr::Opt(expr) => {
                smallvec![text_token("optional").into(), expr.pest_to_element()]
            }
            Expr::Rep(expr) => smallvec![
                text_token("repeat_min").into(),
                0.into(),
                expr.pest_to_element(),
            ],
            Expr::RepOnce(expr) => smallvec![
                text_token("repeat_min").into(),
                1.into(),
                expr.pest_to_element(),
            ],
            Expr::RepMin(expr, min) => smallvec![
                text_token("repeat_min").into(),
                (min as i64).into(),
                expr.pest_to_element(),
            ],
            Expr::RepMax(expr, max) => smallvec![
                text_token("repeat_max").into(),
                (max as i64).into(),
                expr.pest_to_element(),
            ],
            Expr::RepExact(expr, exact) => smallvec![
                text_token("repeat_range").into(),
                (exact as i64).into(),
                (exact as i64).into(),
                expr.pest_to_element(),
            ],
            Expr::RepMinMax(expr, min, max) => smallvec![
                text_token("repeat_range").into(),
                (min as i64).into(),
                (max as i64).into(),
                expr.pest_to_element(),
            ],
            // TODO implement these
            Expr::Skip(_) => unimplemented!(),
            Expr::Push(_) => unimplemented!(),
            Expr::PeekSlice(_, _) => unimplemented!(),
        };
        assert!(values.len() <= STACK_LEN);

        let element = Self::Element::new_sexp(values);

        element
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ion_rs::value::reader::*;
    use ion_rs::value::writer::*;
    use rstest::*;
    use std::fmt::Debug;
    use std::str::from_utf8;

    #[rstest]
    #[case::string(
        r#"a = { "hello" }"#,
        r#"
        {
            a: {
                type: normal,
                expression: (string exact "hello")
            }
        }"#
    )]
    #[case::case_insensitive_string_atomic(
        r#"a = @{ ^"world" }"#,
        r#"
        {
            a: {
                type: atomic,
                expression: (string insensitive "world")
            }
        }"#
    )]
    #[case::range_silent(
        r#"a = _{ 'a'..'z' }"#,
        r#"
        {
            a: {
                type: silent,
                expression: (character_range "a" "z")
            }
        }"#
    )]
    #[case::range_identifier_compound(
        r#"a = ${ ANY }"#,
        r#"
        {
            a: {
                type: compound_atomic,
                expression: (identifier "ANY")
            }
        }"#
    )]
    #[case::predicates_non_atomic(
        r#"a = !{ &(b) }
           b = !{ !"hi" }"#,
        r#"
        {
            a: {
                type: non_atomic,
                expression: (predicate positive (identifier "b"))
            },
            b: {
                type: non_atomic,
                expression: (predicate negative (string exact "hi"))
            }
        }"#
    )]
    #[case::sequence(
        r#"a = { "a" ~ ^"b" ~ "c" }"#,
        r#"
        {
            a: {
                type: normal,
                expression:
                    (sequence
                        (sequence
                            (string exact "a")
                            (string insensitive "b")
                        )
                        (string exact "c")
                    )
            }
        }"#
    )]
    #[case::choice(
        r#"a = { "a" | ^"b" | "c" }"#,
        r#"
        {
            a: {
                type: normal,
                expression:
                    (choice
                        (choice
                            (string exact "a")
                            (string insensitive "b")
                        )
                        (string exact "c")
                    )
            }
        }"#
    )]
    #[case::mix_choice_seq(
        r#"a = { "a" ~ ^"b" | "c" ~ ^"d" ~ "e" | "f" ~ "g" }"#,
        r#"
        {
            a: {
                type: normal,
                expression:
                    (choice
                        (choice
                            (sequence
                                (string exact "a")
                                (string insensitive "b")
                            )
                            (sequence
                                (sequence
                                    (string exact "c")
                                    (string insensitive "d")
                                )
                                (string exact "e")
                            )
                        )
                        (sequence
                            (string exact "f")
                            (string exact "g")
                        )
                    )
            }
        }"#
    )]
    #[case::optional(
        r#"a = { "a"? }"#,
        r#"
        {
            a: {
                type: normal,
                expression: (optional (string exact "a"))
            }
        }"#
    )]
    #[case::repeat_min(
        r#"a = { "a"* }
           b = { "b"+ }
           c = { "c"{1,} }
           d = { "d"{2,} }"#,
        r#"
        {
            a: {
                type: normal,
                expression: (repeat_min 0 (string exact "a"))
            },
            b: {
                type: normal,
                expression: (repeat_min 1 (string exact "b"))
            },
            c: {
                type: normal,
                expression: (repeat_min 1 (string exact "c"))
            },
            d: {
                type: normal,
                expression: (repeat_min 2 (string exact "d"))
            },
        }"#
    )]
    #[case::repeat_max(
        r#"a = { "a"{,100} }"#,
        r#"
        {
            a: {
                type: normal,
                expression: (repeat_max 100 (string exact "a"))
            },
        }"#
    )]
    #[case::repeat_range(
        r#"a = { "a"{5} ~ "b"{7, 10} }"#,
        r#"
        {
            a: {
                type: normal,
                expression:
                    (sequence
                        (repeat_range 5 5 (string exact "a"))
                        (repeat_range 7 10 (string exact "b"))
                    )
            },
        }"#
    )]
    fn good<T, S>(#[case] input: T, #[case] ion_literal: S) -> PestToIonResult<()>
    where
        T: TryPestToElement<Element = OwnedElement> + Debug,
        S: AsRef<str>,
    {
        let actual = input.try_pest_to_element()?;
        let expected = element_reader().read_one(ion_literal.as_ref().as_bytes())?;

        const BUF_SIZE: usize = 16 * 1024 * 1024;
        let mut buf = vec![0u8; BUF_SIZE];
        let mut writer = Format::Text(TextKind::Pretty).element_writer_for_slice(&mut buf)?;
        writer.write(&actual)?;
        let actual_converted_text = from_utf8(writer.finish()?).unwrap();

        assert_eq!(
            expected,
            actual,
            "Expected \n{}\nbut was\n{}",
            ion_literal.as_ref(),
            actual_converted_text
        );
        Ok(())
    }

    /// The goal here is not to test Pest's meta parsing, but just to ensure that we get errors
    /// from our APIs when we expect to.
    #[rstest]
    #[case::empty_rule(r#"a = {}"#)]
    #[case::self_reference(r#"a = { a }"#)]
    #[case::double_rule(r#"a = { "a" }\n a = { "b" }"#)]
    fn pest_errors<T: TryPestToElement>(#[case] input: T) -> PestToIonResult<()> {
        match input.try_pest_to_element() {
            Err(PestToIonError::Pest(_)) => {}
            something => {
                unreachable!("Got result we did not expect: {:?}", something);
            }
        }
        Ok(())
    }
}