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
use crate::{Cow, Shard};

#[derive(Clone, Copy, Debug)]
pub struct SyntaxError;

pub struct ShellwordSplitter<'a> {
    input: &'a str,
}

impl<'a> ShellwordSplitter<'a> {
    pub fn new(input: &'a str) -> Self {
        Self { input }
    }

    fn skip_whitespace(&mut self) {
        let mut it = self.input.char_indices();
        self.input = loop {
            break match it.next() {
                None => "",
                Some((pos, x)) if !x.is_whitespace() => &self.input[pos..],
                _ => continue,
            };
        };
    }
}

fn ch_is_quote(ch: char) -> bool {
    matches!(ch, '"' | '\'')
}

impl<'a> Iterator for ShellwordSplitter<'a> {
    type Item = Result<Cow<'a, str>, SyntaxError>;

    fn next(&mut self) -> Option<Self::Item> {
        self.skip_whitespace();
        let mut it = self.input.char_indices();
        let mut quotec = None;
        let mut ret = Shard::<'a>::new(self.input);
        while let Some((cpos, cx)) = it.next() {
            if cx == '\\' {
                // escape works the same, no matter if inside or outside of quotes
                let x = match it.next() {
                    Some(i) => i.1,
                    None => return Some(Err(SyntaxError)),
                };
                ret.push_owned(match x {
                    'n' => '\n',
                    't' => '\t',
                    'r' => '\r',
                    _ if quotec.is_some() && x.is_whitespace() => continue,
                    _ => x,
                });
                continue;
            }
            if quotec.is_none() {
                if ch_is_quote(cx) {
                    // start of quotation
                    quotec = Some(cx);
                    // allow the algo to reuse simple, quoted args
                    ret.skip(1);
                    continue;
                } else if cx.is_whitespace() {
                    // argument separator, this will never happen on the first iteration
                    self.input = &self.input[cpos..];
                    return ret.finish_cvg().map(Ok);
                }
            } else if Some(cx) == quotec {
                // end of quotation
                quotec = None;
                match it.next() {
                    Some((npos, nx)) if nx.is_whitespace() => {
                        // simple case: the ending quote is followed by an separator
                        // we can thus skip the whitespace and return our item
                        self.input = &self.input[npos..];
                        return ret.finish_cvg().map(Ok);
                    }
                    Some((_, nx)) if ch_is_quote(nx) => {
                        // medium case: the ending quote if directly followed by another quote
                        // thus, remain in quote mode
                        quotec = Some(nx);
                    }
                    Some((_, nx)) => {
                        // complex case: the ending quote is followed by more data which
                        // belongs to the same argument
                        ret.push_owned(nx);
                    }
                    None => {
                        // simple case: the ending quote is followed by EOF
                        self.input = "";
                        return ret.finish_cvg().map(Ok);
                    }
                }
                continue;
            }
            ret.push(cx);
        }
        if quotec.is_some() {
            return Some(Err(SyntaxError));
        }
        self.input = "";
        ret.finish_cvg().map(Ok)
    }
}

#[cfg(test)]
mod tests {
    use alloc::{string::String, vec::Vec};

    /// split_shellwords tests were taken from
    /// https://docs.rs/shellwords/1.1.0/src/shellwords/lib.rs.html
    /// License: MIT
    fn split(x: &str) -> Result<Vec<String>, super::SyntaxError> {
        super::ShellwordSplitter::new(x)
            .map(|i| i.map(super::Cow::into_owned))
            .collect()
    }

    #[test]
    fn nothing_special() {
        assert_eq!(split("a b c d").unwrap(), ["a", "b", "c", "d"]);
    }

    #[test]
    fn quoted_strings() {
        assert_eq!(split("a \"b b\" a").unwrap(), ["a", "b b", "a"]);
    }

    #[test]
    fn escaped_double_quotes() {
        assert_eq!(split("a \"\\\"b\\\" c\" d").unwrap(), ["a", "\"b\" c", "d"]);
    }

    #[test]
    fn escaped_single_quotes() {
        assert_eq!(split("a \"'b' c\" d").unwrap(), ["a", "'b' c", "d"]);
    }

    #[test]
    fn escaped_spaces() {
        assert_eq!(split("a b\\ c d").unwrap(), ["a", "b c", "d"]);
    }

    #[test]
    fn start_with_qspaces() {
        assert_eq!(split("\"  \" b c").unwrap(), ["  ", "b", "c"]);
    }

    #[test]
    fn bad_double_quotes() {
        split("a \"b c d e").unwrap_err();
    }

    #[test]
    fn bad_single_quotes() {
        split("a 'b c d e").unwrap_err();
    }

    #[test]
    fn bad_quotes() {
        split("one '\"\"\"").unwrap_err();
    }

    #[test]
    fn trailing_whitespace() {
        assert_eq!(split("a b c d ").unwrap(), ["a", "b", "c", "d"]);
    }
}