Skip to main content

pagesift_syntax/scanner/
bash.rs

1//! Bash 外部扫描器,移植自 tree-sitter-bash 的 `src/scanner.c`(MIT,Copyright (c) 2017 Max Brunsfeld)。
2//! 官方代码里的 `goto` 改成了分段函数 + 跳转枚举;here-doc 数组的复用方式(反序列化不截断)按原样保留。
3
4mod front;
5mod rest;
6
7use super::{MAX_SERIALIZED, ScanLexer, Scanner, is_alpha, is_space};
8
9const HEREDOC_START: usize = 0;
10const SIMPLE_HEREDOC_BODY: usize = 1;
11const HEREDOC_BODY_BEGINNING: usize = 2;
12const HEREDOC_CONTENT: usize = 3;
13const HEREDOC_END: usize = 4;
14const FILE_DESCRIPTOR: usize = 5;
15const EMPTY_VALUE: usize = 6;
16const CONCAT: usize = 7;
17const VARIABLE_NAME: usize = 8;
18const TEST_OPERATOR: usize = 9;
19const REGEX: usize = 10;
20const REGEX_NO_SLASH: usize = 11;
21const REGEX_NO_SPACE: usize = 12;
22const EXPANSION_WORD: usize = 13;
23const EXTGLOB_PATTERN: usize = 14;
24const BARE_DOLLAR: usize = 15;
25const BRACE_START: usize = 16;
26const IMMEDIATE_DOUBLE_HASH: usize = 17;
27const EXTERNAL_EXPANSION_SYM_HASH: usize = 18;
28const EXTERNAL_EXPANSION_SYM_BANG: usize = 19;
29const EXTERNAL_EXPANSION_SYM_EQUAL: usize = 20;
30const CLOSING_BRACE: usize = 21;
31const CLOSING_BRACKET: usize = 22;
32const HEREDOC_ARROW: usize = 23;
33const HEREDOC_ARROW_DASH: usize = 24;
34const NEWLINE: usize = 25;
35const OPENING_PAREN: usize = 26;
36const ERROR_RECOVERY: usize = 28;
37
38#[derive(Clone, Default)]
39struct Heredoc {
40    is_raw: bool,
41    started: bool,
42    allows_indent: bool,
43    /// 与官方一样,`advance_word` 读出的分隔符末尾带一个 0 字节。
44    delimiter: Vec<u8>,
45    leading: Vec<u8>,
46}
47
48#[derive(Default)]
49pub struct Bash {
50    last_glob_paren_depth: u8,
51    ext_was_in_double_quote: bool,
52    ext_saw_outside_quote: bool,
53    heredocs: Vec<Heredoc>,
54}
55
56enum St {
57    Regex,
58    Extglob,
59    Expansion,
60    Brace,
61}
62
63enum Nx {
64    Ret(bool),
65    Go(St),
66}
67
68fn ws(c: char) -> bool {
69    is_space(c)
70}
71fn alpha(c: char) -> bool {
72    is_alpha(c)
73}
74fn alnum(c: char) -> bool {
75    c.is_alphanumeric()
76}
77fn low8(c: char) -> u8 {
78    (c as u32 & 0xFF) as u8
79}
80fn cstr(v: &[u8]) -> &[u8] {
81    let n = v.iter().position(|b| *b == 0).unwrap_or(v.len());
82    &v[..n]
83}
84
85fn reset_heredoc(h: &mut Heredoc) {
86    h.is_raw = false;
87    h.started = false;
88    h.allows_indent = false;
89    h.delimiter.clear();
90}
91
92fn advance_word(lx: &mut ScanLexer, out: &mut Vec<u8>) -> bool {
93    let mut empty = true;
94    let mut quote = '\0';
95    if lx.lookahead() == '\'' || lx.lookahead() == '"' {
96        quote = lx.lookahead();
97        lx.next();
98    }
99    while lx.lookahead() != '\0'
100        && !(if quote != '\0' {
101            lx.lookahead() == quote || lx.lookahead() == '\r' || lx.lookahead() == '\n'
102        } else {
103            ws(lx.lookahead())
104        })
105    {
106        if lx.lookahead() == '\\' {
107            lx.next();
108            if lx.lookahead() == '\0' {
109                return false;
110            }
111        }
112        empty = false;
113        out.push(low8(lx.lookahead()));
114        lx.next();
115    }
116    out.push(0);
117    if quote != '\0' && lx.lookahead() == quote {
118        lx.next();
119    }
120    !empty
121}
122
123fn bare_dollar(lx: &mut ScanLexer) -> bool {
124    while ws(lx.lookahead()) && lx.lookahead() != '\n' && !lx.eof() {
125        lx.skip();
126    }
127    if lx.lookahead() == '$' {
128        lx.next();
129        lx.set_result(BARE_DOLLAR as u16);
130        lx.mark_end();
131        return ws(lx.lookahead()) || lx.eof() || lx.lookahead() == '"';
132    }
133    false
134}
135
136fn heredoc_start(h: &mut Heredoc, lx: &mut ScanLexer) -> bool {
137    while ws(lx.lookahead()) {
138        lx.skip();
139    }
140    lx.set_result(HEREDOC_START as u16);
141    h.is_raw = matches!(lx.lookahead(), '\'' | '"' | '\\');
142    let found = advance_word(lx, &mut h.delimiter);
143    if !found {
144        h.delimiter.clear();
145        return false;
146    }
147    found
148}
149
150fn heredoc_end_identifier(h: &mut Heredoc, lx: &mut ScanLexer) -> bool {
151    h.leading.clear();
152    let mut size = 0usize;
153    if !h.delimiter.is_empty() {
154        while lx.lookahead() != '\0'
155            && lx.lookahead() != '\n'
156            && size < h.delimiter.len()
157            && (h.delimiter[size] as i8 as i32) == lx.lookahead() as i32
158            && h.leading.len() < h.delimiter.len()
159        {
160            h.leading.push(low8(lx.lookahead()));
161            lx.next();
162            size += 1;
163        }
164    }
165    h.leading.push(0);
166    if h.delimiter.is_empty() {
167        false
168    } else {
169        cstr(&h.leading) == cstr(&h.delimiter)
170    }
171}
172
173impl Bash {
174    fn heredoc_content(&mut self, lx: &mut ScanLexer, middle: usize, end: usize) -> bool {
175        let mut did_advance = false;
176        let last = self.heredocs.len() - 1;
177        loop {
178            match lx.lookahead() {
179                '\0' => {
180                    if lx.eof() && did_advance {
181                        reset_heredoc(&mut self.heredocs[last]);
182                        lx.set_result(end as u16);
183                        return true;
184                    }
185                    return false;
186                }
187                '\\' => {
188                    did_advance = true;
189                    lx.next();
190                    lx.next();
191                }
192                '$' => {
193                    if self.heredocs[last].is_raw {
194                        did_advance = true;
195                        lx.next();
196                        continue;
197                    }
198                    if did_advance {
199                        lx.mark_end();
200                        lx.set_result(middle as u16);
201                        self.heredocs[last].started = true;
202                        lx.next();
203                        if alpha(lx.lookahead()) || lx.lookahead() == '{' || lx.lookahead() == '(' {
204                            return true;
205                        }
206                        continue;
207                    }
208                    if middle == HEREDOC_BODY_BEGINNING && lx.column() == 0 {
209                        lx.set_result(middle as u16);
210                        self.heredocs[last].started = true;
211                        return true;
212                    }
213                    return false;
214                }
215                '\n' => {
216                    if !did_advance {
217                        lx.skip();
218                    } else {
219                        lx.next();
220                    }
221                    did_advance = true;
222                    if self.heredocs[last].allows_indent {
223                        while ws(lx.lookahead()) {
224                            lx.next();
225                        }
226                    }
227                    lx.set_result(if self.heredocs[last].started {
228                        middle
229                    } else {
230                        end
231                    } as u16);
232                    lx.mark_end();
233                    if heredoc_end_identifier(&mut self.heredocs[last], lx) {
234                        if lx.result as usize == HEREDOC_END {
235                            self.heredocs.pop();
236                        }
237                        return true;
238                    }
239                }
240                _ => {
241                    if lx.column() == 0 {
242                        while ws(lx.lookahead()) {
243                            if did_advance {
244                                lx.next();
245                            } else {
246                                lx.skip();
247                            }
248                        }
249                        if end != SIMPLE_HEREDOC_BODY {
250                            lx.set_result(middle as u16);
251                            if heredoc_end_identifier(&mut self.heredocs[last], lx) {
252                                return true;
253                            }
254                        }
255                        if end == SIMPLE_HEREDOC_BODY {
256                            lx.set_result(end as u16);
257                            lx.mark_end();
258                            if heredoc_end_identifier(&mut self.heredocs[last], lx) {
259                                return true;
260                            }
261                        }
262                    }
263                    did_advance = true;
264                    lx.next();
265                }
266            }
267        }
268    }
269}
270
271impl Scanner for Bash {
272    fn serialize(&self, out: &mut Vec<u8>) {
273        out.push(self.last_glob_paren_depth);
274        out.push(self.ext_was_in_double_quote as u8);
275        out.push(self.ext_saw_outside_quote as u8);
276        out.push(self.heredocs.len() as u8);
277        for h in &self.heredocs {
278            if out.len() + 3 + 4 + h.delimiter.len() >= MAX_SERIALIZED {
279                out.clear();
280                return;
281            }
282            out.push(h.is_raw as u8);
283            out.push(h.started as u8);
284            out.push(h.allows_indent as u8);
285            out.extend_from_slice(&(h.delimiter.len() as u32).to_le_bytes());
286            out.extend_from_slice(&h.delimiter);
287        }
288    }
289
290    /// 与官方一致:长度为 0 只清空已有的 here-doc 项(不删除),否则逐项覆盖、不截断多余项。
291    fn deserialize(&mut self, d: &[u8]) {
292        if d.is_empty() {
293            for h in &mut self.heredocs {
294                reset_heredoc(h);
295            }
296            return;
297        }
298        if d.len() < 4 {
299            return;
300        }
301        self.last_glob_paren_depth = d[0];
302        self.ext_was_in_double_quote = d[1] != 0;
303        self.ext_saw_outside_quote = d[2] != 0;
304        let count = d[3] as usize;
305        let mut p = 4;
306        for i in 0..count {
307            if p + 7 > d.len() {
308                break;
309            }
310            if i >= self.heredocs.len() {
311                self.heredocs.push(Heredoc::default());
312            }
313            let h = &mut self.heredocs[i];
314            h.is_raw = d[p] != 0;
315            h.started = d[p + 1] != 0;
316            h.allows_indent = d[p + 2] != 0;
317            let n = u32::from_le_bytes([d[p + 3], d[p + 4], d[p + 5], d[p + 6]]) as usize;
318            p += 7;
319            let n = n.min(d.len() - p);
320            h.delimiter = d[p..p + n].to_vec();
321            p += n;
322        }
323    }
324
325    fn scan(&mut self, lx: &mut ScanLexer, v: &[bool]) -> bool {
326        let mut st = match self.front(lx, v) {
327            Nx::Ret(b) => return b,
328            Nx::Go(s) => s,
329        };
330        loop {
331            let nx = match st {
332                St::Regex => self.regex(lx, v),
333                St::Extglob => self.extglob(lx, v),
334                St::Expansion => self.expansion_word(lx, v),
335                St::Brace => return self.brace_start(lx, v),
336            };
337            match nx {
338                Nx::Ret(b) => return b,
339                Nx::Go(s) => st = s,
340            }
341        }
342    }
343}