codeint-lang-dart 0.10.4

Built-in Dart Language plugin for codeint
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
use std::collections::BTreeSet;

use codeint_model::language::LowerError;
use codeint_model::scan::{ScanToken, track_delim};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DartKind {
    Keyword,
    Ident,
    StringLit,
    NumberLit,
    Punct,
}

#[derive(Debug, Clone)]
pub(crate) struct DartToken {
    pub(crate) line: u32,
    pub(crate) end_line: u32,
    pub(crate) text: String,
    pub(crate) kind: DartKind,
}

impl ScanToken for DartToken {
    fn line(&self) -> u32 {
        self.line
    }

    fn is_keyword(&self, kw: &str) -> bool {
        matches!(self.kind, DartKind::Keyword) && self.text == kw
    }

    fn text(&self) -> &str {
        self.text.as_str()
    }
}

pub(crate) struct ScannedDart {
    pub(crate) code_lines: BTreeSet<u32>,
    pub(crate) header_comments: String,
    pub(crate) tokens: Vec<DartToken>,
}

const DART_RESERVED_WORDS: &str = "assert break case catch class const continue default do else enum extends false final finally for if in is new null rethrow return super switch this throw true try var void while with";

const DART_CONTEXTUAL_KEYWORDS: &str = "abstract as async await base covariant deferred dynamic export extension external factory Function get hide implements import interface late library mixin of on operator part required sealed set show static sync typedef when yield";

fn contains_word(words: &str, candidate: &str) -> bool {
    words.split(' ').any(|kw| kw == candidate)
}

pub(crate) fn is_ident_or_contextual_kw(tok: &DartToken) -> bool {
    tok.kind == DartKind::Ident
        || (tok.kind == DartKind::Keyword && !contains_word(DART_RESERVED_WORDS, &tok.text))
}

pub(crate) fn matching_open_paren(tokens: &[DartToken], close_paren: usize) -> Option<usize> {
    let mut depth = 0usize;
    for idx in (0..=close_paren).rev() {
        match tokens[idx].text.as_str() {
            ")" => depth += 1,
            "(" => {
                depth -= 1;
                if depth == 0 {
                    return Some(idx);
                }
            }
            _ => {}
        }
    }
    None
}

fn is_dart_keyword(word: &str) -> bool {
    contains_word(DART_RESERVED_WORDS, word) || contains_word(DART_CONTEXTUAL_KEYWORDS, word)
}

struct Scanner<'a> {
    delims: Vec<(u8, u32)>,
    code_lines: BTreeSet<u32>,
    header_comments: String,
    tokens: Vec<DartToken>,
    line: u32,
    idx: usize,
    bytes: &'a [u8],
    src: &'a str,
}

pub(crate) fn scan(text: &str) -> Result<ScannedDart, LowerError> {
    let src = text.strip_prefix('\u{feff}').unwrap_or(text);
    let mut scanner = Scanner::new(src);
    scanner.run()?;
    Ok(ScannedDart {
        code_lines: scanner.code_lines,
        header_comments: scanner.header_comments,
        tokens: scanner.tokens,
    })
}

impl<'a> Scanner<'a> {
    fn new(src: &'a str) -> Scanner<'a> {
        Scanner {
            delims: Vec::new(),
            code_lines: BTreeSet::new(),
            header_comments: String::new(),
            tokens: Vec::new(),
            line: 1,
            idx: 0,
            bytes: src.as_bytes(),
            src,
        }
    }
    fn run(&mut self) -> Result<(), LowerError> {
        if self.bytes.starts_with(b"#!") {
            self.skip_to_eol();
        }
        while self.idx < self.bytes.len() {
            self.next_unit()?;
        }
        if let Some((open, open_line)) = self.delims.last() {
            return Err(LowerError::Unparsable(format!(
                "unclosed {:?} opened at line {open_line}",
                *open as char
            )));
        }
        Ok(())
    }

    fn next_unit(&mut self) -> Result<(), LowerError> {
        let rest = &self.bytes[self.idx..];
        let b = rest[0];
        if b.is_ascii_whitespace() {
            if b == b'\n' {
                self.line += 1;
            }
            self.idx += 1;
            return Ok(());
        }
        if rest.starts_with(b"//") {
            self.read_line_comment();
            return Ok(());
        }
        if rest.starts_with(b"/*") {
            return self.read_block_comment();
        }
        if self.is_raw_string_start() {
            return self.read_raw_string();
        }
        if matches!(b, b'\'' | b'"') {
            return self.read_string();
        }
        self.next_atom()
    }

    fn next_atom(&mut self) -> Result<(), LowerError> {
        let b = self.bytes[self.idx];
        if is_id_start(b) {
            self.read_word();
            return Ok(());
        }
        if b.is_ascii_digit() {
            self.read_number();
            return Ok(());
        }
        self.read_punct()
    }

    fn skip_to_eol(&mut self) {
        while self.idx < self.bytes.len() && self.bytes[self.idx] != b'\n' {
            self.idx += 1;
        }
    }

    fn read_line_comment(&mut self) {
        let start = self.idx;
        self.skip_to_eol();
        if self.tokens.is_empty() && !self.bytes[start..].starts_with(b"///") {
            self.header_comments
                .extend([&self.src[start..self.idx], "\n"]);
        }
    }

    fn read_block_comment(&mut self) -> Result<(), LowerError> {
        let start = self.idx;
        self.skip_block_comment()?;
        if self.tokens.is_empty() && !self.bytes[start..].starts_with(b"/**") {
            self.header_comments.push_str(&self.src[start..self.idx]);
            self.header_comments.push('\n');
        }
        Ok(())
    }

    fn skip_block_comment(&mut self) -> Result<(), LowerError> {
        let start_line = self.line;
        self.idx += 2;
        let mut depth = 1usize;
        while self.idx < self.bytes.len() {
            let rest = &self.bytes[self.idx..];
            if rest.starts_with(b"/*") {
                depth += 1;
                self.idx += 2;
            } else if rest.starts_with(b"*/") {
                depth -= 1;
                self.idx += 2;
                if depth == 0 {
                    return Ok(());
                }
            } else {
                if rest[0] == b'\n' {
                    self.line += 1;
                }
                self.idx += 1;
            }
        }
        Err(LowerError::Unparsable(format!(
            "unterminated block comment at line {start_line}"
        )))
    }

    fn is_raw_string_start(&self) -> bool {
        self.bytes[self.idx] == b'r'
            && (self.idx == 0 || !is_id_continue(self.bytes[self.idx - 1]))
            && self
                .bytes
                .get(self.idx + 1)
                .is_some_and(|b| matches!(b, b'\'' | b'"'))
    }

    fn read_raw_string(&mut self) -> Result<(), LowerError> {
        let start = self.idx;
        let start_line = self.line;
        self.idx += 1;
        let quote = self.bytes[self.idx];
        let triple = self.is_triple_quote(quote);
        self.idx += if triple { 3 } else { 1 };
        self.consume_raw_string_body(start_line, quote, triple)?;
        self.emit_multiline_string(start, start_line);
        Ok(())
    }

    fn read_string(&mut self) -> Result<(), LowerError> {
        let open_line = self.line;
        let quote = self.bytes[self.idx];
        let triple = self.is_triple_quote(quote);
        let mut seg_start = self.idx;
        let mut seg_start_line = self.line;
        self.idx += if triple { 3 } else { 1 };
        while self.idx < self.bytes.len() {
            if self.try_consume_string_escape() {
                continue;
            }
            if self.bytes[self.idx] == b'$' && self.bytes.get(self.idx + 1) == Some(&b'{') {
                self.emit_multiline_string(seg_start, seg_start_line);
                self.read_interpolation(open_line)?;
                seg_start = self.idx;
                seg_start_line = self.line;
                continue;
            }
            if self.matches_string_end(quote, triple) {
                self.idx += if triple { 3 } else { 1 };
                self.emit_multiline_string(seg_start, seg_start_line);
                return Ok(());
            }
            self.advance_string_char(open_line, triple)?;
        }
        Err(LowerError::Unparsable(format!(
            "unterminated string literal at line {open_line}"
        )))
    }

    fn try_consume_string_escape(&mut self) -> bool {
        if self.bytes[self.idx] != b'\\' || self.idx + 1 >= self.bytes.len() {
            return false;
        }
        if self.bytes[self.idx + 1] == b'\n' {
            self.line += 1;
        }
        self.idx += 2;
        true
    }

    fn advance_string_char(&mut self, open_line: u32, triple: bool) -> Result<(), LowerError> {
        if self.bytes[self.idx] == b'\n' {
            if !triple {
                return Err(LowerError::Unparsable(format!(
                    "unterminated string literal at line {open_line}"
                )));
            }
            self.line += 1;
        }
        self.idx += 1;
        Ok(())
    }

    fn is_triple_quote(&self, quote: u8) -> bool {
        self.bytes.get(self.idx + 1) == Some(&quote) && self.bytes.get(self.idx + 2) == Some(&quote)
    }

    fn consume_raw_string_body(
        &mut self,
        start_line: u32,
        quote: u8,
        triple: bool,
    ) -> Result<(), LowerError> {
        while self.idx < self.bytes.len() {
            if self.matches_string_end(quote, triple) {
                self.idx += if triple { 3 } else { 1 };
                return Ok(());
            }
            self.advance_string_char(start_line, triple)?;
        }
        Err(LowerError::Unparsable(format!(
            "unterminated string literal at line {start_line}"
        )))
    }

    fn read_interpolation(&mut self, open_line: u32) -> Result<(), LowerError> {
        self.idx += 2;
        self.delims.push((b'{', self.line));
        self.push_tok(DartKind::Punct, "{");
        let base_depth = self.delims.len();
        while self.idx < self.bytes.len() {
            if self.delims.len() == base_depth && self.bytes[self.idx] == b'}' {
                self.delims.pop();
                self.push_tok(DartKind::Punct, "}");
                self.idx += 1;
                return Ok(());
            }
            self.next_unit()?;
        }
        Err(LowerError::Unparsable(format!(
            "unterminated string interpolation at line {open_line}"
        )))
    }

    fn matches_string_end(&self, quote: u8, triple: bool) -> bool {
        if self.bytes[self.idx] != quote {
            return false;
        }
        !triple || self.is_triple_quote(quote)
    }

    fn emit_multiline_string(&mut self, start: usize, start_line: u32) {
        for l in start_line..=self.line {
            self.code_lines.insert(l);
        }
        self.tokens.push(DartToken {
            kind: DartKind::StringLit,
            text: self.src[start..self.idx].to_owned(),
            line: start_line,
            end_line: self.line,
        });
    }

    fn read_word(&mut self) {
        let start = self.idx;
        self.idx += 1;
        while self.idx < self.bytes.len() && is_id_continue(self.bytes[self.idx]) {
            self.idx += 1;
        }
        let slice = &self.src[start..self.idx];
        let kind = if is_dart_keyword(slice) {
            DartKind::Keyword
        } else {
            DartKind::Ident
        };
        self.push_tok(kind, slice);
    }

    fn read_number(&mut self) {
        let start = self.idx;
        if self.bytes[self.idx] == b'0'
            && self
                .bytes
                .get(self.idx + 1)
                .is_some_and(|b| matches!(b, b'x' | b'X'))
        {
            self.idx += 2;
            while self.idx < self.bytes.len() && is_hex_or_sep(self.bytes[self.idx]) {
                self.idx += 1;
            }
        } else {
            self.consume_digits();
            if self.bytes.get(self.idx) == Some(&b'.')
                && self.bytes.get(self.idx + 1).is_some_and(u8::is_ascii_digit)
            {
                self.idx += 1;
                self.consume_digits();
            }
            if self
                .bytes
                .get(self.idx)
                .is_some_and(|b| matches!(b, b'e' | b'E'))
            {
                self.consume_exponent();
            }
        }
        let slice = &self.src[start..self.idx];
        self.push_tok(DartKind::NumberLit, slice);
    }

    fn consume_digits(&mut self) {
        while self.idx < self.bytes.len()
            && (self.bytes[self.idx].is_ascii_digit() || self.bytes[self.idx] == b'_')
        {
            self.idx += 1;
        }
    }

    fn consume_exponent(&mut self) {
        let mut look = self.idx + 1;
        if self
            .bytes
            .get(look)
            .is_some_and(|b| matches!(b, b'+' | b'-'))
        {
            look += 1;
        }
        if self.bytes.get(look).is_some_and(u8::is_ascii_digit) {
            self.idx = look;
            self.consume_digits();
        }
    }

    fn read_punct(&mut self) -> Result<(), LowerError> {
        let op =
            match_dart_op(&self.bytes[self.idx..]).unwrap_or(&self.src[self.idx..self.idx + 1]);
        track_delim(&mut self.delims, op, self.line)?;
        self.push_tok(DartKind::Punct, op);
        self.idx += op.len();
        Ok(())
    }

    fn push_tok(&mut self, kind: DartKind, text: &str) {
        self.code_lines.insert(self.line);
        self.tokens.push(DartToken {
            kind,
            text: text.to_owned(),
            line: self.line,
            end_line: self.line,
        });
    }
}

fn is_id_start(b: u8) -> bool {
    matches!(b, b'a'..=b'z' | b'A'..=b'Z' | b'_' | b'$' | 0x80..=0xff)
}

fn is_id_continue(b: u8) -> bool {
    is_id_start(b) || b.is_ascii_digit()
}

fn is_hex_or_sep(b: u8) -> bool {
    b.is_ascii_hexdigit() || b == b'_'
}

fn match_dart_op(bytes: &[u8]) -> Option<&'static str> {
    static MULTI_OPS: &[&str] = &[
        "...?", ">>>=", "...", "?..", "??=", "~/=", ">>=", "<<=", ">>>", "~/", "??", "?.", "..",
        "=>", "&&", "||", "==", "!=", "<=", ">=", "++", "--", "+=", "-=", "*=", "/=", "%=", "&=",
        "|=", "^=", "<<", ">>",
    ];
    MULTI_OPS
        .iter()
        .copied()
        .find(|op| bytes.starts_with(op.as_bytes()))
}