Skip to main content

pagesift_syntax/scanner/
ocaml.rs

1//! OCaml 外部扫描器(`ocaml`、`interface`、`type` 三个语法共用),移植自 tree-sitter-ocaml 的
2//! `common/scanner.h`(MIT,Copyright (c) 2020 Max Brunsfeld and Pieter Goetschalckx)。
3//!
4//! 官方序列化把引用字符串的分隔符数组按“元素个数”当字节数拷贝(只拷前几个字节),反序列化时再按字节数
5//! 当元素个数还原;这里照原样保留,多出来的元素补 0。
6
7use super::{ScanLexer, Scanner, is_space};
8
9const COMMENT: usize = 0;
10const LEFT_QUOTED_STRING_DELIM: usize = 1;
11const RIGHT_QUOTED_STRING_DELIM: usize = 2;
12const STRING_DELIM: usize = 3;
13const LINE_NUMBER_DIRECTIVE: usize = 4;
14const NULL_CHARACTER: usize = 5;
15const ERROR_SENTINEL: usize = 6;
16
17const LOWER_UTF8_CHARS: [u32; 35] = [
18    0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee,
19    0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
20    0x153, 0x161, 0x17e,
21];
22
23const LOWER_UTF8_PAIRS: [(u32, u32, u32); 29] = [
24    ('a' as u32, 0x300, 0xe0),
25    ('a' as u32, 0x301, 0xe1),
26    ('a' as u32, 0x302, 0xe2),
27    ('a' as u32, 0x303, 0xe3),
28    ('a' as u32, 0x308, 0xe4),
29    ('a' as u32, 0x30a, 0xe5),
30    ('c' as u32, 0x327, 0xe7),
31    ('e' as u32, 0x300, 0xe8),
32    ('e' as u32, 0x301, 0xe9),
33    ('e' as u32, 0x302, 0xea),
34    ('e' as u32, 0x308, 0xeb),
35    ('i' as u32, 0x300, 0xec),
36    ('i' as u32, 0x301, 0xed),
37    ('i' as u32, 0x302, 0xee),
38    ('i' as u32, 0x308, 0xef),
39    ('n' as u32, 0x303, 0xf1),
40    ('o' as u32, 0x300, 0xf2),
41    ('o' as u32, 0x301, 0xf3),
42    ('o' as u32, 0x302, 0xf4),
43    ('o' as u32, 0x303, 0xf5),
44    ('o' as u32, 0x308, 0xf6),
45    ('s' as u32, 0x30c, 0x161),
46    ('u' as u32, 0x300, 0xf9),
47    ('u' as u32, 0x301, 0xfa),
48    ('u' as u32, 0x302, 0xfb),
49    ('u' as u32, 0x308, 0xfc),
50    ('y' as u32, 0x301, 0xfd),
51    ('y' as u32, 0x308, 0xff),
52    ('z' as u32, 0x30c, 0x17e),
53];
54
55#[derive(Default)]
56pub struct Ocaml {
57    in_string: bool,
58    /// 分隔符数组的底层内存:清空只改 `len`,内容保留(官方如此,反序列化的“半截覆盖”靠它复原)。
59    mem: Vec<u32>,
60    len: usize,
61}
62
63impl Ocaml {
64    fn grow(&mut self, n: usize) {
65        if self.mem.len() < n {
66            self.mem.resize(n, 0);
67        }
68    }
69}
70
71fn la(lx: &ScanLexer) -> u32 {
72    lx.lookahead() as u32
73}
74
75fn digit(lx: &ScanLexer) -> bool {
76    lx.lookahead().is_ascii_digit()
77}
78
79fn scan_string(lx: &mut ScanLexer) {
80    loop {
81        match lx.lookahead() {
82            '\\' => {
83                lx.next();
84                lx.next();
85            }
86            '"' => {
87                lx.next();
88                return;
89            }
90            '\0' => {
91                if lx.eof() {
92                    return;
93                }
94                lx.next();
95            }
96            _ => lx.next(),
97        }
98    }
99}
100
101/// 引用字符串分隔符里的一个字符;遇到 `|` 或不合法字符返回 0。
102fn scan_delim_char(lx: &mut ScanLexer) -> u32 {
103    let c = la(lx);
104    if c == '|' as u32 {
105        return 0;
106    }
107    if c == '_' as u32 {
108        lx.next();
109        return c;
110    }
111    if (b'a' as u32..=b'z' as u32).contains(&c) {
112        lx.next();
113        let d = la(lx);
114        if (0x300..=0x327).contains(&d)
115            && let Some(&(_, _, r)) = LOWER_UTF8_PAIRS.iter().find(|p| p.0 == c && p.1 == d)
116        {
117            lx.next();
118            return r;
119        }
120        return c;
121    }
122    if LOWER_UTF8_CHARS.contains(&c) {
123        lx.next();
124        return c;
125    }
126    0
127}
128
129fn is_lowercase_ext(c: u32) -> bool {
130    (b'a' as u32..=b'z' as u32).contains(&c) || c == '_' as u32 || c >= 192
131}
132
133fn is_identstart(c: u32) -> bool {
134    is_lowercase_ext(c) || (b'A' as u32..=b'Z' as u32).contains(&c)
135}
136
137fn is_identchar(c: u32) -> bool {
138    is_identstart(c) || (b'0' as u32..=b'9' as u32).contains(&c) || c == '\'' as u32
139}
140
141fn scan_identifier(lx: &mut ScanLexer) -> bool {
142    if is_identstart(la(lx)) {
143        lx.next();
144        while is_identchar(la(lx)) {
145            lx.next();
146        }
147        return true;
148    }
149    false
150}
151
152fn scan_extattrident(lx: &mut ScanLexer) -> bool {
153    while scan_identifier(lx) {
154        if lx.lookahead() != '.' {
155            return true;
156        }
157        lx.next();
158    }
159    false
160}
161
162/// 字符字面量:返回最后一个字符(0 表示不是字符字面量或没有可回退的字符)。
163fn scan_character(lx: &mut ScanLexer) -> u32 {
164    let mut last = 0u32;
165    match lx.lookahead() {
166        '\\' => {
167            lx.next();
168            if digit(lx) {
169                lx.next();
170                for _ in 0..2 {
171                    if !digit(lx) {
172                        return 0;
173                    }
174                    lx.next();
175                }
176            } else {
177                match lx.lookahead() {
178                    'x' => {
179                        lx.next();
180                        for _ in 0..2 {
181                            if !digit(lx)
182                                && !lx.lookahead().to_ascii_uppercase().is_ascii_hexdigit()
183                            {
184                                return 0;
185                            }
186                            lx.next();
187                        }
188                    }
189                    'o' => {
190                        lx.next();
191                        for _ in 0..3 {
192                            if !digit(lx) || lx.lookahead() > '7' {
193                                return 0;
194                            }
195                            lx.next();
196                        }
197                    }
198                    '\'' | '"' | '\\' | 'n' | 't' | 'b' | 'r' | ' ' => {
199                        last = la(lx);
200                        lx.next();
201                    }
202                    _ => return 0,
203                }
204            }
205        }
206        '\'' => {}
207        '\r' => {
208            lx.next();
209            while lx.lookahead() == '\r' {
210                lx.next();
211            }
212            if lx.lookahead() != '\n' {
213                return 0;
214            }
215            lx.next();
216        }
217        '\0' => {
218            if lx.eof() {
219                return 0;
220            }
221            lx.next();
222        }
223        _ => {
224            if la(lx) < 256 {
225                last = la(lx);
226                lx.next();
227            } else {
228                return 0;
229            }
230        }
231    }
232    if lx.lookahead() == '\'' {
233        lx.next();
234        return 0;
235    }
236    last
237}
238
239impl Ocaml {
240    fn scan_left_delim(&mut self, lx: &mut ScanLexer) -> bool {
241        loop {
242            let c = scan_delim_char(lx);
243            if c == 0 {
244                break;
245            }
246            self.grow(self.len + 1);
247            self.mem[self.len] = c;
248            self.len += 1;
249        }
250        if lx.lookahead() == '|' {
251            lx.next();
252            self.in_string = true;
253            true
254        } else {
255            self.len = 0;
256            false
257        }
258    }
259
260    fn scan_right_delim(&mut self, lx: &mut ScanLexer) -> bool {
261        for i in 0..self.len {
262            if scan_delim_char(lx) != self.mem[i] {
263                return false;
264            }
265        }
266        if lx.lookahead() == '}' {
267            self.in_string = false;
268            self.len = 0;
269            true
270        } else {
271            false
272        }
273    }
274
275    fn scan_quoted_string(&mut self, lx: &mut ScanLexer) -> bool {
276        if !self.scan_left_delim(lx) {
277            return false;
278        }
279        loop {
280            match lx.lookahead() {
281                '|' => {
282                    lx.next();
283                    if self.scan_right_delim(lx) {
284                        return true;
285                    }
286                }
287                '\0' => {
288                    if lx.eof() {
289                        return false;
290                    }
291                    lx.next();
292                }
293                _ => lx.next(),
294            }
295        }
296    }
297
298    fn scan_comment(&mut self, lx: &mut ScanLexer) -> bool {
299        let mut last = 0u32;
300        let mut depth = 0u32;
301        if lx.lookahead() != '*' {
302            return false;
303        }
304        lx.next();
305        // 官方 `last` 表示“上一个字符已读出但没前进”;非 0 时先消耗它
306        let eat = |lx: &mut ScanLexer, last: &mut u32| {
307            if *last != 0 {
308                *last = 0;
309            } else {
310                lx.next();
311            }
312        };
313        loop {
314            let cur = if last != 0 { last } else { la(lx) };
315            match char::from_u32(cur).unwrap_or('\u{FFFD}') {
316                '(' => {
317                    eat(lx, &mut last);
318                    if lx.lookahead() == '*' {
319                        lx.next();
320                        depth += 1;
321                    }
322                }
323                '*' => {
324                    eat(lx, &mut last);
325                    if lx.lookahead() == ')' {
326                        lx.next();
327                        if depth == 0 {
328                            return true;
329                        }
330                        depth -= 1;
331                    }
332                }
333                '\'' => {
334                    eat(lx, &mut last);
335                    last = scan_character(lx);
336                }
337                '"' => {
338                    eat(lx, &mut last);
339                    scan_string(lx);
340                }
341                '{' => {
342                    eat(lx, &mut last);
343                    if lx.lookahead() == '%' {
344                        lx.next();
345                        if lx.lookahead() == '%' {
346                            lx.next();
347                        }
348                        if scan_extattrident(lx) {
349                            while is_space(lx.lookahead()) {
350                                lx.next();
351                            }
352                        } else {
353                            continue;
354                        }
355                    }
356                    if self.scan_quoted_string(lx) {
357                        lx.next();
358                    }
359                }
360                '\0' => {
361                    if lx.eof() {
362                        return true;
363                    }
364                    eat(lx, &mut last);
365                }
366                _ => {
367                    if scan_identifier(lx) || last != 0 {
368                        last = 0;
369                    } else {
370                        lx.next();
371                    }
372                }
373            }
374        }
375    }
376}
377
378impl Scanner for Ocaml {
379    fn scan(&mut self, lx: &mut ScanLexer, v: &[bool]) -> bool {
380        if !v[ERROR_SENTINEL]
381            && v[LEFT_QUOTED_STRING_DELIM]
382            && (is_lowercase_ext(la(lx)) || lx.lookahead() == '|')
383        {
384            lx.set_result(LEFT_QUOTED_STRING_DELIM as u16);
385            return self.scan_left_delim(lx);
386        }
387        if !v[ERROR_SENTINEL] && v[RIGHT_QUOTED_STRING_DELIM] && lx.lookahead() == '|' {
388            lx.next();
389            lx.set_result(RIGHT_QUOTED_STRING_DELIM as u16);
390            return self.scan_right_delim(lx);
391        }
392        if self.in_string && v[STRING_DELIM] && lx.lookahead() == '"' {
393            lx.next();
394            self.in_string = false;
395            lx.set_result(STRING_DELIM as u16);
396            return true;
397        }
398        while is_space(lx.lookahead()) {
399            lx.skip();
400        }
401        if !self.in_string && v[STRING_DELIM] && lx.lookahead() == '"' {
402            lx.next();
403            self.in_string = true;
404            lx.set_result(STRING_DELIM as u16);
405            return true;
406        }
407        if !self.in_string && v[LINE_NUMBER_DIRECTIVE] && lx.lookahead() == '#' && lx.column() == 0
408        {
409            lx.next();
410            while matches!(lx.lookahead(), ' ' | '\t') {
411                lx.next();
412            }
413            if !digit(lx) {
414                return false;
415            }
416            while digit(lx) {
417                lx.next();
418            }
419            while matches!(lx.lookahead(), ' ' | '\t') {
420                lx.next();
421            }
422            if lx.lookahead() != '"' {
423                return false;
424            }
425            lx.next();
426            while !matches!(lx.lookahead(), '\n' | '\r' | '"') && !lx.eof() {
427                lx.next();
428            }
429            if lx.lookahead() != '"' {
430                return false;
431            }
432            lx.next();
433            while !matches!(lx.lookahead(), '\n' | '\r') && !lx.eof() {
434                lx.next();
435            }
436            lx.set_result(LINE_NUMBER_DIRECTIVE as u16);
437            return true;
438        }
439        if !self.in_string && v[COMMENT] && lx.lookahead() == '(' {
440            lx.next();
441            lx.set_result(COMMENT as u16);
442            return self.scan_comment(lx);
443        }
444        if v[NULL_CHARACTER] && lx.lookahead() == '\0' && !lx.eof() {
445            lx.next();
446            lx.set_result(NULL_CHARACTER as u16);
447            return true;
448        }
449        false
450    }
451
452    fn serialize(&self, out: &mut Vec<u8>) {
453        out.push(self.in_string as u8);
454        let n = self.len;
455        if n < super::MAX_SERIALIZED {
456            let bytes: Vec<u8> = self.mem.iter().flat_map(|c| c.to_le_bytes()).collect();
457            out.extend_from_slice(&bytes[..n.min(bytes.len())]);
458        }
459    }
460
461    fn deserialize(&mut self, d: &[u8]) {
462        if d.is_empty() {
463            self.in_string = false;
464            self.len = 0;
465            return;
466        }
467        self.in_string = d[0] != 0;
468        let n = d.len() - 1;
469        if n > 0 {
470            self.grow(n);
471            for (i, b) in d[1..].iter().enumerate() {
472                let sh = 8 * (i % 4);
473                self.mem[i / 4] = (self.mem[i / 4] & !(0xff << sh)) | ((*b as u32) << sh);
474            }
475        }
476        self.len = n;
477    }
478}