Skip to main content

pagesift_syntax/scanner/
r.rs

1//! R 外部扫描器,移植自 tree-sitter-r 的 `src/scanner.c`(MIT,Copyright (c) 2025 tree-sitter-r authors)。
2
3use super::{MAX_SERIALIZED, ScanLexer, Scanner, is_space};
4
5const START: usize = 0;
6const NEWLINE: usize = 1;
7const SEMICOLON: usize = 2;
8const RAW_STRING_OPEN: usize = 3;
9const RAW_STRING_CONTENT: usize = 4;
10const RAW_STRING_CLOSE: usize = 5;
11const ELSE: usize = 6;
12const OPEN_PAREN: usize = 7;
13const CLOSE_PAREN: usize = 8;
14const OPEN_BRACE: usize = 9;
15const CLOSE_BRACE: usize = 10;
16const OPEN_BRACKET: usize = 11;
17const CLOSE_BRACKET: usize = 12;
18const OPEN_BRACKET2: usize = 13;
19const CLOSE_BRACKET2: usize = 14;
20const ERROR_SENTINEL: usize = 15;
21
22const SCOPE_BRACE: u8 = 1;
23const SCOPE_PAREN: u8 = 2;
24const SCOPE_BRACKET: u8 = 3;
25const SCOPE_BRACKET2: u8 = 4;
26/// 序列化缓冲里除作用域栈之外还要放:括号、连字符个数、引号各一字节,加四字节的栈深度。
27const MAX_SCOPES: usize = MAX_SERIALIZED - 3 - 4;
28
29#[derive(Default)]
30pub struct R {
31    closing_bracket: u8,
32    hyphen_count: u8,
33    closing_quote: u8,
34    /// 栈底的顶层作用域不入栈。
35    scopes: Vec<u8>,
36}
37
38fn is_identifier_continuation(c: char) -> bool {
39    c.is_alphanumeric() || c == '_' || c == '.' || c as u32 >= 128
40}
41
42fn scan_else(lx: &mut ScanLexer) -> bool {
43    for ch in "else".chars() {
44        if lx.lookahead() != ch {
45            return false;
46        }
47        lx.next();
48    }
49    // `else_idx` 这样的更长标识符不算
50    if is_identifier_continuation(lx.lookahead()) {
51        return false;
52    }
53    lx.mark_end();
54    lx.set_result(ELSE as u16);
55    true
56}
57
58fn scan_else_with_leading_newlines(lx: &mut ScanLexer) -> bool {
59    while is_space(lx.lookahead()) {
60        if lx.lookahead() != '\n' {
61            lx.skip();
62            continue;
63        }
64        lx.skip();
65        lx.mark_end();
66        lx.set_result(NEWLINE as u16);
67    }
68    // 后面是注释就交给内部扫描器
69    if lx.lookahead() == '#' {
70        return false;
71    }
72    scan_else(lx);
73    true
74}
75
76impl R {
77    fn peek(&self) -> u8 {
78        self.scopes.last().copied().unwrap_or(0)
79    }
80
81    fn push(&mut self, scope: u8) -> bool {
82        if self.scopes.len() >= MAX_SCOPES {
83            return false;
84        }
85        self.scopes.push(scope);
86        true
87    }
88
89    fn pop(&mut self, expected: u8) -> bool {
90        match self.scopes.pop() {
91            Some(s) => s == expected,
92            None => false,
93        }
94    }
95
96    fn consume_whitespace(&self, lx: &mut ScanLexer) {
97        while is_space(lx.lookahead()) {
98            if lx.lookahead() != '\n' {
99                lx.skip();
100                continue;
101            }
102            // `(`、`[`、`[[` 里的换行没有语法意义,直接跳过;顶层和 `{` 里的换行留给后面的分支
103            if matches!(self.peek(), SCOPE_PAREN | SCOPE_BRACKET | SCOPE_BRACKET2) {
104                lx.skip();
105                continue;
106            }
107            break;
108        }
109    }
110
111    fn scan_raw_string_open(&mut self, lx: &mut ScanLexer) -> bool {
112        if !matches!(lx.lookahead(), 'r' | 'R') {
113            return false;
114        }
115        lx.next();
116        let quote = lx.lookahead();
117        if quote != '"' && quote != '\'' {
118            return false;
119        }
120        lx.next();
121        let mut hyphens = 0u8;
122        while lx.lookahead() == '-' {
123            if hyphens == u8::MAX {
124                return false;
125            }
126            lx.next();
127            hyphens += 1;
128        }
129        let close = match lx.lookahead() {
130            '(' => b')',
131            '[' => b']',
132            '{' => b'}',
133            _ => return false,
134        };
135        lx.next();
136        lx.mark_end();
137        lx.set_result(RAW_STRING_OPEN as u16);
138        self.closing_bracket = close;
139        self.hyphen_count = hyphens;
140        self.closing_quote = quote as u8;
141        true
142    }
143
144    fn scan_raw_string_content_or_close(&mut self, lx: &mut ScanLexer) -> bool {
145        let mut any_content = false;
146        while !lx.eof() {
147            if lx.lookahead() != self.closing_bracket as char {
148                lx.next();
149                any_content = true;
150                continue;
151            }
152            lx.mark_end();
153            lx.next();
154            let mut matched = true;
155            for _ in 0..self.hyphen_count {
156                if lx.lookahead() != '-' {
157                    matched = false;
158                    break;
159                }
160                lx.next();
161            }
162            if !matched || lx.lookahead() != self.closing_quote as char {
163                any_content = true;
164                continue;
165            }
166            lx.next();
167            if any_content {
168                lx.set_result(RAW_STRING_CONTENT as u16);
169            } else {
170                lx.mark_end();
171                lx.set_result(RAW_STRING_CLOSE as u16);
172            }
173            return true;
174        }
175        false
176    }
177
178    fn scan_raw_string_close(&mut self, lx: &mut ScanLexer) -> bool {
179        lx.next();
180        for _ in 0..self.hyphen_count {
181            lx.next();
182        }
183        lx.next();
184        lx.mark_end();
185        lx.set_result(RAW_STRING_CLOSE as u16);
186        true
187    }
188
189    fn open_block(&mut self, lx: &mut ScanLexer, scope: u8, sym: usize) -> bool {
190        if !self.push(scope) {
191            return false;
192        }
193        lx.next();
194        lx.mark_end();
195        lx.set_result(sym as u16);
196        true
197    }
198
199    fn close_block(&mut self, lx: &mut ScanLexer, scope: u8, sym: usize) -> bool {
200        if !self.pop(scope) {
201            return false;
202        }
203        lx.next();
204        lx.mark_end();
205        lx.set_result(sym as u16);
206        true
207    }
208
209    fn open_bracket(&mut self, lx: &mut ScanLexer, v: &[bool]) -> bool {
210        lx.next();
211        if v[OPEN_BRACKET2] && lx.lookahead() == '[' {
212            if !self.push(SCOPE_BRACKET2) {
213                return false;
214            }
215            lx.next();
216            lx.mark_end();
217            lx.set_result(OPEN_BRACKET2 as u16);
218            return true;
219        }
220        if v[OPEN_BRACKET] {
221            if !self.push(SCOPE_BRACKET) {
222                return false;
223            }
224            lx.mark_end();
225            lx.set_result(OPEN_BRACKET as u16);
226            return true;
227        }
228        false
229    }
230
231    fn close_bracket2(&mut self, lx: &mut ScanLexer) -> bool {
232        lx.next();
233        if lx.lookahead() != ']' {
234            return false;
235        }
236        self.close_block(lx, SCOPE_BRACKET2, CLOSE_BRACKET2)
237    }
238}
239
240impl Scanner for R {
241    fn scan(&mut self, lx: &mut ScanLexer, v: &[bool]) -> bool {
242        // 错误恢复时所有符号都有效,不处理
243        if v[ERROR_SENTINEL] {
244            return false;
245        }
246        if v[START] {
247            lx.set_result(START as u16);
248            return true;
249        }
250        if v[RAW_STRING_CONTENT] {
251            return self.scan_raw_string_content_or_close(lx);
252        } else if v[RAW_STRING_CLOSE] {
253            return self.scan_raw_string_close(lx);
254        }
255        self.consume_whitespace(lx);
256        let c = lx.lookahead();
257        if v[SEMICOLON] && c == ';' {
258            lx.next();
259            lx.mark_end();
260            lx.set_result(SEMICOLON as u16);
261            true
262        } else if v[OPEN_PAREN] && c == '(' {
263            self.open_block(lx, SCOPE_PAREN, OPEN_PAREN)
264        } else if v[CLOSE_PAREN] && c == ')' {
265            self.close_block(lx, SCOPE_PAREN, CLOSE_PAREN)
266        } else if v[OPEN_BRACE] && c == '{' {
267            self.open_block(lx, SCOPE_BRACE, OPEN_BRACE)
268        } else if v[CLOSE_BRACE] && c == '}' {
269            self.close_block(lx, SCOPE_BRACE, CLOSE_BRACE)
270        } else if (v[OPEN_BRACKET] || v[OPEN_BRACKET2]) && c == '[' {
271            self.open_bracket(lx, v)
272        } else if v[CLOSE_BRACKET] && c == ']' && self.peek() == SCOPE_BRACKET {
273            self.close_block(lx, SCOPE_BRACKET, CLOSE_BRACKET)
274        } else if v[CLOSE_BRACKET2] && c == ']' && self.peek() == SCOPE_BRACKET2 {
275            self.close_bracket2(lx)
276        } else if v[RAW_STRING_OPEN] && matches!(c, 'r' | 'R') {
277            self.scan_raw_string_open(lx)
278        } else if v[ELSE] && c == 'e' {
279            scan_else(lx)
280        } else if v[ELSE] && self.peek() == SCOPE_BRACE && c == '\n' {
281            scan_else_with_leading_newlines(lx)
282        } else if v[NEWLINE] && c == '\n' {
283            lx.next();
284            lx.mark_end();
285            lx.set_result(NEWLINE as u16);
286            true
287        } else {
288            false
289        }
290    }
291
292    fn serialize(&self, out: &mut Vec<u8>) {
293        out.extend_from_slice(&[self.closing_bracket, self.hyphen_count, self.closing_quote]);
294        out.extend_from_slice(&(self.scopes.len() as u32).to_le_bytes());
295        out.extend_from_slice(&self.scopes);
296    }
297
298    fn deserialize(&mut self, d: &[u8]) {
299        let reset = |s: &mut R| {
300            s.closing_bracket = 0;
301            s.hyphen_count = 0;
302            s.closing_quote = 0;
303            s.scopes.clear();
304        };
305        if d.is_empty() {
306            reset(self);
307            return;
308        }
309        if d.len() < 7 {
310            reset(self);
311            return;
312        }
313        self.closing_bracket = d[0];
314        self.hyphen_count = d[1];
315        self.closing_quote = d[2];
316        let n = u32::from_le_bytes([d[3], d[4], d[5], d[6]]) as usize;
317        if n > d.len() - 7 {
318            reset(self);
319            return;
320        }
321        self.scopes = d[7..7 + n].to_vec();
322    }
323}