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
//!
//! `regex-intersect` is a library for finding out if two regexes have a non-empty intersection.
//!
//! For example `.*` and `abc` obviously intersect (because `.*` matches everything, including the string "abc").
//! However, `d.*` and `abc` or `a[h-z]c` and `abc` do not, and could never intersect, because `abc` could never start with a `d` in the first case,
//! and `b` is not in the set `[h-z]` in the second case.
//!
//!
//! ## Examples
//!
//! Check if non empty:
//!
//! ```
//! use regex_intersect::non_empty;
//! assert!(non_empty("a.*", "ab.*cd"))
//!```
//!
//! ## Tracing
//!
//! This libary incorporates tracing, which helps follow the way it operates. Tracing is not enabled by
//! default but you can enable it:
//!
//! ```toml
//! regex-intersect = { version="0.1", features=["tracing"] }
//! ```
//!
#![warn(missing_docs)]
#![allow(clippy::similar_names)]

use regex_syntax::hir::{Class, ClassUnicode, Hir, HirKind, Literal, RepetitionKind};
use regex_syntax::ParserBuilder;
use std::borrow::BorrowMut;

fn maybe_trim<'a>(
    x: &'a Hir,
    y: &'a Hir,
    xs: &'a [Hir],
    ys: &'a [Hir],
    reversed: bool,
) -> Option<(&'a [Hir], &'a [Hir])> {
    if x.eq(y) {
        trim_slice(xs, ys, reversed)
    } else {
        None
    }
}
fn trim_slice<'a>(
    left: &'a [Hir],
    right: &'a [Hir],
    reversed: bool,
) -> Option<(&'a [Hir], &'a [Hir])> {
    match (left, right) {
        ([xs @ .., x], [ys @ .., y]) | ([x, xs @ ..], [y, ys @ ..])
            if reversed && x.is_literal() && y.is_literal() =>
        {
            maybe_trim(x, y, xs, ys, reversed)
        }
        ([x, xs @ ..], [y, ys @ ..]) if !reversed && x.is_literal() && y.is_literal() => {
            maybe_trim(x, y, xs, ys, reversed)
        }
        _ => Some((left, right)),
    }
}

fn trim<'a>(left: &'a Hir, right: &'a Hir, reversed: bool) -> Option<(Hir, Hir)> {
    match (left.kind(), right.kind()) {
        (HirKind::Concat(left), HirKind::Concat(right)) => {
            trim_slice(left.as_slice(), right.as_slice(), reversed)
                .map(|(left, right)| (Hir::concat(left.to_vec()), Hir::concat(right.to_vec())))
        }
        _ => Some((left.clone(), right.clone())),
    }
}

#[cfg_attr(feature="tracing", tracing::instrument(skip_all, fields(
  left = format!("{}", left.iter().map(|f| format!("{}", f)).collect::<Vec<_>>().join(", ")),
  right = format!("{:?}", right.iter().map(|f| format!("{}", f)).collect::<Vec<_>>().join(", ")))))]
fn concats(left: &[Hir], right: &[Hir]) -> bool {
    match (left, right) {
        // nothing matches with nothing
        (&[], &[]) => true,
        // nothing only matches *something* if that something is 'zero or X' (meaning, can match nothing)
        (&[], [x, ..]) | ([x, ..], &[]) if matches!(x.kind(), HirKind::Repetition(r) if r.kind == RepetitionKind::ZeroOrMore || r.kind == RepetitionKind::ZeroOrOne) => {
            true
        }
        // last item, and we're done only if repetition is one or more (+), which makes it symmetric to the case with zero or more above.
        ([x], [rep, ..]) | ([rep, ..], [x]) if matches!(rep.kind(), HirKind::Repetition(r) if r.kind == RepetitionKind::OneOrMore) => {
            exp(rep, x)
        }
        // otherwise, keep moving recursively
        (xall @ [x, xs @ ..], yall @ [y, ys @ ..]) => {
            match (x.kind(), y.kind()) {
                // need to incorporate the class of repetition (zeroorone, one, many, etc.)
                (HirKind::Repetition(_), _) => exp(x, y) && concats(xall, ys),
                (_, HirKind::Repetition(_)) => exp(x, y) && concats(xs, yall),
                (_, _) => exp(x, y) && concats(xs, ys),
            }
        }
        _ => false,
    }
}

#[cfg_attr(feature = "tracing", tracing::instrument)]
fn unicode_range(left: &ClassUnicode, right: &ClassUnicode) -> bool {
    let mut rl = left.clone();
    rl.borrow_mut().intersect(right);
    rl.iter().count() > 0
}

#[cfg_attr(feature = "tracing", tracing::instrument)]
fn literal(left: &Literal, right: &Literal) -> bool {
    left.eq(right)
}

#[cfg_attr(feature="tracing", tracing::instrument(skip_all, fields(left = format!("{}", left), right = format!("{}", right))))]
fn exp(left: &Hir, right: &Hir) -> bool {
    match (left.kind(), right.kind()) {
        (HirKind::Concat(xs), HirKind::Concat(ys)) => concats(xs, ys),
        (HirKind::Concat(xs), _) => concats(xs, &[right.clone()]),
        (_, HirKind::Concat(ys)) => concats(&[left.clone()], ys),
        (HirKind::Class(Class::Unicode(left)), HirKind::Class(Class::Unicode(right))) => {
            unicode_range(left, right)
        }
        (HirKind::Class(Class::Unicode(cls)), HirKind::Literal(Literal::Unicode(lit)))
        | (HirKind::Literal(Literal::Unicode(lit)), HirKind::Class(Class::Unicode(cls))) => {
            cls.iter().any(|c| *lit >= c.start() && *lit <= c.end())
        }
        (HirKind::Literal(left), HirKind::Literal(right)) => literal(left, right),
        (HirKind::Empty, HirKind::Repetition(rep)) | (HirKind::Repetition(rep), HirKind::Empty)
            if rep.kind == RepetitionKind::ZeroOrMore || rep.kind == RepetitionKind::ZeroOrOne =>
        {
            true
        }
        (HirKind::Repetition(left), HirKind::Repetition(right)) => exp(&left.hir, &right.hir),
        (HirKind::Repetition(left), _) => exp(&left.hir, right),
        (_, HirKind::Repetition(right)) => exp(left, &right.hir),
        (HirKind::Empty, HirKind::Empty) => true,
        _tup => {
            #[cfg(feature = "tracing")]
            tracing::warn!("not found: {:?}", _tup);

            false
        }
    }
}

#[cfg_attr(feature = "tracing", tracing::instrument)]
fn hir(exp: &str) -> Hir {
    let mut parser = ParserBuilder::new().allow_invalid_utf8(true).build();
    parser.parse(exp).unwrap()
}

#[must_use]
#[cfg_attr(feature = "tracing", tracing::instrument)]
///
/// Check if `left` and `right` contains a non empty intersection.
///
/// ## Examples
///
/// ```
/// use regex_intersect::non_empty;
/// assert!(non_empty("a.*", "ab.*cd"))
///```
pub fn non_empty(left: &str, right: &str) -> bool {
    let trimmed =
        trim(&hir(left), &hir(right), false).and_then(|(left, right)| trim(&left, &right, true));
    trimmed.map_or(false, |(hl, hr)| exp(&hl, &hr))
}

#[cfg(test)]
mod tests {
    use super::*;
    const NON_EMPTY: &[(&str, &[&str])] = &[
        ("abcd", &["abcd", "....", "[a-d]*"]),
        ("pqrs", &[".qrs", "p.rs", "pq.s", "pqr."]),
        (".*", &["asdklfj", "jasdfh", "asdhfajfh", "asdflkasdfjl"]),
        ("d*", &["[abcd][abcd]", "d[a-z]+", ".....", "[d]*"]),
        ("[a-p]+", &["[p-z]+", "apapapaapapapap", ".*", "abcdefgh*"]),
        (
            "abcd[a-c]z+",
            &["abcd[b-d][yz]*", "abcdazzzz", "abcdbzzz", "abcdcz"],
        ),
        (".*\\\\", &[".*", "asdfasdf\\\\"]),
        (".a.a", &["b.b.", "c.c.", "d.d.", "e.e."]),
        (
            ".*.*.*.*.*.*.*.*.*.*.*.*.*.*.*",
            &[".*.*.*.*.*.*.*.*.*.*.*"],
        ),
        ("foo.*bar", &["foobar", "fooalkdsjfbar"]),
        ("[a-b]+c", &["[b-c]+"]),
        (".xyz.", &[".*pqr.*"]), // this was moved from the 'EMPTY' testset because it didn't make sense there
    ];
    const EMPTY: &[(&str, &[&str])] = &[
        ("abcd", &["lsdfhda", "abcdla", "asdlfk", "ksdfj"]),
        ("[a-d]+", &["xyz", "p+", "[e-f]+"]),
        ("[0-9]*", &["[a-z]", ".\\*"]),
        ("ab+", &["a", "b", "abc"]),
        ("mamama.*", &["dadada.*", "nanana.*"]),
        (".*mamama", &[".*dadada", ".*nanana"]),
        (".xyz.", &["paaap"]),
        (".*.*.*.*f", &[".*.*.*.*g"]),
    ];

    const EXTRAS_NON_EMPTY: &[(&str, &[&str])] = &[
        ("fabcd", &["f.*"]),
        ("f.*abcd", &["fd.*"]),
        ("f[a-n]*abcd", &["fd.*"]),
    ];

    const EXTRAS_EMPTY: &[(&str, &[&str])] = &[
        ("fabcd", &["fd.*"]),
        ("f.*abcd", &["fd.*z"]),
        ("f[a-n]*abcd", &["fd.*z"]),
    ];

    #[test]
    fn test_one() {
        assert!(!non_empty(".*f", ".*g"));
    }

    #[test]
    fn test_non_empty() {
        for (left, rights) in NON_EMPTY {
            for right in rights.iter() {
                assert!(non_empty(left, right));
                assert!(non_empty(right, left));
            }
        }
    }

    #[test]
    fn test_empty() {
        for (left, rights) in EMPTY {
            for right in rights.iter() {
                assert!(!non_empty(left, right));
                assert!(!non_empty(right, left));
            }
        }
    }

    #[test]
    fn test_extras_non_empty() {
        for (left, rights) in EXTRAS_NON_EMPTY {
            for right in rights.iter() {
                assert!(non_empty(left, right));
                assert!(non_empty(right, left));
            }
        }
    }
    #[test]
    fn test_extras_empty() {
        for (left, rights) in EXTRAS_EMPTY {
            for right in rights.iter() {
                assert!(!non_empty(left, right));
                assert!(!non_empty(right, left));
            }
        }
    }
}