Skip to main content

safe_chains/
parse.rs

1use std::ops::Deref;
2
3#[derive(Debug, Clone, PartialEq, Eq)]
4pub struct Token(String);
5
6impl Deref for Token {
7    type Target = str;
8    fn deref(&self) -> &str {
9        &self.0
10    }
11}
12
13#[derive(Copy, Clone)]
14pub struct WordSet(&'static [&'static str]);
15
16impl WordSet {
17    pub const fn new(words: &'static [&'static str]) -> Self {
18        let mut i = 1;
19        while i < words.len() {
20            assert!(
21                const_less(words[i - 1].as_bytes(), words[i].as_bytes()),
22                "WordSet: entries must be sorted, no duplicates"
23            );
24            i += 1;
25        }
26        Self(words)
27    }
28
29    pub const fn flags(words: &'static [&'static str]) -> Self {
30        let mut i = 0;
31        while i < words.len() {
32            let b = words[i].as_bytes();
33            assert!(b.len() >= 2, "WordSet::flags: flag too short (need at least 2 chars)");
34            assert!(b[0] == b'-', "WordSet::flags: flag must start with '-'");
35            if b[1] == b'-' {
36                assert!(b.len() >= 3, "WordSet::flags: long flag needs at least 3 chars (e.g. --x)");
37            }
38            i += 1;
39        }
40        Self::new(words)
41    }
42
43    pub fn contains(&self, s: &str) -> bool {
44        self.0.binary_search(&s).is_ok()
45    }
46
47    pub fn contains_short(&self, b: u8) -> bool {
48        let target = [b'-', b];
49        std::str::from_utf8(&target).is_ok_and(|s| self.0.binary_search(&s).is_ok())
50    }
51
52    pub fn iter(&self) -> impl Iterator<Item = &'static str> + '_ {
53        self.0.iter().copied()
54    }
55}
56
57const fn const_less(a: &[u8], b: &[u8]) -> bool {
58    let min = if a.len() < b.len() { a.len() } else { b.len() };
59    let mut i = 0;
60    while i < min {
61        if a[i] < b[i] {
62            return true;
63        }
64        if a[i] > b[i] {
65            return false;
66        }
67        i += 1;
68    }
69    a.len() < b.len()
70}
71
72impl Token {
73    pub(crate) fn from_raw(s: String) -> Self {
74        Self(s)
75    }
76
77    #[cfg(test)]
78    pub(crate) fn from_test(s: &str) -> Self {
79        Self(s.to_string())
80    }
81
82    pub fn as_str(&self) -> &str {
83        &self.0
84    }
85
86    pub fn command_name(&self) -> &str {
87        let s = self.as_str();
88        if s.starts_with('@') {
89            return s;
90        }
91        s.rsplit('/').next().unwrap_or(s)
92    }
93
94    pub fn is_one_of(&self, options: &[&str]) -> bool {
95        options.contains(&self.as_str())
96    }
97
98    pub fn split_value(&self, sep: &str) -> Option<&str> {
99        self.as_str().split_once(sep).map(|(_, v)| v)
100    }
101
102    /// The token with all DOUBLE-quoted string content replaced by a space — for analyzing code
103    /// whose string literals are INERT (awk: `{print "system"}` is a literal, not a call). NOT
104    /// sound for languages that INTERPOLATE code inside double quotes (perl `"@{[…]}"`), which use
105    /// their own interpolation-aware stripper.
106    pub fn content_outside_double_quotes(&self) -> String {
107        let bytes = self.as_str().as_bytes();
108        let mut result = Vec::with_capacity(bytes.len());
109        let mut i = 0;
110        while i < bytes.len() {
111            if bytes[i] == b'"' {
112                result.push(b' ');
113                i += 1;
114                while i < bytes.len() {
115                    if bytes[i] == b'\\' && i + 1 < bytes.len() {
116                        i += 2;
117                        continue;
118                    }
119                    if bytes[i] == b'"' {
120                        i += 1;
121                        break;
122                    }
123                    i += 1;
124                }
125            } else {
126                result.push(bytes[i]);
127                i += 1;
128            }
129        }
130        String::from_utf8(result).unwrap_or_default()
131    }
132}
133
134impl PartialEq<str> for Token {
135    fn eq(&self, other: &str) -> bool {
136        self.0 == other
137    }
138}
139
140impl PartialEq<&str> for Token {
141    fn eq(&self, other: &&str) -> bool {
142        self.0 == *other
143    }
144}
145
146impl PartialEq<Token> for str {
147    fn eq(&self, other: &Token) -> bool {
148        self == other.as_str()
149    }
150}
151
152impl PartialEq<Token> for &str {
153    fn eq(&self, other: &Token) -> bool {
154        *self == other.as_str()
155    }
156}
157
158impl std::fmt::Display for Token {
159    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160        f.write_str(&self.0)
161    }
162}
163
164pub fn has_flag(tokens: &[Token], short: Option<&str>, long: Option<&str>) -> bool {
165    for token in &tokens[1..] {
166        if token == "--" {
167            return false;
168        }
169        if let Some(long_flag) = long
170            && (token == long_flag || token.starts_with(&format!("{long_flag}=")))
171        {
172            return true;
173        }
174        if let Some(short_flag) = short {
175            let short_char = short_flag.trim_start_matches('-');
176            if token.starts_with('-')
177                && !token.starts_with("--")
178                && token[1..].contains(short_char)
179            {
180                return true;
181            }
182        }
183    }
184    false
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190
191    fn tok(s: &str) -> Token {
192        Token(s.to_string())
193    }
194
195    fn toks(words: &[&str]) -> Vec<Token> {
196        words.iter().map(|s| tok(s)).collect()
197    }
198
199    #[test]
200    fn has_flag_short() {
201        let tokens = toks(&["sed", "-i", "s/foo/bar/"]);
202        assert!(has_flag(&tokens, Some("-i"), Some("--in-place")));
203    }
204
205    #[test]
206    fn has_flag_long_with_eq() {
207        let tokens = toks(&["sed", "--in-place=.bak", "s/foo/bar/"]);
208        assert!(has_flag(&tokens, Some("-i"), Some("--in-place")));
209    }
210
211    #[test]
212    fn has_flag_combined_short() {
213        let tokens = toks(&["sed", "-ni", "s/foo/bar/p"]);
214        assert!(has_flag(&tokens, Some("-i"), Some("--in-place")));
215    }
216
217    #[test]
218    fn has_flag_stops_at_double_dash() {
219        let tokens = toks(&["cmd", "--", "-i"]);
220        assert!(!has_flag(&tokens, Some("-i"), Some("--in-place")));
221    }
222
223    #[test]
224    fn has_flag_long_only() {
225        let tokens = toks(&["sort", "--compress-program", "gzip", "file.txt"]);
226        assert!(has_flag(&tokens, None, Some("--compress-program")));
227    }
228
229    #[test]
230    fn has_flag_long_only_eq() {
231        let tokens = toks(&["sort", "--compress-program=gzip", "file.txt"]);
232        assert!(has_flag(&tokens, None, Some("--compress-program")));
233    }
234
235    #[test]
236    fn has_flag_long_only_absent() {
237        let tokens = toks(&["sort", "-r", "file.txt"]);
238        assert!(!has_flag(&tokens, None, Some("--compress-program")));
239    }
240
241    #[test]
242    fn command_name_simple() {
243        assert_eq!(tok("ls").command_name(), "ls");
244    }
245
246    #[test]
247    fn command_name_with_path() {
248        assert_eq!(tok("/usr/bin/ls").command_name(), "ls");
249    }
250
251    #[test]
252    fn command_name_relative_path() {
253        assert_eq!(tok("./scripts/test.sh").command_name(), "test.sh");
254    }
255
256    #[test]
257    fn command_name_scoped_package() {
258        assert_eq!(tok("@herb-tools/linter").command_name(), "@herb-tools/linter");
259    }
260
261    #[test]
262    fn reverse_partial_eq() {
263        let t = tok("hello");
264        assert!("hello" == t);
265        assert!("world" != t);
266    }
267
268    #[test]
269    fn token_deref() {
270        let t = tok("--flag");
271        assert!(t.starts_with("--"));
272        assert!(t.contains("fl"));
273        assert_eq!(t.len(), 6);
274    }
275
276    #[test]
277    fn token_is_one_of() {
278        assert!(tok("-v").is_one_of(&["-v", "--verbose"]));
279        assert!(!tok("-q").is_one_of(&["-v", "--verbose"]));
280    }
281
282    #[test]
283    fn token_split_value() {
284        assert_eq!(tok("--method=GET").split_value("="), Some("GET"));
285        assert_eq!(tok("--flag").split_value("="), None);
286    }
287
288    #[test]
289    fn word_set_contains() {
290        let set = WordSet::new(&["list", "show", "view"]);
291        assert!(set.contains(&tok("list")));
292        assert!(set.contains(&tok("view")));
293        assert!(!set.contains(&tok("delete")));
294    }
295
296    #[test]
297    fn word_set_iter() {
298        let set = WordSet::new(&["a", "b", "c"]);
299        let items: Vec<&str> = set.iter().collect();
300        assert_eq!(items, vec!["a", "b", "c"]);
301    }
302
303    #[test]
304    fn content_outside_double_quotes_strips_string() {
305        assert_eq!(tok(r#""system""#).content_outside_double_quotes(), " ");
306    }
307
308    #[test]
309    fn content_outside_double_quotes_preserves_code() {
310        let result = tok(r#"{print "hello"} END{print NR}"#).content_outside_double_quotes();
311        assert_eq!(result, r#"{print  } END{print NR}"#);
312    }
313
314    #[test]
315    fn content_outside_double_quotes_escaped() {
316        let result = tok(r#"{print "he said \"hi\""}"#).content_outside_double_quotes();
317        assert_eq!(result, "{print  }");
318    }
319
320    #[test]
321    fn content_outside_double_quotes_no_quotes() {
322        assert_eq!(tok("{print $1}").content_outside_double_quotes(), "{print $1}");
323    }
324}