Skip to main content

safe_chains/
parse.rs

1use std::ops::Deref;
2
3/// What a word holds where its value is unknown (a variable bound to unknown items, a substitution,
4/// a stdin item) in the classification that asks what the word's TEXT could be. A handler that reads
5/// a word as code or a header value (an awk or sed program, a `perl -e` script) refuses a word
6/// holding it; one that reads a path judges it as the relative name it spells. It is a fixed string
7/// rather than a bit beside the token so that it survives being re-spelled: a wrapper (`env`,
8/// `timeout`, `bash -c`, `xargs`) rebuilds its inner command from text, and a side bit dropped there
9/// would read as known content.
10pub const UNKNOWN_CONTENT: &str = "__SAFE_CHAINS_UNKNOWN__";
11
12/// Whether `s` holds a part whose content is unknown ([`UNKNOWN_CONTENT`]).
13pub fn has_unknown_content(s: &str) -> bool {
14    s.contains(UNKNOWN_CONTENT)
15}
16
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct Token(String);
19
20impl Deref for Token {
21    type Target = str;
22    fn deref(&self) -> &str {
23        &self.0
24    }
25}
26
27#[derive(Copy, Clone)]
28pub struct WordSet(&'static [&'static str]);
29
30impl WordSet {
31    pub const fn new(words: &'static [&'static str]) -> Self {
32        let mut i = 1;
33        while i < words.len() {
34            assert!(const_less(words[i - 1].as_bytes(), words[i].as_bytes()), "WordSet: entries must be sorted, no duplicates");
35            i += 1;
36        }
37        Self(words)
38    }
39
40    pub const fn flags(words: &'static [&'static str]) -> Self {
41        let mut i = 0;
42        while i < words.len() {
43            let b = words[i].as_bytes();
44            assert!(b.len() >= 2, "WordSet::flags: flag too short (need at least 2 chars)");
45            assert!(b[0] == b'-', "WordSet::flags: flag must start with '-'");
46            if b[1] == b'-' {
47                assert!(b.len() >= 3, "WordSet::flags: long flag needs at least 3 chars (e.g. --x)");
48            }
49            i += 1;
50        }
51        Self::new(words)
52    }
53
54    pub fn contains(&self, s: &str) -> bool {
55        self.0.binary_search(&s).is_ok()
56    }
57
58    pub fn contains_short(&self, b: u8) -> bool {
59        let target = [b'-', b];
60        std::str::from_utf8(&target).is_ok_and(|s| self.0.binary_search(&s).is_ok())
61    }
62
63    pub fn iter(&self) -> impl Iterator<Item = &'static str> + '_ {
64        self.0.iter().copied()
65    }
66}
67
68const fn const_less(a: &[u8], b: &[u8]) -> bool {
69    let min = if a.len() < b.len() { a.len() } else { b.len() };
70    let mut i = 0;
71    while i < min {
72        if a[i] < b[i] {
73            return true;
74        }
75        if a[i] > b[i] {
76            return false;
77        }
78        i += 1;
79    }
80    a.len() < b.len()
81}
82
83impl Token {
84    pub fn from_raw(s: String) -> Self {
85        Self(s)
86    }
87
88    #[cfg(test)]
89    pub(crate) fn from_test(s: &str) -> Self {
90        Self(s.to_string())
91    }
92
93    pub fn as_str(&self) -> &str {
94        &self.0
95    }
96
97    pub fn command_name(&self) -> &str {
98        let s = self.as_str();
99        if s.starts_with('@') {
100            return s;
101        }
102        s.rsplit('/').next().unwrap_or(s)
103    }
104
105    pub fn is_one_of(&self, options: &[&str]) -> bool {
106        options.contains(&self.as_str())
107    }
108
109    pub fn split_value(&self, sep: &str) -> Option<&str> {
110        self.as_str().split_once(sep).map(|(_, v)| v)
111    }
112
113    /// The token with all DOUBLE-quoted string content replaced by a space — for analyzing code
114    /// whose string literals are INERT (awk: `{print "system"}` is a literal, not a call). NOT
115    /// sound for languages that INTERPOLATE code inside double quotes (perl `"@{[…]}"`), which use
116    /// their own interpolation-aware stripper.
117    pub fn content_outside_double_quotes(&self) -> String {
118        let bytes = self.as_str().as_bytes();
119        let mut result = Vec::with_capacity(bytes.len());
120        let mut i = 0;
121        while i < bytes.len() {
122            if bytes[i] == b'"' {
123                result.push(b' ');
124                i += 1;
125                while i < bytes.len() {
126                    if bytes[i] == b'\\' {
127                        i += 2;
128                        continue;
129                    }
130                    if bytes[i] == b'"' {
131                        i += 1;
132                        break;
133                    }
134                    i += 1;
135                }
136            } else {
137                result.push(bytes[i]);
138                i += 1;
139            }
140        }
141        String::from_utf8(result).unwrap_or_default()
142    }
143}
144
145impl PartialEq<str> for Token {
146    fn eq(&self, other: &str) -> bool {
147        self.0 == other
148    }
149}
150
151impl PartialEq<&str> for Token {
152    fn eq(&self, other: &&str) -> bool {
153        self.0 == *other
154    }
155}
156
157impl PartialEq<Token> for str {
158    fn eq(&self, other: &Token) -> bool {
159        self == other.as_str()
160    }
161}
162
163impl PartialEq<Token> for &str {
164    fn eq(&self, other: &Token) -> bool {
165        *self == other.as_str()
166    }
167}
168
169impl std::fmt::Display for Token {
170    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171        f.write_str(&self.0)
172    }
173}
174
175pub fn has_flag(tokens: &[Token], short: Option<&str>, long: Option<&str>) -> bool {
176    for token in &tokens[1..] {
177        if token == "--" {
178            return false;
179        }
180        if let Some(long_flag) = long
181            && (token == long_flag || token.starts_with(&format!("{long_flag}=")))
182        {
183            return true;
184        }
185        if let Some(short_flag) = short {
186            let short_char = short_flag.trim_start_matches('-');
187            if token.starts_with('-') && !token.starts_with("--") && token[1..].contains(short_char) {
188                return true;
189            }
190        }
191    }
192    false
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198    use proptest::prelude::*;
199
200    fn tok(s: &str) -> Token {
201        Token(s.to_string())
202    }
203
204    fn toks(words: &[&str]) -> Vec<Token> {
205        words.iter().map(|s| tok(s)).collect()
206    }
207
208    #[test]
209    fn display_renders_the_token_text() {
210        assert_eq!(tok("git status").to_string(), "git status");
211        assert_eq!(format!("[{}]", tok("-x")), "[-x]");
212    }
213
214    #[test]
215    fn has_flag_short() {
216        let tokens = toks(&["sed", "-i", "s/foo/bar/"]);
217        assert!(has_flag(&tokens, Some("-i"), Some("--in-place")));
218    }
219
220    #[test]
221    fn has_flag_long_with_eq() {
222        let tokens = toks(&["sed", "--in-place=.bak", "s/foo/bar/"]);
223        assert!(has_flag(&tokens, Some("-i"), Some("--in-place")));
224    }
225
226    #[test]
227    fn has_flag_combined_short() {
228        let tokens = toks(&["sed", "-ni", "s/foo/bar/p"]);
229        assert!(has_flag(&tokens, Some("-i"), Some("--in-place")));
230    }
231
232    #[test]
233    fn has_flag_stops_at_double_dash() {
234        let tokens = toks(&["cmd", "--", "-i"]);
235        assert!(!has_flag(&tokens, Some("-i"), Some("--in-place")));
236    }
237
238    #[test]
239    fn has_flag_long_only() {
240        let tokens = toks(&["sort", "--compress-program", "gzip", "file.txt"]);
241        assert!(has_flag(&tokens, None, Some("--compress-program")));
242    }
243
244    #[test]
245    fn has_flag_long_only_eq() {
246        let tokens = toks(&["sort", "--compress-program=gzip", "file.txt"]);
247        assert!(has_flag(&tokens, None, Some("--compress-program")));
248    }
249
250    #[test]
251    fn has_flag_long_only_absent() {
252        let tokens = toks(&["sort", "-r", "file.txt"]);
253        assert!(!has_flag(&tokens, None, Some("--compress-program")));
254    }
255
256    #[test]
257    fn command_name_simple() {
258        assert_eq!(tok("ls").command_name(), "ls");
259    }
260
261    #[test]
262    fn command_name_with_path() {
263        assert_eq!(tok("/usr/bin/ls").command_name(), "ls");
264    }
265
266    #[test]
267    fn command_name_relative_path() {
268        assert_eq!(tok("./scripts/test.sh").command_name(), "test.sh");
269    }
270
271    #[test]
272    fn command_name_scoped_package() {
273        assert_eq!(tok("@herb-tools/linter").command_name(), "@herb-tools/linter");
274    }
275
276    #[test]
277    fn reverse_partial_eq() {
278        let t = tok("hello");
279        assert!("hello" == t);
280        assert!("world" != t);
281    }
282
283    #[test]
284    fn token_deref() {
285        let t = tok("--flag");
286        assert!(t.starts_with("--"));
287        assert!(t.contains("fl"));
288        assert_eq!(t.len(), 6);
289    }
290
291    #[test]
292    fn token_is_one_of() {
293        assert!(tok("-v").is_one_of(&["-v", "--verbose"]));
294        assert!(!tok("-q").is_one_of(&["-v", "--verbose"]));
295    }
296
297    #[test]
298    fn token_split_value() {
299        assert_eq!(tok("--method=GET").split_value("="), Some("GET"));
300        assert_eq!(tok("--flag").split_value("="), None);
301    }
302
303    #[test]
304    fn word_set_contains() {
305        let set = WordSet::new(&["list", "show", "view"]);
306        assert!(set.contains(&tok("list")));
307        assert!(set.contains(&tok("view")));
308        assert!(!set.contains(&tok("delete")));
309    }
310
311    #[test]
312    fn word_set_iter() {
313        let set = WordSet::new(&["a", "b", "c"]);
314        let items: Vec<&str> = set.iter().collect();
315        assert_eq!(items, vec!["a", "b", "c"]);
316    }
317
318    #[test]
319    fn content_outside_double_quotes_strips_string() {
320        assert_eq!(tok(r#""system""#).content_outside_double_quotes(), " ");
321    }
322
323    #[test]
324    fn content_outside_double_quotes_preserves_code() {
325        let result = tok(r#"{print "hello"} END{print NR}"#).content_outside_double_quotes();
326        assert_eq!(result, r#"{print  } END{print NR}"#);
327    }
328
329    #[test]
330    fn content_outside_double_quotes_escaped() {
331        let result = tok(r#"{print "he said \"hi\""}"#).content_outside_double_quotes();
332        assert_eq!(result, "{print  }");
333    }
334
335    #[test]
336    fn content_outside_double_quotes_unterminated_string_ending_in_a_backslash() {
337        assert_eq!(tok(r#"x "ab\"#).content_outside_double_quotes(), "x  ");
338        assert_eq!(tok(r#"x "\"#).content_outside_double_quotes(), "x  ");
339    }
340
341    #[test]
342    fn content_outside_double_quotes_no_quotes() {
343        assert_eq!(tok("{print $1}").content_outside_double_quotes(), "{print $1}");
344    }
345
346    proptest! {
347        #[test]
348        fn const_less_is_the_strict_byte_order(
349            a in proptest::collection::vec(b'a'..=b'c', 0..5),
350            b in proptest::collection::vec(b'a'..=b'c', 0..5),
351        ) {
352            prop_assert_eq!(const_less(&a, &b), a < b);
353            prop_assert!(!const_less(&a, &a));
354        }
355
356        /// `command_name` is the last `/`-separated segment of its input, with one carve-out: any
357        /// string starting with `@` (a scoped npm package name) is returned verbatim. This is the
358        /// contract callers rely on — `git command_name` returns `git`, `./bin/foo` returns `foo`,
359        /// `@scope/pkg` returns `@scope/pkg` — so the property states it exactly.
360        #[test]
361        fn command_name_is_last_slash_segment_or_full_at_prefixed(
362            s in "\\PC{0,128}",
363        ) {
364            let token = Token::from_raw(s.clone());
365            let expected = if s.starts_with('@') {
366                s.as_str()
367            } else {
368                s.rsplit('/').next().unwrap_or(&s)
369            };
370            prop_assert_eq!(token.command_name(), expected);
371        }
372
373        /// `split_value(sep)` returns `Some(suffix)` iff `sep` occurs in the input, and that
374        /// `suffix` is exactly the substring after the FIRST occurrence of `sep`. Empty
375        /// `sep` is meaningless to `split_once`, so it is filtered out. Together this means
376        /// a flag of the form `--key=value` yields `Some("value")` and the prefix is the
377        /// smallest possible one — no caller can be surprised by where the split lands.
378        #[test]
379        fn split_value_is_some_iff_separator_present_and_yields_first_suffix(
380            s in "\\PC{0,128}",
381            sep in "\\PC{1,8}",
382        ) {
383            let token = Token::from_raw(s.clone());
384            let result = token.split_value(&sep);
385            let first_at = s.find(&sep);
386            prop_assert_eq!(result.is_some(), first_at.is_some());
387            if let (Some(suffix), Some(idx)) = (result, first_at) {
388                prop_assert_eq!(suffix, &s[idx + sep.len()..]);
389            }
390        }
391
392        /// The stripper replaces every closed `"…"` region with a single space and copies
393        /// everything else through unchanged. The fact that each `"` either becomes a space
394        /// or is consumed (escapes skip ahead, the closing `"` ends the loop with `i += 1`)
395        /// means a second application never sees a `"` to act on, so the operation is
396        /// idempotent. A regression that, say, copied the closing `"` through would break
397        /// this on the very next iteration.
398        #[test]
399        fn content_outside_double_quotes_is_idempotent(
400            s in "\\PC{0,256}",
401        ) {
402            let once = Token::from_raw(s).content_outside_double_quotes();
403            let twice = Token::from_raw(once.clone()).content_outside_double_quotes();
404            prop_assert_eq!(once, twice);
405        }
406
407        /// The `--` token terminates argument parsing; `has_flag` must respect it on every
408        /// input shape. Whether the flags asked about appear before `--` or after it, in the
409        /// leading tokens, in a later `--key=value`, or nowhere at all, the verdict computed
410        /// on `prefix + ["--"] + tail` is identical to the verdict on `prefix` alone. This
411        /// is the property the implementation's `if token == "--" { return false; }` line
412        /// promises; arbitrary fillers after `--` exercise the loop continuing past the
413        /// terminator.
414        #[test]
415        fn has_flag_verdict_is_invariant_under_appending_a_double_dash_tail(
416            prefix in proptest::collection::vec("\\PC{0,16}", 0..4),
417            tail in proptest::collection::vec("\\PC{0,16}", 0..4),
418            short in proptest::option::of("\\PC{2,16}"),
419            long in proptest::option::of("\\PC{3,32}"),
420        ) {
421            // Force the flag forms into the shapes `has_flag` actually recognises; anything
422            // else would be testing the regex, not the function.
423            let short = short.filter(|s| s.starts_with('-') && !s.starts_with("--") && s.len() >= 2);
424            let long = long.filter(|s| s.starts_with("--") && s.len() >= 3 && !s.contains('='));
425
426            let mut base: Vec<Token> = Vec::with_capacity(prefix.len() + 2);
427            base.push(tok("cmd"));
428            for p in &prefix {
429                base.push(tok(p));
430            }
431            if let Some(s) = &short {
432                base.push(tok(s));
433            }
434            if let Some(l) = &long {
435                base.push(tok(l));
436            }
437
438            let mut with_tail = base.clone();
439            with_tail.push(tok("--"));
440            for t in &tail {
441                with_tail.push(tok(t));
442            }
443
444            prop_assert_eq!(
445                has_flag(&base, short.as_deref(), long.as_deref()),
446                has_flag(&with_tail, short.as_deref(), long.as_deref()),
447            );
448        }
449    }
450}