Skip to main content

pagesift_syntax/scanner/
css.rs

1//! CSS 外部扫描器,移植自 tree-sitter-css 的 `src/scanner.c`(MIT,Copyright (c) 2018 Max Brunsfeld)。
2//! 无状态:序列化为空。
3
4use super::{ScanLexer, Scanner, is_space};
5
6const DESCENDANT_OP: usize = 0;
7const PSEUDO_CLASS_SELECTOR_COLON: usize = 1;
8const ERROR_RECOVERY: usize = 2;
9
10#[derive(Default)]
11pub struct Css;
12
13impl Scanner for Css {
14    fn scan(&mut self, lx: &mut ScanLexer, v: &[bool]) -> bool {
15        if v[ERROR_RECOVERY] {
16            return false;
17        }
18        if is_space(lx.lookahead()) && v[DESCENDANT_OP] {
19            lx.set_result(DESCENDANT_OP as u16);
20            lx.skip();
21            while is_space(lx.lookahead()) {
22                lx.skip();
23            }
24            lx.mark_end();
25            let c = lx.lookahead();
26            if matches!(c, '#' | '.' | '[' | '-' | '*') || c.is_alphanumeric() {
27                return true;
28            }
29            if c == ':' {
30                lx.next();
31                if is_space(lx.lookahead()) {
32                    return false;
33                }
34                loop {
35                    if matches!(lx.lookahead(), ';' | '}') || lx.eof() {
36                        return false;
37                    }
38                    if lx.lookahead() == '{' {
39                        return true;
40                    }
41                    lx.next();
42                }
43            }
44        }
45        if v[PSEUDO_CLASS_SELECTOR_COLON] {
46            while is_space(lx.lookahead()) {
47                lx.skip();
48            }
49            if lx.lookahead() == ':' {
50                lx.next();
51                if lx.lookahead() == ':' {
52                    return false;
53                }
54                lx.mark_end();
55                lx.set_result(PSEUDO_CLASS_SELECTOR_COLON as u16);
56                // 需要 `{` 才是伪类选择器,`;` 说明是属性;注释里的字符不算
57                let mut in_comment = false;
58                while !matches!(lx.lookahead(), ';' | '}') && !lx.eof() {
59                    lx.next();
60                    if lx.lookahead() == '{' && !in_comment {
61                        return true;
62                    }
63                    if lx.lookahead() == '/' && !in_comment {
64                        lx.next();
65                        if lx.lookahead() == '*' {
66                            in_comment = true;
67                        }
68                    } else if lx.lookahead() == '*' && in_comment {
69                        lx.next();
70                        if lx.lookahead() == '/' {
71                            in_comment = false;
72                        }
73                    }
74                }
75                // 到了输入末尾也返回伪类选择器,错误恢复时更好
76                return lx.eof();
77            }
78        }
79        false
80    }
81
82    fn serialize(&self, _out: &mut Vec<u8>) {}
83
84    fn deserialize(&mut self, _data: &[u8]) {}
85}