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