neutralts/bif/
parse_bif_allow.rs

1#![doc = include_str!("../../doc/bif-allow.md")]
2
3use crate::{bif::constants::*, bif::Bif, bif::BifError, constants::*, utils::*};
4use std::collections::HashSet;
5
6impl<'a> Bif<'a> {
7    /*
8        {:allow; {:flg; partial casein replace :} name >> ... :}
9    */
10    pub(crate) fn parse_bif_allow(&mut self) -> Result<(), BifError> {
11        if self.mod_filter || self.mod_scope {
12            return Err(self.bif_error(BIF_ERROR_MODIFIER_NOT_ALLOWED));
13        }
14
15        self.extract_params_code(true);
16        let mut found = String::new();
17        let words_string = get_from_key(
18            &self.shared.schema["__indir"][&self.inherit.indir]["declare"],
19            &self.params,
20        );
21
22        if words_string.is_empty() {
23            return Err(self.bif_error(&(self.params.clone() + BIF_ERROR_DECLARED_IS_EMPTY)));
24        }
25
26        if !self.flags.is_empty() {
27            let flags_allowed: HashSet<&str> =
28                ["partial", "replace", "casein"].into_iter().collect();
29
30            for f in self.flags.split('|').filter(|s| !s.is_empty()) {
31                if !flags_allowed.contains(f) {
32                    return Err(self.bif_error(&format!("{} flag not allowed", f)));
33                }
34            }
35        }
36
37        let mut words_list: Vec<&str> = words_string.split_whitespace().collect();
38        self.code = new_child_parse!(self, &self.code, self.mod_scope);
39
40        for word in &mut words_list {
41            let lower_haystack;
42            let mut haystack = &self.code;
43            let mut pattern = word.to_string().clone();
44
45            if self.flags.contains("|partial|") || self.flags.contains("|replace|") {
46                pattern = format!("{}{}{}", "*", pattern, "*");
47            }
48
49            if self.flags.contains("|casein|") {
50                pattern = pattern.to_lowercase();
51                lower_haystack = self.code.clone().to_lowercase();
52                haystack = &lower_haystack;
53            }
54
55            if wildcard_match(haystack, &pattern) {
56                found = word.to_string();
57                break;
58            }
59        }
60
61        if !found.is_empty() ^ self.mod_negate {
62            if self.flags.contains("|replace|") {
63                found = found.replace("~", "");
64                found = found.replace("*", "");
65                found = found.replace("?", "");
66                found = found.replace(".", "");
67                self.out = found.to_string();
68            } else {
69                self.out = self.code.to_string();
70            }
71        } else {
72            self.out = EMPTY_STRING;
73        }
74
75        Ok(())
76    }
77}
78
79#[cfg(test)]
80#[path = "parse_bif_allow_tests.rs"]
81mod tests;