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
use crate::matching::Matcher;
use crate::util::{is_atomic, Expression, Flags};
use regex::{Error, Regex};
use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
use std::collections::VecDeque;
use std::fmt;

/// A compiled collection of rules ready for the building of a
/// [`Matcher`] or for use in the definition of a new rule.
///
/// You do not build new `Grammar`s directly. Rather, the [`grammar!`] macro compiles them for you.
///
/// [`Matcher`]:  ../pidgin/struct.Matcher.html
/// [`grammar!`]: ../pidgin/macro.grammar.html

#[derive(Clone, Debug)]
pub struct Grammar {
    ///
    pub name: Option<String>,
    pub(crate) sequence: Vec<Expression>,
    pub(crate) flags: Flags,
    pub(crate) stingy: bool,
    pub(crate) lower_limit: Option<usize>,
    pub(crate) upper_limit: Option<usize>,
}

impl Grammar {
    pub(crate) fn rx_rule(rx: String) -> Grammar {
        Grammar {
            name: None,
            flags: Flags::new(),
            stingy: false,
            lower_limit: None,
            upper_limit: None,
            sequence: vec![Expression::Part(rx, false)],
        }
    }
    pub(crate) fn name(&mut self, name: &str) {
        self.name = Some(name.to_string());
    }
    /// Compiles a `Matcher` based on the `Grammar`'s rules.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[macro_use] extern crate pidgin;
    /// # use std::error::Error;
    /// # fn demo() -> Result<(), Box<Error>> {
    /// let m = grammar!{
    /// 	(?wbB)
    /// 	noun   => <person> | <place> | <thing>
    /// 	person => [["Moe", "Larry", "Curly", "Sade", "Diana Ross"]]
    /// 	place  => [["Brattleboro, Vermont"]]
    /// 	thing  => [["tiddly wink", "muffin", "kazoo"]]
    /// }.matcher()?;
    /// # Ok(()) }
    /// ```
    ///
    /// # Errors
    ///
    /// If the `Grammar` contains an ill-formed `r(rx)` or one with a named capture
    /// which is repeated, an error will be returned.
    pub fn matcher(&self) -> Result<Matcher, Error> {
        Matcher::new(&self)
    }
    pub(crate) fn reps_min(&self, r: usize) -> Result<Grammar, String> {
        if self.upper_limit.is_none() || self.lower_limit.unwrap() >= r {
            let mut flags = self.flags.clone();
            flags.enclosed = Some(true);
            Ok(Grammar {
                flags,
                name: self.name.clone(),
                sequence: self.sequence.clone(),
                lower_limit: Some(r),
                upper_limit: self.upper_limit.clone(),
                stingy: self.stingy,
            })
        } else {
            Err(format!(
                "minimum repetitions {} is greater than maximum repetitions {}",
                r,
                self.upper_limit.unwrap()
            ))
        }
    }
    pub(crate) fn reps_max(&self, r: usize) -> Result<Grammar, String> {
        if self.lower_limit.is_none() || self.lower_limit.unwrap() <= r {
            if r == 0 {
                Err(String::from(
                    "the maximum number of repetitions must be greater than 0",
                ))
            } else {
                let mut flags = self.flags.clone();
                flags.enclosed = Some(true);
                Ok(Grammar {
                    flags,
                    name: self.name.clone(),
                    sequence: self.sequence.clone(),
                    lower_limit: self.lower_limit.clone(),
                    upper_limit: Some(r),
                    stingy: self.stingy,
                })
            }
        } else {
            Err(format!(
                "minimum repetitions {} is greater than maximum repetitions {}",
                self.lower_limit.unwrap(),
                r
            ))
        }
    }
    pub(crate) fn stingy(mut self, stingy: bool) -> Grammar {
        self.stingy = stingy;
        self
    }
    pub(crate) fn any_suffix(&self) -> bool {
        (self.lower_limit.is_some() || self.upper_limit.is_some())
            && !(self.lower_limit.is_some()
                && self.upper_limit.is_some()
                && self.lower_limit.unwrap() == 1
                && self.upper_limit.unwrap() == 1)
    }
    pub(crate) fn repetition_suffix(&self) -> String {
        let stingy_modifier = if self.stingy { "?" } else { "" };
        if self.lower_limit.is_none() {
            if self.upper_limit.is_none() {
                String::from("")
            } else {
                let r = self.upper_limit.unwrap();
                if r == 1 {
                    format!("?{}", stingy_modifier)
                } else {
                    format!("{{0,{}}}{}", r, stingy_modifier)
                }
            }
        } else if self.upper_limit.is_none() {
            let r = self.lower_limit.unwrap();
            match r {
                0 => format!("*{}", stingy_modifier),
                1 => format!("+{}", stingy_modifier),
                _ => format!("{{{},}}{}", r, stingy_modifier),
            }
        } else {
            let min = self.lower_limit.unwrap();
            let max = self.upper_limit.unwrap();
            match min {
                0 => match max {
                    1 => format!("?{}", stingy_modifier),
                    _ => format!("{{0,{}}}{}", max, stingy_modifier),
                },
                _ => {
                    if min == max {
                        if min == 1 {
                            String::from("")
                        } else {
                            format!("{{{}}}", min)
                        }
                    } else {
                        format!("{{{},{}}}{}", min, max, stingy_modifier)
                    }
                }
            }
        }
    }
    /// Return a copy of one of the rules used by the grammar.
    ///
    /// This is chiefly useful when combining grammars generated by the macro.
    ///
    /// # Examples
    ///
    /// ```rust
    /// #[macro_use] extern crate pidgin;
    /// let library = grammar!{
    ///     books => <cat> | <dog> | <camel>
    ///     cat   => [["persian", "siamese", "calico", "tabby"]]
    ///     dog   => [["dachshund", "chihuahua", "corgi", "malamute"]]
    ///     camel => [["bactrian", "dromedary"]]
    /// };
    /// let g = grammar!{
    ///     seen -> ("I saw a") g(library.rule("cat").unwrap()) (".")
    /// };
    /// let matcher = g.matcher().unwrap();
    /// assert!(matcher.is_match("I saw a calico."));
    /// ```
    pub fn rule(&self, rule: &str) -> Option<Grammar> {
        let mut expressions = VecDeque::new();
        for e in &self.sequence {
            expressions.push_back(e);
        }
        loop {
            if let Some(e) = expressions.pop_front() {
                match e {
                    Expression::Grammar(ref g, _) => {
                        if let Some(ref n) = g.name {
                            if n == rule {
                                return Some(g.clone());
                            }
                        }
                        for e in &g.sequence {
                            expressions.push_back(&e);
                        }
                    }
                    Expression::Alternation(v, _) | Expression::Sequence(v, _) => {
                        for e in v {
                            expressions.push_back(e);
                        }
                    }
                    Expression::Repetition(e, _, _) => expressions.push_back(e),
                    _ => (),
                }
            } else {
                break;
            }
        }
        None
    }
    /// Generates a non-capturing regex matching what the grammar matches.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[macro_use] extern crate pidgin;
    /// # use std::error::Error;
    /// # fn dem() -> Result<(),Box<Error>> {
    /// let g = grammar!{
    ///     foo -> r(r"\A") <bar> r(r"\z")
    ///     bar => (?i) [["cat", "camel", "corn"]]
    /// };
    /// let rx = g.rx()?.to_string();
    /// assert_eq!(r"\A(?i:\s*c(?:orn|a(?:t|mel)))\s*\z", rx);
    /// # Ok(()) }
    /// ```
    ///
    /// ```rust
    /// # #[macro_use] extern crate pidgin;
    /// # use std::error::Error;
    /// # fn dem() -> Result<(),Box<Error>> {
    /// let g = grammar!{
    ///     sentence    -> <capitalized_word> <other_words>? <terminal_punctuation>
    ///     other_words -> <other_word>+
    ///     other_word  -> <non_terminal_punctuation>? <word>
    ///     capitalized_word         => r(r"\b[A-Z]\w*\b")
    ///     word                     => r(r"\b\w+\b")
    ///     terminal_punctuation     => r(r"[.?!]")
    ///     non_terminal_punctuation => r("(?:--?|[,;'\"])")
    /// };
    /// let rx = g.rule("word").unwrap().rx().unwrap();
    /// let p = g
    ///     .matcher()?
    ///     .parse("John, don't forget to pick up chips.")
    ///     .unwrap();
    /// let other_words = p.name("other_words").unwrap().as_str();
    /// let other_words = rx
    ///     .find_iter(other_words)
    ///     .map(|m| m.as_str())
    ///     .collect::<Vec<_>>();
    /// assert_eq!(
    ///     vec!["don", "t", "forget", "to", "pick", "up", "chips"],
    ///     other_words
    /// );
    /// # Ok(()) }
    /// ```
    pub fn rx(&self) -> Result<Regex, Error> {
        let mut g = self.clear_recursive();
        g.clear_name();
        Regex::new(g.to_string().as_str())
    }
    // the root stringification method
    // because we pass the default flags in here, at any point hereafter
    // we will have some definition of every flag
    pub(crate) fn to_string(&self) -> String {
        self.to_s(&Flags::defaults(), false, false)
    }
    pub(crate) fn clear_recursive(&self) -> Grammar {
        let sequence = self.sequence.iter().map(|e| e.clear_names()).collect();
        Grammar {
            sequence,
            name: None,
            flags: self.flags.clone(),
            upper_limit: self.upper_limit.clone(),
            lower_limit: self.lower_limit.clone(),
            stingy: self.stingy,
        }
    }
    pub(crate) fn clear_name(&mut self) {
        self.name = None;
    }
    fn needs_closure(&self, context: &Flags) -> bool {
        self.flags.enclosed.unwrap_or(false)
            || self.needs_flags_set(context)
            || self.any_suffix()
                && !(self.sequence.len() == 1
                    && is_atomic(&self.sequence[0].to_s(&self.flags.merge(context), true, true)))
    }
    fn needs_flags_set(&self, context: &Flags) -> bool {
        self.flags.differing_flags(context)
    }
    // flag string when needed
    fn flags(&self, context: &Flags) -> String {
        if !self.needs_flags_set(context) {
            return String::from("");
        }
        let mut flags_on = Vec::with_capacity(4);
        let mut flags_off = Vec::with_capacity(4);
        if let Some(b) = choose_flag(&self.flags.case_insensitive, &context.case_insensitive) {
            if b {
                flags_on.push("i");
            } else {
                flags_off.push("i");
            }
        }
        if let Some(b) = choose_flag(&self.flags.multi_line, &context.multi_line) {
            if b {
                flags_on.push("m");
            } else {
                flags_off.push("m");
            }
        }
        if let Some(b) = choose_flag(&self.flags.dot_all, &context.dot_all) {
            if b {
                flags_on.push("s");
            } else {
                flags_off.push("s");
            }
        }
        if let Some(b) = choose_flag(&self.flags.unicode, &context.unicode) {
            if b {
                flags_on.push("u");
            } else {
                flags_off.push("u");
            }
        }
        if let Some(b) = choose_flag(&self.flags.reverse_greed, &context.reverse_greed) {
            if b {
                flags_on.push("U");
            } else {
                flags_off.push("U");
            }
        }
        let mut flags = String::new();
        if flags_on.len() > 0 {
            flags.push_str(&flags_on.join(""));
        }
        if flags_off.len() > 0 {
            flags.push('-');
            flags.push_str(&flags_off.join(""));
        }
        flags
    }
    pub(crate) fn to_s(&self, context: &Flags, describing: bool, top: bool) -> String {
        let mut s = if self.name.is_some() {
            format!("(?P<{}>", self.name.as_ref().unwrap())
        } else {
            String::new()
        };
        let closure_skippable = top && !self.any_suffix();
        if !closure_skippable && self.needs_closure(context) {
            s = s + format!("(?{}:", self.flags(context)).as_str();
        }
        for e in &self.sequence {
            s += e.to_s(&self.flags.merge(context), describing, top).as_ref();
        }
        if !closure_skippable && self.needs_closure(context) {
            s = s + ")"
        }
        if self.name.is_some() {
            s = s + ")"
        }
        s + self.repetition_suffix().as_str()
    }
}

fn choose_flag(o1: &Option<bool>, o2: &Option<bool>) -> Option<bool> {
    if o1.is_some() && (o1.unwrap() ^ o2.unwrap()) {
        o1.clone()
    } else {
        None
    }
}

impl PartialOrd for Grammar {
    fn partial_cmp(&self, other: &Grammar) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Grammar {
    fn cmp(&self, other: &Grammar) -> Ordering {
        let o = self.sequence.len().cmp(&other.sequence.len());
        if o != Ordering::Equal {
            return o;
        }
        if self.name.is_some() ^ other.name.is_some() {
            return if self.name.is_some() {
                Ordering::Greater
            } else {
                Ordering::Less
            };
        }
        if self.name.is_some() {
            let o = self
                .name
                .as_ref()
                .unwrap()
                .cmp(&other.name.as_ref().unwrap());
            if o != Ordering::Equal {
                return o;
            }
        }
        for i in 0..self.sequence.len() {
            let v1 = &self.sequence[i];
            let v2 = &other.sequence[i];
            let o = v1.cmp(&v2);
            if o != Ordering::Equal {
                return o;
            }
        }
        self.flags.cmp(&other.flags)
    }
}

impl PartialEq for Grammar {
    fn eq(&self, other: &Grammar) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl Eq for Grammar {}

impl fmt::Display for Grammar {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.to_string())
    }
}