Skip to main content

lean_ctx_ext/
compound_lexer.rs

1// SPDX-License-Identifier: Apache-2.0
2/// Splits a compound shell command into segments separated by `&&`, `||`, `;`.
3/// Pipes (`|`) are treated specially: only the left side of a pipe is eligible
4/// for rewriting (the right side consumes output format and must stay raw).
5///
6/// Respects single quotes, double quotes, backtick-quotes, and `$(...)` subshells
7/// so that operators inside quoted strings are not treated as separators.
8///
9/// Returns a `Vec<Segment>` where each entry is either a command segment or an
10/// operator token that should be emitted verbatim.
11
12#[derive(Debug, Clone, PartialEq)]
13pub enum Segment {
14    Command(String),
15    Operator(String),
16}
17
18pub fn split_compound(input: &str) -> Vec<Segment> {
19    let input = input.trim();
20    if input.is_empty() {
21        return vec![];
22    }
23
24    if contains_heredoc(input) {
25        return vec![Segment::Command(input.to_string())];
26    }
27
28    let chars: Vec<char> = input.chars().collect();
29    let mut segments: Vec<Segment> = Vec::new();
30    let mut current = String::new();
31    let mut i = 0;
32    let len = chars.len();
33
34    while i < len {
35        let ch = chars[i];
36
37        match ch {
38            '\'' => {
39                current.push(ch);
40                i += 1;
41                while i < len && chars[i] != '\'' {
42                    current.push(chars[i]);
43                    i += 1;
44                }
45                if i < len {
46                    current.push('\'');
47                    i += 1;
48                }
49            }
50            '"' => {
51                current.push(ch);
52                i += 1;
53                while i < len && chars[i] != '"' {
54                    if chars[i] == '\\' && i + 1 < len {
55                        current.push('\\');
56                        current.push(chars[i + 1]);
57                        i += 2;
58                        continue;
59                    }
60                    current.push(chars[i]);
61                    i += 1;
62                }
63                if i < len {
64                    current.push('"');
65                    i += 1;
66                }
67            }
68            '`' => {
69                current.push(ch);
70                i += 1;
71                while i < len && chars[i] != '`' {
72                    current.push(chars[i]);
73                    i += 1;
74                }
75                if i < len {
76                    current.push('`');
77                    i += 1;
78                }
79            }
80            '$' if i + 1 < len && chars[i + 1] == '(' => {
81                current.push('$');
82                current.push('(');
83                i += 2;
84                let mut depth = 1;
85                while i < len && depth > 0 {
86                    if chars[i] == '(' {
87                        depth += 1;
88                    } else if chars[i] == ')' {
89                        depth -= 1;
90                    }
91                    current.push(chars[i]);
92                    i += 1;
93                }
94            }
95            '\\' if i + 1 < len => {
96                current.push('\\');
97                current.push(chars[i + 1]);
98                i += 2;
99            }
100            '&' if i + 1 < len && chars[i + 1] == '&' => {
101                push_command(&mut segments, &current);
102                current.clear();
103                segments.push(Segment::Operator("&&".to_string()));
104                i += 2;
105            }
106            '|' if i + 1 < len && chars[i + 1] == '|' => {
107                push_command(&mut segments, &current);
108                current.clear();
109                segments.push(Segment::Operator("||".to_string()));
110                i += 2;
111            }
112            '|' => {
113                push_command(&mut segments, &current);
114                current.clear();
115                segments.push(Segment::Operator("|".to_string()));
116                let rest: String = chars[i + 1..].iter().collect::<String>();
117                let rest = rest.trim().to_string();
118                if !rest.is_empty() {
119                    segments.push(Segment::Command(rest));
120                }
121                return segments;
122            }
123            ';' => {
124                push_command(&mut segments, &current);
125                current.clear();
126                segments.push(Segment::Operator(";".to_string()));
127                i += 1;
128            }
129            _ => {
130                current.push(ch);
131                i += 1;
132            }
133        }
134    }
135
136    push_command(&mut segments, &current);
137    segments
138}
139
140fn push_command(segments: &mut Vec<Segment>, cmd: &str) {
141    let trimmed = cmd.trim();
142    if !trimmed.is_empty() {
143        segments.push(Segment::Command(trimmed.to_string()));
144    }
145}
146
147fn contains_heredoc(input: &str) -> bool {
148    input.contains("<<") || input.contains("$((")
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154
155    #[test]
156    fn simple_command() {
157        let segs = split_compound("git status");
158        assert_eq!(segs, vec![Segment::Command("git status".into())]);
159    }
160
161    #[test]
162    fn and_chain() {
163        let segs = split_compound("cd src && git status && echo done");
164        assert_eq!(
165            segs,
166            vec![
167                Segment::Command("cd src".into()),
168                Segment::Operator("&&".into()),
169                Segment::Command("git status".into()),
170                Segment::Operator("&&".into()),
171                Segment::Command("echo done".into()),
172            ]
173        );
174    }
175
176    #[test]
177    fn pipe_stops_at_right() {
178        let segs = split_compound("git log --oneline | grep fix");
179        assert_eq!(
180            segs,
181            vec![
182                Segment::Command("git log --oneline".into()),
183                Segment::Operator("|".into()),
184                Segment::Command("grep fix".into()),
185            ]
186        );
187    }
188
189    #[test]
190    fn pipe_in_chain() {
191        let segs = split_compound("cd src && git log | head -5");
192        assert_eq!(
193            segs,
194            vec![
195                Segment::Command("cd src".into()),
196                Segment::Operator("&&".into()),
197                Segment::Command("git log".into()),
198                Segment::Operator("|".into()),
199                Segment::Command("head -5".into()),
200            ]
201        );
202    }
203
204    #[test]
205    fn semicolons() {
206        let segs = split_compound("git add .; git commit -m 'fix'");
207        assert_eq!(
208            segs,
209            vec![
210                Segment::Command("git add .".into()),
211                Segment::Operator(";".into()),
212                Segment::Command("git commit -m 'fix'".into()),
213            ]
214        );
215    }
216
217    #[test]
218    fn or_chain() {
219        let segs = split_compound("git pull || echo failed");
220        assert_eq!(
221            segs,
222            vec![
223                Segment::Command("git pull".into()),
224                Segment::Operator("||".into()),
225                Segment::Command("echo failed".into()),
226            ]
227        );
228    }
229
230    #[test]
231    fn quoted_ampersand_not_split() {
232        let segs = split_compound("echo 'foo && bar'");
233        assert_eq!(segs, vec![Segment::Command("echo 'foo && bar'".into())]);
234    }
235
236    #[test]
237    fn double_quoted_pipe_not_split() {
238        let segs = split_compound(r#"echo "hello | world""#);
239        assert_eq!(
240            segs,
241            vec![Segment::Command(r#"echo "hello | world""#.into())]
242        );
243    }
244
245    #[test]
246    fn heredoc_kept_whole() {
247        let segs = split_compound("cat <<EOF\nhello\nEOF && echo done");
248        assert_eq!(
249            segs,
250            vec![Segment::Command(
251                "cat <<EOF\nhello\nEOF && echo done".into()
252            )]
253        );
254    }
255
256    #[test]
257    fn subshell_not_split() {
258        let segs = split_compound("echo $(git status && echo ok)");
259        assert_eq!(
260            segs,
261            vec![Segment::Command("echo $(git status && echo ok)".into())]
262        );
263    }
264}