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
use {
    bet::BeTree,
    regex::{self, Regex},
    thiserror::Error,
};

#[derive(Debug, Error)]
pub enum StrFilterParseError {

    #[error("invalid pattern {0:?} : {1}")]
    InvalidPattern(String, String),

    #[error("invalid regex {0:?}")]
    InvalidRegex(#[from] regex::Error),
}

/// Query operators.
/// `And` and `Or` are binary while `Not` is unary.
#[derive(Debug, Clone, Copy, PartialEq)]
enum BoolOperator {
    And,
    Or,
    Not,
}
impl BoolOperator {
    fn eval(self, a: bool, b: Option<bool>) -> bool {
        match (self, b) {
            (Self::And, Some(b)) => a & b,
            (Self::Or, Some(b)) => a | b,
            (Self::Not, None) => !a,
            _ => {
                panic!("unexpected operator or operands"); // parsing failed
            }
        }
    }
    /// tell whether we can skip evaluating the second operand
    fn short_circuit(self, a: bool) -> bool {
        match (self, a) {
            (Self::And, false) => true,
            (Self::Or, true) => true,
            _ => false,
        }
    }
}

/// a filter for strings
#[derive(Debug)]
pub struct StrFilter {
    expr: BeTree<BoolOperator, Regex>,
}

fn invalid(pattern: &str, reason: &str) -> Result<StrFilter, StrFilterParseError> {
    Err(StrFilterParseError::InvalidPattern(pattern.to_string(), reason.to_string()))
}

impl StrFilter {
    pub fn new(pattern: &str) -> Result<Self, StrFilterParseError> {
        if pattern.contains(',') {
            Self::with_comma_syntax(pattern)
        } else {
            Self::with_be_syntax(pattern)
        }
    }
    /// parse a filter defined with a rich binary expression syntax (parentheses, &, |, etc.)
    /// a sequence of patterns, each one with an optional NOT before.
    ///
    /// Example: ̀ dystroy & !miaou`
    pub fn with_be_syntax(pattern: &str) -> Result<Self, StrFilterParseError> {
        let mut expr = BeTree::new();
        let chars: Vec<char> = pattern.chars().collect();
        for i in 0..chars.len() {
            match chars[i] {
                '(' if chars.get(i + 1) == Some(&' ') => {
                    if expr.accept_opening_par() {
                        expr.open_par();
                    } else {
                        return invalid(pattern, "unexpected opening parenthesis");
                    }
                }
                ')' if i > 0 && chars.get(i - 1) == Some(&' ') => {
                    if expr.accept_closing_par() {
                        expr.close_par();
                    } else {
                        println!("expr: {:#?}", &expr);
                        return invalid(pattern, "unexpected closing parenthesis");
                    }
                }
                '&' if chars.get(i + 1) == Some(&' ') => {
                    if expr.accept_binary_operator() {
                        expr.push_operator(BoolOperator::And);
                    } else {
                        return invalid(pattern, "unexpected '&'");
                    }
                }
                '|' if chars.get(i + 1) == Some(&' ') => {
                    if expr.accept_binary_operator() {
                        expr.push_operator(BoolOperator::Or);
                    } else {
                        return invalid(pattern, "unexpected '|'");
                    }
                }
                '!' if expr.accept_unary_operator() => {
                    expr.push_operator(BoolOperator::Not);
                }
                ' ' => {}
                c => {
                    expr.mutate_or_create_atom(String::new).push(c);
                }
            }
        }
        let expr = expr.try_map_atoms(|s| Regex::new(s))?;
        Ok(Self { expr })
    }
    /// parse a filter defined with the comma syntax, ie a AND on
    /// a sequence of patterns, each one with an optional NOT before.
    ///
    /// Example: ̀ dystroy,!miaou`
    pub fn with_comma_syntax(pattern: &str) -> Result<Self, StrFilterParseError> {
        let mut expr = BeTree::new();
        let atoms = pattern.split(',').map(|s| s.trim());
        for atom in atoms {
            if atom.is_empty() {
                return invalid(pattern, "empty token");
            }
            if !expr.is_empty() {
                expr.push_operator(BoolOperator::And);
            }
            if let Some(atom) = atom.strip_prefix("!") {
                expr.push_operator(BoolOperator::Not);
                expr.push_atom(Regex::new(atom)?);
            } else {
                expr.push_atom(Regex::new(atom)?);
            }
        }
        Ok(Self { expr })
    }
    pub fn accepts(&self, candidate: &str) -> bool {
        self.expr
            .eval(
                |r| r.is_match(candidate),
                |op, a, b| op.eval(a, b),
                |op, &a| op.short_circuit(a),
            )
            .unwrap_or_else(|| {
                println!("unexpected lack of expr result on {:?}", candidate);
                false
            })
    }
}

#[cfg(test)]
mod str_filter_tests {

    use super::*;

    #[test]
    fn test_comma() {
        let f = StrFilter::new("dystroy,!miaou").unwrap();
        assert_eq!(f.accepts("a/dystroy/b"), true);
        assert_eq!(f.accepts("a/miaou/b"), false);
        assert_eq!(f.accepts("a/miaou/dystroy"), false);
    }

    #[test]
    fn test_comma_regex() {
        let f = StrFilter::new(r#"dystroy,!m\w{3}u"#).unwrap();
        assert_eq!(f.accepts("a/dystroy/b"), true);
        assert_eq!(f.accepts("a/miaou/b"), false);
        assert_eq!(f.accepts("a/miaou/dystroy"), false);
    }

    #[test]
    fn test_be() {
        let f = StrFilter::new("dystroy & !( miaou | blog )").unwrap();
        assert_eq!(f.accepts("a/dystroy/b"), true);
        assert_eq!(f.accepts("dystroy/miaou/b"), false);
        assert_eq!(f.accepts("a/blog/dystroy"), false);
        assert_eq!(f.accepts("a/blog/"), false);
    }

    #[test]
    fn test_be_regex() {
        let f = StrFilter::new(r#"^/dystroy & !( m\w{3}u | blog )"#).unwrap();
        assert_eq!(f.accepts("/a/dystroy/b"), false);
        assert_eq!(f.accepts("/dystroy/b"), true);
        assert_eq!(f.accepts("/dystroy/mieou/b"), false);
        assert_eq!(f.accepts("/dystroy/mieaou/b"), true);
        assert_eq!(f.accepts("/z/dystroy/mieaou/b"), false);
        assert_eq!(f.accepts("/a/blog/dystroy"), false);
        assert_eq!(f.accepts("/a/blog/"), false);
    }

}