Skip to main content

pagesift_syntax/scanner/
php.rs

1//! PHP 外部扫描器,移植自 tree-sitter-php 的 `common/scanner.h`(MIT,Copyright (c) 2017 Josh Vera, GitHub)。
2
3use super::{MAX_SERIALIZED, ScanLexer, Scanner, is_space};
4
5const AUTOMATIC_SEMICOLON: usize = 0;
6const ENCAPSED_STRING_CHARS: usize = 1;
7const ENCAPSED_STRING_CHARS_AFTER_VARIABLE: usize = 2;
8const EXECUTION_STRING_CHARS: usize = 3;
9const EXECUTION_STRING_CHARS_AFTER_VARIABLE: usize = 4;
10const ENCAPSED_STRING_CHARS_HEREDOC: usize = 5;
11const ENCAPSED_STRING_CHARS_AFTER_VARIABLE_HEREDOC: usize = 6;
12const EOF_TOKEN: usize = 7;
13const HEREDOC_START: usize = 8;
14const HEREDOC_END: usize = 9;
15const NOWDOC_STRING: usize = 10;
16const SENTINEL_ERROR: usize = 11;
17
18#[derive(Default)]
19pub struct Php {
20    heredocs: Vec<(bool, Vec<char>)>,
21}
22
23fn is_name_char(c: char) -> bool {
24    c.is_alphanumeric() || c == '_' || c as u32 >= 0x80
25}
26
27fn is_escapable(lx: &mut ScanLexer) -> bool {
28    let c = lx.lookahead();
29    if matches!(c, 'n' | 'r' | 't' | 'v' | 'e' | 'f' | '\\' | '$' | '"') {
30        return true;
31    }
32    if c == 'x' {
33        lx.next();
34        return lx.lookahead().is_ascii_hexdigit();
35    }
36    if c == 'u' {
37        return true;
38    }
39    matches!(lx.lookahead(), '0'..='7')
40}
41
42fn heredoc_word(lx: &mut ScanLexer) -> Vec<char> {
43    let mut w = Vec::new();
44    while is_name_char(lx.lookahead()) {
45        w.push(lx.lookahead());
46        lx.next();
47    }
48    w
49}
50
51fn whitespace(lx: &mut ScanLexer) -> bool {
52    loop {
53        while is_space(lx.lookahead()) {
54            lx.next();
55        }
56        if lx.lookahead() == '/' {
57            lx.next();
58            if lx.lookahead() == '/' {
59                lx.next();
60                while lx.lookahead() != '\0' && lx.lookahead() != '\n' {
61                    lx.next();
62                }
63            } else {
64                return false;
65            }
66        } else {
67            return true;
68        }
69    }
70}
71
72impl Php {
73    fn nowdoc(&self, lx: &mut ScanLexer) -> bool {
74        let mut consumed = false;
75        let Some((_, tag)) = self.heredocs.last() else {
76            return false;
77        };
78        while is_space(lx.lookahead()) {
79            lx.next();
80            consumed = true;
81        }
82        let mut matched = false;
83        for (i, &c) in tag.iter().enumerate() {
84            if lx.lookahead() != c {
85                break;
86            }
87            lx.next();
88            consumed = true;
89            matched = i == tag.len() - 1 && !is_name_char(lx.lookahead());
90        }
91        if matched {
92            return false;
93        }
94        let mut has_content = consumed;
95        loop {
96            lx.mark_end();
97            match lx.lookahead() {
98                '\n' | '\r' => return has_content,
99                _ => {
100                    if lx.eof() {
101                        return false;
102                    }
103                    lx.next();
104                }
105            }
106            has_content = true;
107        }
108    }
109
110    fn encapsed(&self, lx: &mut ScanLexer, mut after_var: bool, heredoc: bool, exec: bool) -> bool {
111        let mut consumed = false;
112        if heredoc && !self.heredocs.is_empty() {
113            while is_space(lx.lookahead()) && lx.lookahead() != '\r' && lx.lookahead() != '\n' {
114                lx.next();
115                consumed = true;
116            }
117            let tag = &self.heredocs.last().unwrap().1;
118            let mut matched = false;
119            for (i, &c) in tag.iter().enumerate() {
120                if lx.lookahead() != c {
121                    break;
122                }
123                consumed = true;
124                lx.next();
125                matched = i == tag.len() - 1 && !is_name_char(lx.lookahead());
126            }
127            if matched {
128                return false;
129            }
130        }
131        let mut has_content = consumed;
132        loop {
133            lx.mark_end();
134            match lx.lookahead() {
135                '"' => {
136                    if !heredoc && !exec {
137                        return has_content;
138                    }
139                    lx.next();
140                }
141                '`' => {
142                    if exec {
143                        return has_content;
144                    }
145                    lx.next();
146                }
147                '\n' | '\r' => {
148                    if heredoc {
149                        return has_content;
150                    }
151                    lx.next();
152                }
153                '\\' => {
154                    lx.next();
155                    if lx.lookahead() == '{' {
156                        lx.next();
157                    } else if exec && lx.lookahead() == '`' {
158                        return has_content;
159                    } else if heredoc && lx.lookahead() == '\\' {
160                        lx.next();
161                    } else if is_escapable(lx) {
162                        return has_content;
163                    }
164                }
165                '$' => {
166                    lx.next();
167                    if (is_name_char(lx.lookahead()) && !lx.lookahead().is_ascii_digit())
168                        || lx.lookahead() == '{'
169                    {
170                        return has_content;
171                    }
172                }
173                '-' if after_var => {
174                    lx.next();
175                    if lx.lookahead() == '>' {
176                        lx.next();
177                        if is_name_char(lx.lookahead()) {
178                            return has_content;
179                        }
180                    }
181                }
182                // C 里 `-` 在非变量后落入 `[` 分支
183                '-' | '[' => {
184                    if after_var && lx.lookahead() == '[' {
185                        return has_content;
186                    }
187                    lx.next();
188                }
189                '{' => {
190                    lx.next();
191                    if lx.lookahead() == '$' {
192                        return has_content;
193                    }
194                }
195                _ => {
196                    if lx.eof() {
197                        return false;
198                    }
199                    lx.next();
200                }
201            }
202            has_content = true;
203            after_var = false;
204        }
205    }
206}
207
208impl Scanner for Php {
209    fn serialize(&self, out: &mut Vec<u8>) {
210        out.push(self.heredocs.len() as u8);
211        for (indent, word) in &self.heredocs {
212            if out.len() + 5 + word.len() * 4 >= MAX_SERIALIZED {
213                out.clear();
214                return;
215            }
216            out.push(*indent as u8);
217            out.extend_from_slice(&(word.len() as u32).to_le_bytes());
218            for c in word {
219                out.extend_from_slice(&(*c as u32).to_le_bytes());
220            }
221        }
222    }
223
224    fn deserialize(&mut self, d: &[u8]) {
225        self.heredocs.clear();
226        if d.is_empty() {
227            return;
228        }
229        let n = d[0] as usize;
230        let mut p = 1;
231        for _ in 0..n {
232            if p + 5 > d.len() {
233                break;
234            }
235            let indent = d[p] != 0;
236            let len = u32::from_le_bytes([d[p + 1], d[p + 2], d[p + 3], d[p + 4]]) as usize;
237            p += 5;
238            let mut word = Vec::new();
239            for _ in 0..len {
240                if p + 4 > d.len() {
241                    break;
242                }
243                word.push(
244                    char::from_u32(u32::from_le_bytes([d[p], d[p + 1], d[p + 2], d[p + 3]]))
245                        .unwrap_or('\u{FFFD}'),
246                );
247                p += 4;
248            }
249            self.heredocs.push((indent, word));
250        }
251    }
252
253    fn scan(&mut self, lx: &mut ScanLexer, valid: &[bool]) -> bool {
254        if valid[SENTINEL_ERROR] {
255            return false;
256        }
257        lx.mark_end();
258        let enc = [
259            (ENCAPSED_STRING_CHARS_AFTER_VARIABLE, true, false, false),
260            (ENCAPSED_STRING_CHARS, false, false, false),
261            (EXECUTION_STRING_CHARS_AFTER_VARIABLE, true, false, true),
262            (EXECUTION_STRING_CHARS, false, false, true),
263            (
264                ENCAPSED_STRING_CHARS_AFTER_VARIABLE_HEREDOC,
265                true,
266                true,
267                false,
268            ),
269            (ENCAPSED_STRING_CHARS_HEREDOC, false, true, false),
270        ];
271        for (sym, after, heredoc, exec) in enc {
272            if valid[sym] {
273                lx.set_result(sym as u16);
274                return self.encapsed(lx, after, heredoc, exec);
275            }
276        }
277        if valid[NOWDOC_STRING] {
278            lx.set_result(NOWDOC_STRING as u16);
279            return self.nowdoc(lx);
280        }
281        if valid[HEREDOC_END] {
282            lx.set_result(HEREDOC_END as u16);
283            let Some((_, tag)) = self.heredocs.last() else {
284                return false;
285            };
286            let tag = tag.clone();
287            while is_space(lx.lookahead()) {
288                lx.skip();
289            }
290            if heredoc_word(lx) != tag {
291                return false;
292            }
293            lx.mark_end();
294            self.heredocs.pop();
295            return true;
296        }
297        if !whitespace(lx) {
298            return false;
299        }
300        if valid[EOF_TOKEN] && lx.eof() {
301            lx.set_result(EOF_TOKEN as u16);
302            return true;
303        }
304        if valid[HEREDOC_START] {
305            lx.set_result(HEREDOC_START as u16);
306            while is_space(lx.lookahead()) {
307                lx.skip();
308            }
309            let word = heredoc_word(lx);
310            if word.is_empty() {
311                return false;
312            }
313            lx.mark_end();
314            self.heredocs.push((false, word));
315            return true;
316        }
317        if valid[AUTOMATIC_SEMICOLON] {
318            lx.set_result(AUTOMATIC_SEMICOLON as u16);
319            if lx.lookahead() != '?' {
320                return false;
321            }
322            lx.next();
323            return lx.lookahead() == '>';
324        }
325        false
326    }
327}