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
use std::fmt;
use std::iter::FromIterator;
use std::str::FromStr;

use bitflags::bitflags;
use derive_more::{Deref, DerefMut, From, Index, IndexMut, Into, IntoIterator};

use crate::{
    compile::ExprExt,
    error::{Error, Result},
    ffi,
};

bitflags! {
    /// Pattern flags
    #[derive(Default)]
    pub struct Flags: u32 {
        /// Set case-insensitive matching.
        const CASELESS = ffi::HS_FLAG_CASELESS;
        /// Matching a `.` will not exclude newlines.
        const DOTALL = ffi::HS_FLAG_DOTALL;
        /// Set multi-line anchoring.
        const MULTILINE = ffi::HS_FLAG_MULTILINE;
        /// Set single-match only mode.
        const SINGLEMATCH = ffi::HS_FLAG_SINGLEMATCH;
        /// Allow expressions that can match against empty buffers.
        const ALLOWEMPTY = ffi::HS_FLAG_ALLOWEMPTY;
        /// Enable UTF-8 mode for this expression.
        const UTF8 = ffi::HS_FLAG_UTF8;
        /// Enable Unicode property support for this expression.
        const UCP = ffi::HS_FLAG_UCP;
        /// Enable prefiltering mode for this expression.
        const PREFILTER = ffi::HS_FLAG_PREFILTER;
        /// Enable leftmost start of match reporting.
        const SOM_LEFTMOST = ffi::HS_FLAG_SOM_LEFTMOST;
        /// Logical combination.
        #[cfg(feature = "v5")]
        const COMBINATION = ffi::HS_FLAG_COMBINATION;
        /// Don't do any match reporting.
        #[cfg(feature = "v5")]
        const QUIET = ffi::HS_FLAG_QUIET;
    }
}

impl FromStr for Flags {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        let mut flags = Flags::empty();

        for c in s.chars() {
            match c {
                'i' => flags |= Flags::CASELESS,
                'm' => flags |= Flags::MULTILINE,
                's' => flags |= Flags::DOTALL,
                'H' => flags |= Flags::SINGLEMATCH,
                'V' => flags |= Flags::ALLOWEMPTY,
                '8' => flags |= Flags::UTF8,
                'W' => flags |= Flags::UCP,
                'P' => flags |= Flags::PREFILTER,
                'L' => flags |= Flags::SOM_LEFTMOST,
                #[cfg(feature = "v5")]
                'C' => flags |= Flags::COMBINATION,
                #[cfg(feature = "v5")]
                'Q' => flags |= Flags::QUIET,
                _ => return Err(Error::InvalidFlag(c)),
            }
        }

        Ok(flags)
    }
}

impl fmt::Display for Flags {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.contains(Flags::CASELESS) {
            write!(f, "i")?
        }
        if self.contains(Flags::MULTILINE) {
            write!(f, "m")?
        }
        if self.contains(Flags::DOTALL) {
            write!(f, "s")?
        }
        if self.contains(Flags::SINGLEMATCH) {
            write!(f, "H")?
        }
        if self.contains(Flags::ALLOWEMPTY) {
            write!(f, "V")?
        }
        if self.contains(Flags::UTF8) {
            write!(f, "8")?
        }
        if self.contains(Flags::UCP) {
            write!(f, "W")?
        }
        if self.contains(Flags::PREFILTER) {
            write!(f, "P")?
        }
        if self.contains(Flags::SOM_LEFTMOST) {
            write!(f, "L")?
        }
        #[cfg(feature = "v5")]
        if self.contains(Flags::COMBINATION) {
            write!(f, "C")?
        }
        #[cfg(feature = "v5")]
        if self.contains(Flags::QUIET) {
            write!(f, "Q")?
        }
        Ok(())
    }
}

/// Defines the precision to track start of match offsets in stream state.
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum SomHorizon {
    /// use full precision to track start of match offsets in stream state.
    ///
    /// This mode will use the most stream state per pattern,
    /// but will always return an accurate start of match offset
    /// regardless of how far back in the past it was found.
    Large = ffi::HS_MODE_SOM_HORIZON_LARGE,
    /// use medium precision to track start of match offsets in stream state.
    ///
    /// This mode will use less stream state than @ref HS_MODE_SOM_HORIZON_LARGE and
    /// will limit start of match accuracy to offsets
    /// within 2^32 bytes of the end of match offset reported.
    Medium = ffi::HS_MODE_SOM_HORIZON_MEDIUM,
    /// use limited precision to track start of match offsets in stream state.
    ///
    /// This mode will use less stream state than `SomHorizon::Large` and
    /// will limit start of match accuracy to offsets
    /// within 2^16 bytes of the end of match offset reported.
    Small = ffi::HS_MODE_SOM_HORIZON_SMALL,
}

/// The pattern with basic regular expression.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Pattern {
    /// The expression to parse.
    pub expression: String,
    /// Flags which modify the behaviour of the expression.
    pub flags: Flags,
    /// ID number to be associated with the corresponding pattern in the expressions array.
    pub id: Option<usize>,
    /// Extended behaviour for this pattern
    pub ext: ExprExt,
    /// The precision to track start of match offsets in stream state.
    pub som: Option<SomHorizon>,
}

impl Pattern {
    /// Construct a pattern with expression.
    pub fn new<S: Into<String>>(expr: S) -> Result<Pattern> {
        Ok(Pattern {
            expression: expr.into(),
            flags: Flags::empty(),
            id: None,
            ext: ExprExt::default(),
            som: None,
        })
    }

    /// Construct a pattern with expression and flags.
    pub fn with_flags<S: Into<String>>(expr: S, flags: Flags) -> Result<Pattern> {
        Ok(Pattern {
            expression: expr.into(),
            flags,
            id: None,
            ext: ExprExt::default(),
            som: None,
        })
    }

    /// Set case-insensitive matching.
    pub fn caseless(mut self) -> Self {
        self.flags |= Flags::CASELESS;
        self
    }

    /// Matching a `.` will not exclude newlines.
    pub fn dot_all(mut self) -> Self {
        self.flags |= Flags::DOTALL;
        self
    }

    /// Set multi-line anchoring.
    pub fn multi_line(mut self) -> Self {
        self.flags |= Flags::MULTILINE;
        self
    }

    /// Set single-match only mode.
    pub fn single_match(mut self) -> Self {
        self.flags |= Flags::SINGLEMATCH;
        self
    }

    /// Allow expressions that can match against empty buffers.
    pub fn allow_empty(mut self) -> Self {
        self.flags |= Flags::ALLOWEMPTY;
        self
    }

    /// Enable UTF-8 mode for this expression.
    pub fn utf8(mut self) -> Self {
        self.flags |= Flags::UTF8;
        self
    }

    /// Enable Unicode property support for this expression.
    pub fn ucp(mut self) -> Self {
        self.flags |= Flags::UCP;
        self
    }

    /// Enable prefiltering mode for this expression.
    pub fn prefilter(mut self) -> Self {
        self.flags |= Flags::PREFILTER;
        self
    }

    /// Report the leftmost start of match offset when a match is found.
    pub fn left_most(mut self) -> Self {
        self.flags |= Flags::SOM_LEFTMOST;
        self
    }

    /// Logical combination.
    #[cfg(feature = "v5")]
    pub fn combination(mut self) -> Self {
        self.flags |= Flags::COMBINATION;
        self
    }

    /// Don't do any match reporting.
    #[cfg(feature = "v5")]
    pub fn quiet(mut self) -> Self {
        self.flags |= Flags::QUIET;
        self
    }

    pub(crate) fn som(&self) -> Option<SomHorizon> {
        if self.flags.contains(Flags::SOM_LEFTMOST) {
            self.som.or(Some(SomHorizon::Medium))
        } else {
            None
        }
    }
}

impl fmt::Display for Pattern {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(id) = self.id {
            write!(f, "{}:", id)?;
        }

        if self.id.is_some() || !self.flags.is_empty() || !self.ext.is_empty() {
            write!(f, "/{}/", self.expression)?;
        } else {
            write!(f, "{}", self.expression)?;
        }

        if !self.flags.is_empty() {
            write!(f, "{}", self.flags)?;
        }
        if !self.ext.is_empty() {
            write!(f, "{}", self.ext)?;
        }

        Ok(())
    }
}

impl FromStr for Pattern {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        let (id, expr) = match s.find(":/") {
            Some(off) => (Some(s[..off].parse()?), &s[off + 1..]),
            None => (None, s),
        };

        match (expr.starts_with('/'), expr.rfind('/')) {
            (true, Some(end)) if end > 0 => {
                let (expr, remaining) = (&expr[1..end], &expr[end + 1..]);
                let (flags, ext) = match (remaining.ends_with('}'), remaining.rfind('{')) {
                    (true, Some(start)) => {
                        let (flags, ext) = remaining.split_at(start);

                        (flags.parse()?, ext.parse()?)
                    }
                    _ => (remaining.parse()?, ExprExt::default()),
                };

                Ok(Pattern {
                    expression: expr.into(),
                    flags,
                    id,
                    ext,
                    som: None,
                })
            }

            _ => Ok(Pattern {
                expression: expr.into(),
                flags: Flags::empty(),
                id,
                ext: ExprExt::default(),
                som: None,
            }),
        }
    }
}

/// Vec of `Pattern`
#[repr(transparent)]
#[derive(Clone, Debug, Deref, DerefMut, From, Index, IndexMut, Into, IntoIterator)]
#[deref(forward)]
#[deref_mut(forward)]
pub struct Patterns(pub Vec<Pattern>);

impl FromIterator<Pattern> for Patterns {
    fn from_iter<T: IntoIterator<Item = Pattern>>(iter: T) -> Self {
        Self(Vec::from_iter(iter))
    }
}

impl FromStr for Patterns {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        s.lines()
            .flat_map(|line| {
                let line = line.trim();

                if line.is_empty() || line.starts_with('#') {
                    None
                } else {
                    Some(line.parse())
                }
            })
            .collect::<Result<Vec<_>>>()
            .map(Self)
    }
}

impl Patterns {
    pub(crate) fn som(&self) -> Option<SomHorizon> {
        if self
            .iter()
            .any(|Pattern { flags, .. }| flags.contains(Flags::SOM_LEFTMOST))
        {
            self.iter()
                .flat_map(|&Pattern { som, .. }| som)
                .max()
                .or(Some(SomHorizon::Medium))
        } else {
            None
        }
    }
}

/// Define `Pattern` with flags
#[macro_export]
macro_rules! pattern {
    ( $expr:expr ) => {{
        pattern! { $expr ; $crate::CompileFlags::default() }
    }};
    ( $expr:expr ; $( $flag:ident )|* ) => {{
        pattern! { $expr ; $( $crate::CompileFlags:: $flag )|* }
    }};
    ( $expr:expr ; $flags:expr ) => {{
        $crate::Pattern {
            expression: $expr.into(),
            flags: $flags,
            id: None,
            ext: $crate::ExpressionExt::default(),
            som: None,
        }
    }};
    ( $id:literal => $expr:expr ; $( $flag:ident )|* ) => {{
        pattern! { $id => $expr ; $( $crate::CompileFlags:: $flag )|* }
    }};
    ( $id:literal => $expr:expr ; $flags:expr ) => {{
        $crate::Pattern {
            expression: $expr.into(),
            flags: $flags,
            id: Some($id),
            ext: $crate::ExpressionExt::default(),
            som: None,
        }
    }};
}

/// Define multi `Pattern` with flags and ID
#[macro_export]
macro_rules! patterns {
    ( $( $expr:expr ),* ) => {
        Patterns(vec![ $( pattern! { $expr } ),* ])
    };
    ( $( $expr:expr ),* ; $( $flag:ident )|* ) => {
        patterns! { $( $expr ),*; $( $crate::CompileFlags:: $flag )|* }
    };
    ( $( $expr:expr ),* ; $flags:expr ) => {{
        Patterns(vec![ $( pattern! { $expr ; $flags } ),* ])
    }};
}

#[cfg(test)]
mod tests {
    use crate::common::tests::*;
    use crate::prelude::*;

    use super::*;

    const DATABASE_SIZE: usize = 2664;

    #[test]
    fn test_compile_flags() {
        let flags = Flags::CASELESS | Flags::DOTALL;

        assert_eq!(flags.to_string(), "is");

        assert_eq!("ism".parse::<Flags>().unwrap(), flags | Flags::MULTILINE);
        assert!("test".parse::<Flags>().is_err());
    }

    #[test]
    fn test_pattern() {
        let p: Pattern = "test".parse().unwrap();

        assert_eq!(p, pattern! { "test" });
        assert_eq!(p.expression, "test");
        assert!(p.flags.is_empty());
        assert_eq!(p.id, None);

        let p: Pattern = "/test/".parse().unwrap();

        assert_eq!(p, pattern! { "test" });
        assert_eq!(p.expression, "test");
        assert!(p.flags.is_empty());
        assert_eq!(p.id, None);

        let p: Pattern = "/test/i".parse().unwrap();

        assert_eq!(p, pattern! { "test"; CASELESS });
        assert_eq!(p.expression, "test");
        assert_eq!(p.flags, Flags::CASELESS);
        assert_eq!(p.id, None);

        let p: Pattern = "3:/test/i".parse().unwrap();

        assert_eq!(p, pattern! { 3 => "test"; CASELESS });
        assert_eq!(p.expression, "test");
        assert_eq!(p.flags, Flags::CASELESS);
        assert_eq!(p.id, Some(3));

        let s = r#"1:/hatstand.*teakettle/s{min_offset=50,max_offset=100}"#;
        let p: Pattern = s.parse().unwrap();

        assert_eq!(p, {
            let mut p = pattern! { 1 => "hatstand.*teakettle"; DOTALL };
            p.ext.set_min_offset(50);
            p.ext.set_max_offset(100);
            p
        });
        assert_eq!(p.expression, "hatstand.*teakettle");
        assert_eq!(p.flags, Flags::DOTALL);
        assert_eq!(p.id, Some(1));
        assert_eq!(p.ext.min_offset().unwrap(), 50);
        assert_eq!(p.ext.max_offset().unwrap(), 100);
        assert_eq!(p.to_string(), s);

        let p: Pattern = "test/i".parse().unwrap();

        assert_eq!(p, pattern! { "test/i" });
        assert_eq!(p.expression, "test/i");
        assert!(p.flags.is_empty());
        assert_eq!(p.id, None);

        let p: Pattern = "/t/e/s/t/i".parse().unwrap();

        assert_eq!(p, pattern! { "t/e/s/t"; CASELESS });
        assert_eq!(p.expression, "t/e/s/t");
        assert_eq!(p.flags, Flags::CASELESS);
        assert_eq!(p.id, None);
    }

    #[test]
    fn test_pattern_build() {
        let p = &pattern! {"test"};

        assert_eq!(p.expression, "test");
        assert!(p.flags.is_empty());
        assert_eq!(p.id, None);

        let info = p.info().unwrap();

        assert_eq!(info.min_width, 4);
        assert_eq!(info.max_width, 4);
        assert!(!info.unordered_matches());
        assert!(!info.matches_at_eod());
        assert!(!info.matches_only_at_eod());

        let db: BlockDatabase = p.build().unwrap();

        validate_database(&db);
    }

    #[test]
    fn test_pattern_build_with_flags() {
        let p = &pattern! {"test"; CASELESS};

        assert_eq!(p.expression, "test");
        assert_eq!(p.flags, Flags::CASELESS);
        assert_eq!(p.id, None);

        let db: BlockDatabase = p.build().unwrap();

        validate_database(&db);
    }

    #[test]
    fn test_patterns_build() {
        let db: BlockDatabase = patterns!("test", "foo", "bar").build().unwrap();

        validate_database_with_size(&db, DATABASE_SIZE);
    }

    #[test]
    fn test_patterns_build_with_flags() {
        let db: BlockDatabase = patterns!("test", "foo", "bar"; CASELESS | DOTALL).build().unwrap();

        validate_database_with_size(&db, DATABASE_SIZE);
    }
}