Skip to main content

pagesift_syntax/scanner/
csharp.rs

1//! C# 外部扫描器,移植自 tree-sitter-c-sharp 的 `src/scanner.c`
2//! (MIT,Copyright (c) 2014-2023 Max Brunsfeld, Damien Guard, Amaan Qureshi, and contributors)。
3
4use super::{MAX_SERIALIZED, ScanLexer, Scanner, is_alpha, is_space};
5
6const OPT_SEMI: usize = 0;
7const INTERPOLATION_REGULAR_START: usize = 1;
8const INTERPOLATION_VERBATIM_START: usize = 2;
9const INTERPOLATION_RAW_START: usize = 3;
10const INTERPOLATION_START_QUOTE: usize = 4;
11const INTERPOLATION_END_QUOTE: usize = 5;
12const INTERPOLATION_OPEN_BRACE: usize = 6;
13const INTERPOLATION_CLOSE_BRACE: usize = 7;
14const INTERPOLATION_STRING_CONTENT: usize = 8;
15const RAW_STRING_START: usize = 9;
16const RAW_STRING_END: usize = 10;
17const RAW_STRING_CONTENT: usize = 11;
18const LAMBDA_PAREN_OPEN: usize = 12;
19
20const REGULAR: u8 = 1;
21const VERBATIM: u8 = 2;
22const RAW: u8 = 4;
23
24#[derive(Clone, Copy, Default)]
25struct Interp {
26    dollar_count: u8,
27    open_brace_count: u8,
28    quote_count: u8,
29    string_type: u8,
30}
31
32#[derive(Default)]
33pub struct CSharp {
34    quote_count: u8,
35    stack: Vec<Interp>,
36}
37
38fn is_id_start(c: char) -> bool {
39    c == '_' || is_alpha(c)
40}
41fn is_id_continue(c: char) -> bool {
42    c == '_' || c.is_alphanumeric()
43}
44
45fn skip_ws_and_comments(lx: &mut ScanLexer) {
46    loop {
47        let c = lx.lookahead();
48        if matches!(c, ' ' | '\t' | '\r' | '\n') {
49            lx.next();
50        } else if c == '/' {
51            lx.next();
52            if lx.lookahead() == '/' {
53                while lx.lookahead() != '\0' && lx.lookahead() != '\n' {
54                    lx.next();
55                }
56            } else if lx.lookahead() == '*' {
57                lx.next();
58                let mut prev = '\0';
59                while lx.lookahead() != '\0' && !(prev == '*' && lx.lookahead() == '/') {
60                    prev = lx.lookahead();
61                    lx.next();
62                }
63                if lx.lookahead() == '/' {
64                    lx.next();
65                }
66            } else {
67                return;
68            }
69        } else {
70            return;
71        }
72    }
73}
74
75enum Lambda {
76    NoParen,
77    FailedAfterParen,
78    Success,
79}
80
81/// C# 14 的简单 lambda 参数列表探测(带修饰符的 `(ref x, out y) =>`)。
82fn lambda_paren_open(lx: &mut ScanLexer) -> Lambda {
83    while is_space(lx.lookahead()) {
84        lx.skip();
85    }
86    if lx.lookahead() != '(' {
87        return Lambda::NoParen;
88    }
89    lx.next();
90    lx.mark_end();
91    let mut saw_hard = false;
92    let mut expecting = true;
93    loop {
94        skip_ws_and_comments(lx);
95        let c = lx.lookahead();
96        if c == '\0' {
97            return Lambda::FailedAfterParen;
98        }
99        if c == ')' {
100            lx.next();
101            skip_ws_and_comments(lx);
102            if !saw_hard || lx.lookahead() != '=' {
103                return Lambda::FailedAfterParen;
104            }
105            lx.next();
106            if lx.lookahead() != '>' {
107                return Lambda::FailedAfterParen;
108            }
109            lx.set_result(LAMBDA_PAREN_OPEN as u16);
110            return Lambda::Success;
111        }
112        if !expecting {
113            if c != ',' {
114                return Lambda::FailedAfterParen;
115            }
116            lx.next();
117            expecting = true;
118            continue;
119        }
120        let mut consumed_name = false;
121        while !consumed_name {
122            skip_ws_and_comments(lx);
123            if !is_id_start(lx.lookahead()) {
124                return Lambda::FailedAfterParen;
125            }
126            // 与官方一样把整个标识符读进 9 字节缓冲(字符截断成 8 位)
127            let mut buf = [0u8; 9];
128            let mut n = 0usize;
129            while is_id_continue(lx.lookahead()) {
130                if n < buf.len() {
131                    buf[n] = (lx.lookahead() as u32 & 0xFF) as u8;
132                }
133                n += 1;
134                lx.next();
135            }
136            let word = &buf[..n.min(9)];
137            let hard = n <= 8 && matches!(word, b"ref" | b"out" | b"in" | b"readonly");
138            let soft = n == 6 && word == b"scoped";
139            if hard {
140                saw_hard = true;
141            } else if !soft {
142                consumed_name = true;
143            }
144        }
145        expecting = false;
146    }
147}
148
149impl Scanner for CSharp {
150    fn serialize(&self, out: &mut Vec<u8>) {
151        if self.stack.len() * 4 + 2 > MAX_SERIALIZED {
152            return;
153        }
154        out.push(self.quote_count);
155        out.push(self.stack.len() as u8);
156        for i in &self.stack {
157            out.extend_from_slice(&[
158                i.dollar_count,
159                i.open_brace_count,
160                i.quote_count,
161                i.string_type,
162            ]);
163        }
164    }
165
166    fn deserialize(&mut self, d: &[u8]) {
167        self.quote_count = 0;
168        self.stack.clear();
169        if d.len() >= 2 {
170            self.quote_count = d[0];
171            let n = d[1] as usize;
172            for k in 0..n {
173                let p = 2 + k * 4;
174                if p + 4 > d.len() {
175                    break;
176                }
177                self.stack.push(Interp {
178                    dollar_count: d[p],
179                    open_brace_count: d[p + 1],
180                    quote_count: d[p + 2],
181                    string_type: d[p + 3],
182                });
183            }
184        }
185    }
186
187    fn scan(&mut self, lx: &mut ScanLexer, valid: &[bool]) -> bool {
188        let mut brace_advanced: u8 = 0;
189        let mut quote_count: u8 = 0;
190        let mut did_advance = false;
191
192        if valid[LAMBDA_PAREN_OPEN] {
193            match lambda_paren_open(lx) {
194                Lambda::Success => return true,
195                Lambda::FailedAfterParen => return false,
196                Lambda::NoParen => {}
197            }
198        }
199        if valid[OPT_SEMI] && valid[INTERPOLATION_REGULAR_START] {
200            return false;
201        }
202        if valid[OPT_SEMI] {
203            lx.set_result(OPT_SEMI as u16);
204            if lx.lookahead() == ';' {
205                lx.next();
206            }
207            return true;
208        }
209        if valid[RAW_STRING_START] {
210            while is_space(lx.lookahead()) {
211                lx.skip();
212            }
213            if lx.lookahead() == '"' {
214                while lx.lookahead() == '"' {
215                    lx.next();
216                    quote_count = quote_count.wrapping_add(1);
217                }
218                if quote_count >= 3 {
219                    lx.set_result(RAW_STRING_START as u16);
220                    self.quote_count = quote_count;
221                    return true;
222                }
223            }
224        }
225        if valid[RAW_STRING_END] && lx.lookahead() == '"' {
226            while lx.lookahead() == '"' {
227                lx.next();
228                quote_count = quote_count.wrapping_add(1);
229            }
230            if quote_count == self.quote_count {
231                lx.set_result(RAW_STRING_END as u16);
232                self.quote_count = 0;
233                return true;
234            }
235            did_advance = quote_count > 0;
236        }
237        if valid[RAW_STRING_CONTENT] {
238            while lx.lookahead() != '\0' {
239                if lx.lookahead() == '"' {
240                    lx.mark_end();
241                    quote_count = 0;
242                    while lx.lookahead() == '"' {
243                        lx.next();
244                        quote_count = quote_count.wrapping_add(1);
245                    }
246                    if quote_count == self.quote_count {
247                        lx.set_result(RAW_STRING_CONTENT as u16);
248                        return true;
249                    }
250                }
251                lx.next();
252            }
253            lx.mark_end();
254            lx.set_result(RAW_STRING_CONTENT as u16);
255            return true;
256        }
257        if valid[INTERPOLATION_REGULAR_START]
258            || valid[INTERPOLATION_VERBATIM_START]
259            || valid[INTERPOLATION_RAW_START]
260        {
261            while is_space(lx.lookahead()) {
262                lx.skip();
263            }
264            let mut dollars: u8 = 0;
265            let mut verbatim = false;
266            if lx.lookahead() == '@' {
267                verbatim = true;
268                lx.next();
269            }
270            while lx.lookahead() == '$' && quote_count == 0 {
271                lx.next();
272                dollars = dollars.wrapping_add(1);
273            }
274            if dollars > 0 && (lx.lookahead() == '"' || lx.lookahead() == '@') {
275                lx.set_result(INTERPOLATION_REGULAR_START as u16);
276                let mut it = Interp {
277                    dollar_count: dollars,
278                    ..Default::default()
279                };
280                if verbatim || lx.lookahead() == '@' {
281                    if lx.lookahead() == '@' {
282                        lx.next();
283                        verbatim = true;
284                    }
285                    lx.set_result(INTERPOLATION_VERBATIM_START as u16);
286                    it.string_type = VERBATIM;
287                }
288                lx.mark_end();
289                lx.next();
290                if lx.lookahead() == '"' && !verbatim {
291                    lx.next();
292                    if lx.lookahead() == '"' {
293                        lx.set_result(INTERPOLATION_RAW_START as u16);
294                        it.string_type |= RAW;
295                        self.stack.push(it);
296                    }
297                } else {
298                    it.string_type |= REGULAR;
299                    self.stack.push(it);
300                }
301                return true;
302            }
303        }
304        if valid[INTERPOLATION_START_QUOTE] && !self.stack.is_empty() {
305            let cur = self.stack.last_mut().unwrap();
306            if cur.string_type & (VERBATIM | REGULAR) != 0 {
307                if lx.lookahead() == '"' {
308                    lx.next();
309                    cur.quote_count = cur.quote_count.wrapping_add(1);
310                }
311            } else {
312                while lx.lookahead() == '"' {
313                    lx.next();
314                    cur.quote_count = cur.quote_count.wrapping_add(1);
315                }
316            }
317            lx.set_result(INTERPOLATION_START_QUOTE as u16);
318            return cur.quote_count > 0;
319        }
320        if valid[INTERPOLATION_END_QUOTE] && !self.stack.is_empty() {
321            let cur_q = self.stack.last().unwrap().quote_count;
322            while lx.lookahead() == '"' {
323                lx.next();
324                quote_count = quote_count.wrapping_add(1);
325            }
326            if quote_count == cur_q {
327                lx.set_result(INTERPOLATION_END_QUOTE as u16);
328                self.stack.pop();
329                return true;
330            }
331            did_advance = quote_count > 0;
332        }
333        if valid[INTERPOLATION_OPEN_BRACE] && !self.stack.is_empty() {
334            let cur = self.stack.last_mut().unwrap();
335            while lx.lookahead() == '{' && brace_advanced < cur.dollar_count {
336                lx.next();
337                brace_advanced += 1;
338            }
339            if brace_advanced > 0 && brace_advanced == cur.dollar_count && lx.lookahead() != '{' {
340                cur.open_brace_count = brace_advanced;
341                lx.set_result(INTERPOLATION_OPEN_BRACE as u16);
342                return true;
343            }
344        }
345        if valid[INTERPOLATION_CLOSE_BRACE] && !self.stack.is_empty() {
346            let mut braces: u8 = 0;
347            let cur = self.stack.last_mut().unwrap();
348            while is_space(lx.lookahead()) {
349                lx.next();
350            }
351            while lx.lookahead() == '}' {
352                lx.next();
353                braces = braces.wrapping_add(1);
354                if braces == cur.open_brace_count {
355                    cur.open_brace_count = 0;
356                    lx.set_result(INTERPOLATION_CLOSE_BRACE as u16);
357                    return true;
358                }
359            }
360            return false;
361        }
362        if valid[INTERPOLATION_STRING_CONTENT] && !self.stack.is_empty() {
363            lx.set_result(INTERPOLATION_STRING_CONTENT as u16);
364            let cur = *self.stack.last().unwrap();
365            while lx.lookahead() != '\0' {
366                if cur.string_type & RAW != 0 {
367                    if lx.lookahead() == '"' {
368                        lx.mark_end();
369                        lx.next();
370                        if lx.lookahead() == '"' {
371                            lx.next();
372                            let mut q: u8 = 2;
373                            while lx.lookahead() == '"' {
374                                q = q.wrapping_add(1);
375                                lx.next();
376                            }
377                            if q == cur.quote_count {
378                                return did_advance;
379                            }
380                        }
381                    }
382                    if lx.lookahead() == '{' {
383                        lx.mark_end();
384                        while lx.lookahead() == '{' && brace_advanced < cur.open_brace_count {
385                            lx.next();
386                            brace_advanced += 1;
387                        }
388                        if brace_advanced == cur.open_brace_count
389                            && (brace_advanced == 0 || lx.lookahead() != '{')
390                        {
391                            return did_advance;
392                        }
393                    }
394                } else if cur.string_type & VERBATIM != 0 {
395                    if lx.lookahead() == '"' {
396                        lx.mark_end();
397                        lx.next();
398                        if lx.lookahead() == '"' {
399                            lx.next();
400                            continue;
401                        }
402                        return did_advance;
403                    }
404                    if lx.lookahead() == '{' {
405                        lx.mark_end();
406                        while lx.lookahead() == '{' && brace_advanced < cur.open_brace_count {
407                            lx.next();
408                            brace_advanced += 1;
409                        }
410                        if brace_advanced == cur.open_brace_count
411                            && (brace_advanced == 0 || lx.lookahead() != '{')
412                        {
413                            return did_advance;
414                        }
415                    }
416                } else if cur.string_type & REGULAR != 0 {
417                    if matches!(lx.lookahead(), '\\' | '\n' | '"') {
418                        lx.mark_end();
419                        return did_advance;
420                    }
421                    if lx.lookahead() == '{' {
422                        lx.mark_end();
423                        while lx.lookahead() == '{' && brace_advanced < cur.open_brace_count {
424                            lx.next();
425                            brace_advanced += 1;
426                        }
427                        if brace_advanced == cur.open_brace_count
428                            && (brace_advanced == 0 || lx.lookahead() != '{')
429                        {
430                            return did_advance;
431                        }
432                    }
433                }
434                if lx.lookahead() != '{' {
435                    brace_advanced = 0;
436                }
437                lx.next();
438                did_advance = true;
439            }
440            lx.mark_end();
441            return did_advance;
442        }
443        false
444    }
445}