Skip to main content

pagesift_syntax/scanner/
js.rs

1//! JavaScript 外部扫描器,移植自 tree-sitter-javascript 的 `src/scanner.c`(MIT,Copyright (c) 2014 Max Brunsfeld)。
2//! 模板字符、JSX 文本、三元问号与 HTML 注释的扫描也被 TypeScript 的扫描器复用。
3
4use super::{ScanLexer, Scanner, is_alpha, is_space};
5
6pub(super) const AUTOMATIC_SEMICOLON: usize = 0;
7pub(super) const TEMPLATE_CHARS: usize = 1;
8pub(super) const TERNARY_QMARK: usize = 2;
9pub(super) const HTML_COMMENT: usize = 3;
10pub(super) const LOGICAL_OR: usize = 4;
11pub(super) const ESCAPE_SEQUENCE: usize = 5;
12pub(super) const REGEX_PATTERN: usize = 6;
13pub(super) const JSX_TEXT: usize = 7;
14
15pub struct Js;
16
17fn is_nl(c: char) -> bool {
18    matches!(c, '\n' | '\u{2028}' | '\u{2029}')
19}
20
21/// 模板字符串里的字面字符(两个语法共用)。
22pub(super) fn template_chars(lx: &mut ScanLexer) -> bool {
23    lx.set_result(TEMPLATE_CHARS as u16);
24    let mut has_content = false;
25    loop {
26        lx.mark_end();
27        match lx.lookahead() {
28            '`' | '\\' => return has_content,
29            '\0' => return false,
30            '$' => {
31                lx.next();
32                if lx.lookahead() == '{' {
33                    return has_content;
34                }
35            }
36            _ => lx.next(),
37        }
38        has_content = true;
39    }
40}
41
42#[derive(PartialEq)]
43enum Ws {
44    Reject,
45    NoNewline,
46    Accept,
47}
48
49fn ws_and_comments(lx: &mut ScanLexer, scanned_comment: &mut bool, consume: bool) -> Ws {
50    let mut saw_block_newline = false;
51    loop {
52        while is_space(lx.lookahead()) {
53            lx.skip();
54        }
55        if lx.lookahead() != '/' {
56            return Ws::Accept;
57        }
58        lx.skip();
59        if lx.lookahead() == '/' {
60            lx.skip();
61            while lx.lookahead() != '\0' && !is_nl(lx.lookahead()) {
62                lx.skip();
63            }
64            *scanned_comment = true;
65        } else if lx.lookahead() == '*' {
66            lx.skip();
67            while lx.lookahead() != '\0' {
68                let c = lx.lookahead();
69                if c == '*' {
70                    lx.skip();
71                    if lx.lookahead() == '/' {
72                        lx.skip();
73                        *scanned_comment = true;
74                        if lx.lookahead() != '/' && !consume {
75                            return if saw_block_newline {
76                                Ws::Accept
77                            } else {
78                                Ws::NoNewline
79                            };
80                        }
81                        break;
82                    }
83                } else if is_nl(c) {
84                    saw_block_newline = true;
85                    lx.skip();
86                } else {
87                    lx.skip();
88                }
89            }
90        } else {
91            return Ws::Reject;
92        }
93    }
94}
95
96fn automatic_semicolon(
97    lx: &mut ScanLexer,
98    comment_condition: bool,
99    scanned_comment: &mut bool,
100) -> bool {
101    lx.set_result(AUTOMATIC_SEMICOLON as u16);
102    lx.mark_end();
103    loop {
104        let c = lx.lookahead();
105        if c == '\0' {
106            return true;
107        }
108        if c == '/' {
109            let r = ws_and_comments(lx, scanned_comment, false);
110            if r == Ws::Reject {
111                return false;
112            }
113            if r == Ws::Accept
114                && comment_condition
115                && lx.lookahead() != ','
116                && lx.lookahead() != '='
117            {
118                return true;
119            }
120        }
121        if lx.lookahead() == '}' {
122            return true;
123        }
124        // is_at_included_range_start:整段输入只有一个范围,恒为假
125        if is_nl(lx.lookahead()) {
126            break;
127        }
128        if !is_space(lx.lookahead()) {
129            return false;
130        }
131        lx.skip();
132    }
133    lx.skip();
134    if ws_and_comments(lx, scanned_comment, true) == Ws::Reject {
135        return false;
136    }
137    match lx.lookahead() {
138        '`' | ',' | ':' | ';' | '*' | '%' | '>' | '<' | '=' | '[' | '(' | '?' | '^' | '|' | '&'
139        | '/' => false,
140        '.' => {
141            lx.skip();
142            lx.lookahead().is_ascii_digit()
143        }
144        '+' => {
145            lx.skip();
146            lx.lookahead() == '+'
147        }
148        '-' => {
149            lx.skip();
150            lx.lookahead() == '-'
151        }
152        '!' => {
153            lx.skip();
154            lx.lookahead() != '='
155        }
156        'i' => in_or_instanceof(lx),
157        _ => true,
158    }
159}
160
161/// 遇到 `i`:`in`、`instanceof` 之前不插分号,标识符之前插。
162pub(super) fn in_or_instanceof(lx: &mut ScanLexer) -> bool {
163    lx.skip();
164    if lx.lookahead() != 'n' {
165        return true;
166    }
167    lx.skip();
168    if !is_alpha(lx.lookahead()) {
169        return false;
170    }
171    for ch in "stanceof".chars() {
172        if lx.lookahead() != ch {
173            return true;
174        }
175        lx.skip();
176    }
177    is_alpha(lx.lookahead())
178}
179
180fn ternary_qmark(lx: &mut ScanLexer) -> bool {
181    while is_space(lx.lookahead()) {
182        lx.skip();
183    }
184    if lx.lookahead() == '?' {
185        lx.next();
186        if lx.lookahead() == '?' {
187            return false;
188        }
189        lx.mark_end();
190        lx.set_result(TERNARY_QMARK as u16);
191        if lx.lookahead() == '.' {
192            lx.next();
193            return lx.lookahead().is_ascii_digit();
194        }
195        return true;
196    }
197    false
198}
199
200/// HTML 风格注释 `<!--` / `-->`(两个语法共用)。
201pub(super) fn html_comment(lx: &mut ScanLexer) -> bool {
202    while is_space(lx.lookahead()) || is_nl(lx.lookahead()) {
203        lx.skip();
204    }
205    let pat = match lx.lookahead() {
206        '<' => "<!--",
207        '-' => "-->",
208        _ => return false,
209    };
210    for ch in pat.chars() {
211        if lx.lookahead() != ch {
212            return false;
213        }
214        lx.next();
215    }
216    while lx.lookahead() != '\0' && !is_nl(lx.lookahead()) {
217        lx.next();
218    }
219    lx.set_result(HTML_COMMENT as u16);
220    lx.mark_end();
221    true
222}
223
224pub(super) fn jsx_text(lx: &mut ScanLexer) -> bool {
225    let (mut saw_text, mut at_newline) = (false, false);
226    while !matches!(lx.lookahead(), '\0' | '<' | '>' | '{' | '}' | '&') {
227        let ws = is_space(lx.lookahead());
228        if lx.lookahead() == '\n' {
229            at_newline = true;
230        } else {
231            at_newline &= ws;
232            if !at_newline {
233                saw_text = true;
234            }
235        }
236        lx.next();
237    }
238    lx.set_result(JSX_TEXT as u16);
239    saw_text
240}
241
242impl Scanner for Js {
243    fn serialize(&self, _out: &mut Vec<u8>) {}
244    fn deserialize(&mut self, _d: &[u8]) {}
245
246    fn scan(&mut self, lx: &mut ScanLexer, valid: &[bool]) -> bool {
247        if valid[TEMPLATE_CHARS] {
248            if valid[AUTOMATIC_SEMICOLON] {
249                return false;
250            }
251            return template_chars(lx);
252        }
253        if valid[JSX_TEXT] && jsx_text(lx) {
254            return true;
255        }
256        if valid[AUTOMATIC_SEMICOLON] {
257            let mut scanned_comment = false;
258            let ret = automatic_semicolon(lx, !valid[LOGICAL_OR], &mut scanned_comment);
259            if !ret && !scanned_comment && valid[TERNARY_QMARK] && lx.lookahead() == '?' {
260                return ternary_qmark(lx);
261            }
262            return ret;
263        }
264        if valid[TERNARY_QMARK] {
265            return ternary_qmark(lx);
266        }
267        if valid[HTML_COMMENT]
268            && !valid[LOGICAL_OR]
269            && !valid[ESCAPE_SEQUENCE]
270            && !valid[REGEX_PATTERN]
271        {
272            return html_comment(lx);
273        }
274        false
275    }
276}