oxc_parser 0.161.0

A collection of JavaScript tools written in Rust.
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
//! Token cursor: reading, consuming, expecting and re-lexing the current token,
//! and checkpoints for backtracking.

use oxc_ast::ast::RegExpFlags;
use oxc_span::Span;
use oxc_str::JSStr;

use crate::{
    ParserConfig as Config, ParserImpl, diagnostics,
    lexer::{Kind, LexerCheckpoint, Token, cold_branch},
};

#[derive(Clone, Copy)]
pub struct ParserCheckpoint<'a> {
    lexer: LexerCheckpoint<'a>,
    cur_token: Token,
    prev_token_end: u32,
    errors_pos: usize,
    cover_parenthesized_len: usize,
    dynamic_imports_len: usize,
    import_metas_len: usize,
    has_fatal_error: bool,
}

impl<'a> ParserCheckpoint<'a> {
    pub(crate) fn lexer(&self) -> &LexerCheckpoint<'a> {
        &self.lexer
    }

    /// The current token when the checkpoint was saved.
    pub(crate) fn token(&self) -> Token {
        self.cur_token
    }

    pub(crate) fn prev_token_end(&self) -> u32 {
        self.prev_token_end
    }

    pub(crate) fn errors_len(&self) -> usize {
        self.errors_pos
    }

    pub(crate) fn dynamic_imports_len(&self) -> usize {
        self.dynamic_imports_len
    }

    pub(crate) fn import_metas_len(&self) -> usize {
        self.import_metas_len
    }
}

impl<'a, C: Config> ParserImpl<'a, C> {
    /// Get current token's span start.
    #[inline]
    pub(crate) fn cur_start(&self) -> u32 {
        self.token.start()
    }

    /// Create a [`Span`] from provided `start` to end of previous token.
    #[inline]
    pub(crate) fn end_span(&self, start: u32) -> Span {
        Span::new(start, self.prev_token_end)
    }

    /// Get current token
    #[inline]
    pub(crate) fn cur_token(&self) -> Token {
        self.token
    }

    /// Get current Kind
    #[inline]
    pub(crate) fn cur_kind(&self) -> Kind {
        self.token.kind()
    }

    /// Get current source text
    #[inline]
    pub(crate) fn cur_src(&self) -> &'a str {
        self.token_source(&self.token)
    }

    /// Get source text for a token
    #[inline]
    pub(crate) fn token_source(&self, token: &Token) -> &'a str {
        let span = token.span();
        if cfg!(debug_assertions) {
            &self.source_text[span.start as usize..span.end as usize]
        } else {
            // SAFETY:
            // Span comes from the lexer, which ensures:
            // * `start` and `end` are in bounds of source text.
            // * `end >= start`.
            // * `start` and `end` are both on UTF-8 char boundaries.
            // * `self.source_text` is same text that `Token`s are generated from.
            //
            // TODO: I (@overlookmotel) don't think we should really be doing this.
            // We don't have static guarantees of these properties.
            unsafe { self.source_text.get_unchecked(span.start as usize..span.end as usize) }
        }
    }

    /// Get current string
    pub(crate) fn cur_string(&self) -> &'a str {
        self.lexer.get_string(self.token)
    }

    /// Get the decoded value of the current string literal.
    pub(crate) fn cur_js_string(&self) -> JSStr<'a> {
        self.lexer.get_js_string(self.token)
    }

    /// Get current template string
    pub(crate) fn cur_template_string(&self) -> Option<JSStr<'a>> {
        self.lexer.get_template_string(self.token.start())
    }

    /// Checks if the current index has token `Kind`
    #[inline]
    pub(crate) fn at(&self, kind: Kind) -> bool {
        self.cur_kind() == kind
    }

    /// `StringValue` of `IdentifierName` normalizes any Unicode escape sequences
    /// in `IdentifierName` hence such escapes cannot be used to write an Identifier
    /// whose code point sequence is the same as a `ReservedWord`.
    #[cold]
    fn report_escaped_keyword(&mut self, span: Span) {
        self.error(diagnostics::escaped_keyword(span));
    }

    /// Move to the next token
    /// Checks if the current token is escaped if it is a keyword
    #[inline]
    pub(crate) fn advance(&mut self, kind: Kind) {
        // Manually inlined escaped keyword check - escaped identifiers are extremely rare
        if self.token.escaped() && kind.is_any_keyword() {
            self.report_escaped_keyword(self.token.span());
        }
        self.prev_token_end = self.token.end();
        self.token = self.lexer.next_token();
    }

    /// Move to the next `JSXChild`
    /// Checks if the current token is escaped if it is a keyword
    pub(crate) fn advance_for_jsx_child(&mut self) {
        self.prev_token_end = self.token.end();
        self.token = self.lexer.next_jsx_child();
    }

    /// Advance and return true if we are at `Kind`, return false otherwise
    #[inline]
    #[must_use = "Use `bump` instead of `eat` if you are ignoring the return value"]
    pub(crate) fn eat(&mut self, kind: Kind) -> bool {
        if self.at(kind) {
            self.advance(kind);
            return true;
        }
        false
    }

    /// Advance if we are at `Kind`
    #[inline]
    pub(crate) fn bump(&mut self, kind: Kind) {
        if self.at(kind) {
            self.advance(kind);
        }
    }

    /// Advance any token
    #[inline]
    pub(crate) fn bump_any(&mut self) {
        self.advance(self.cur_kind());
    }

    /// Advance if `accept` holds for the token after the current one.
    ///
    /// Use this instead of [`Lexer::peek_token`] where the answer is nearly always yes, such as
    /// a modifier keyword, which is nearly always followed by the member it modifies. The token
    /// after is then lexed once and kept. Peeking lexes it, discards it, and leaves it to be
    /// lexed again.
    ///
    /// [`Lexer::peek_token`]: crate::lexer::Lexer::peek_token
    #[inline]
    pub(crate) fn eat_if_next(&mut self, accept: impl FnOnce(Token) -> bool) -> bool {
        let checkpoint = self.lexer.checkpoint();
        let next = self.lexer.next_token();
        if !accept(next) {
            self.lexer.rewind(checkpoint);
            return false;
        }
        self.advance_to(next);
        true
    }

    /// Move to `next`, the token after the current one, which the lexer has already read.
    #[inline]
    pub(crate) fn advance_to(&mut self, next: Token) {
        if self.token.escaped() && self.token.kind().is_any_keyword() {
            self.report_escaped_keyword(self.token.span());
        }
        self.prev_token_end = self.token.end();
        self.token = next;
    }

    /// [Automatic Semicolon Insertion](https://tc39.es/ecma262/#sec-automatic-semicolon-insertion)
    /// # Errors
    pub(crate) fn asi(&mut self) {
        if self.eat(Kind::Semicolon) || self.can_insert_semicolon() {
            /* no op */
        } else {
            // ASI failure is a syntax error (cold). Build the diagnostic out of line so the
            // ~232-byte `OxcDiagnostic` buffer does not inflate `asi`'s stack frame on the
            // common (valid) path.
            cold_branch(|| {
                let span = Span::empty(self.prev_token_end);
                let error = diagnostics::auto_semicolon_insertion(span);
                self.set_fatal_error(error);
            });
        }
    }

    #[inline]
    pub(crate) fn can_insert_semicolon(&self) -> bool {
        let token = self.cur_token();
        matches!(token.kind(), Kind::Semicolon | Kind::RCurly | Kind::Eof) || token.is_on_new_line()
    }

    /// Cold path for expect failures - separated to improve branch prediction
    #[cold]
    #[inline(never)]
    fn handle_expect_failure(&mut self, expected_kind: Kind) {
        let range = self.cur_token().span();
        let error =
            diagnostics::expect_token(expected_kind.to_str(), self.cur_kind().to_str(), range);
        self.set_fatal_error(error);
    }

    /// # Errors
    #[inline]
    pub(crate) fn expect_without_advance(&mut self, kind: Kind) {
        if !self.at(kind) {
            self.handle_expect_failure(kind);
        }
    }

    /// Expect a `Kind` or return error
    /// # Errors
    #[inline]
    pub(crate) fn expect(&mut self, kind: Kind) {
        if !self.at(kind) {
            self.handle_expect_failure(kind);
        }
        self.advance(kind);
    }

    #[inline]
    pub(crate) fn expect_closing(&mut self, kind: Kind, opening_span: Span) {
        if !self.at(kind) {
            let range = self.cur_token().span();
            let error = diagnostics::expect_closing(
                kind.to_str(),
                self.cur_kind().to_str(),
                range,
                opening_span,
            );
            self.set_fatal_error(error);
        }
        self.advance(kind);
    }

    #[inline]
    pub(crate) fn expect_conditional_alternative(&mut self, question_span: Span) {
        if !self.at(Kind::Colon) {
            let range = self.cur_token().span();
            let error = diagnostics::expect_conditional_alternative(
                self.cur_kind().to_str(),
                range,
                question_span,
            );
            self.set_fatal_error(error);
        }
        self.bump_any(); // bump `:`
    }

    /// Expect the next next token to be a `JsxChild`, i.e. `<` or `{` or `JSXText`
    /// # Errors
    pub(crate) fn expect_jsx_child(&mut self, kind: Kind) {
        self.expect_without_advance(kind);
        self.advance_for_jsx_child();
    }

    /// Move to the next token, lexing it as a JSX attribute value.
    pub(crate) fn advance_for_jsx_attribute_value(&mut self) {
        self.prev_token_end = self.token.end();
        self.token = self.lexer.next_jsx_attribute_value();
    }

    /// Tell lexer to read a regex
    pub(crate) fn read_regex(&mut self) -> (u32, RegExpFlags) {
        let (token, pattern_end, flags) = self.lexer.next_regex(self.cur_kind());
        self.token = token;
        (pattern_end, flags)
    }

    /// Tell lexer to read a template substitution tail
    pub(crate) fn re_lex_template_substitution_tail(&mut self) {
        if self.fatal_error.is_some() {
            return;
        }
        if self.at(Kind::RCurly) {
            self.token = self.lexer.next_template_substitution_tail();
        }
    }

    /// Tell lexer to continue reading jsx identifier if the lexer character position is at `-` for `<component-name>`.
    ///
    /// Returns `true` if was continued.
    #[inline]
    pub(crate) fn continue_lex_jsx_identifier(&mut self) -> bool {
        if let Some(token) = self.lexer.continue_lex_jsx_identifier(self.token.start()) {
            self.token = token;
            true
        } else {
            false
        }
    }

    #[inline]
    pub(crate) fn re_lex_right_angle(&mut self) -> Kind {
        if self.fatal_error.is_some() {
            return Kind::Eof;
        }
        let kind = self.cur_kind();
        if kind == Kind::RAngle {
            self.token = self.lexer.re_lex_right_angle();
            self.token.kind()
        } else {
            kind
        }
    }

    pub(crate) fn re_lex_ts_l_angle(&mut self) -> bool {
        if self.fatal_error.is_some() {
            return false;
        }
        let kind = self.cur_kind();
        if kind == Kind::ShiftLeft {
            self.token = self.lexer.re_lex_as_typescript_l_angle(2);
            true
        } else if kind == Kind::ShiftLeftEq {
            self.token = self.lexer.re_lex_as_typescript_l_angle(3);
            true
        } else {
            kind == Kind::LAngle
        }
    }

    pub(crate) fn re_lex_ts_r_angle(&mut self) -> bool {
        if self.fatal_error.is_some() {
            return false;
        }
        let kind = self.cur_kind();
        if kind == Kind::ShiftRight {
            self.token = self.lexer.re_lex_as_typescript_r_angle(2);
            true
        } else if kind == Kind::ShiftRight3 {
            self.token = self.lexer.re_lex_as_typescript_r_angle(3);
            true
        } else {
            kind == Kind::RAngle
        }
    }

    pub(crate) fn checkpoint(&self) -> ParserCheckpoint<'a> {
        ParserCheckpoint {
            lexer: self.lexer.checkpoint(),
            cur_token: self.token,
            prev_token_end: self.prev_token_end,
            errors_pos: self.errors.len(),
            cover_parenthesized_len: self.state.cover_parenthesized.len(),
            dynamic_imports_len: self.module_record_builder.dynamic_imports_len(),
            import_metas_len: self.module_record_builder.import_metas_len(),
            has_fatal_error: self.fatal_error.is_some(),
        }
    }

    pub(crate) fn rewind(&mut self, checkpoint: ParserCheckpoint<'a>) {
        let ParserCheckpoint {
            lexer,
            cur_token,
            prev_token_end,
            errors_pos,
            cover_parenthesized_len,
            dynamic_imports_len,
            import_metas_len,
            has_fatal_error,
        } = checkpoint;

        // A fatal error set after the checkpoint is discarded. If it is a lexer error that
        // `set_unexpected` took from the lexer, give it back.
        if !has_fatal_error
            && let Some(fatal_error) = self.fatal_error.take()
            && self.lexer.errors.len() < lexer.errors_len()
        {
            self.lexer.errors.push(fatal_error.error);
        }
        self.lexer.rewind(lexer);
        self.token = cur_token;
        self.prev_token_end = prev_token_end;
        self.errors.truncate(errors_pos);
        self.state.cover_parenthesized.truncate(cover_parenthesized_len);
        self.module_record_builder
            .truncate_expression_records(dynamic_imports_len, import_metas_len);
    }

    /// Continue parsing from `checkpoint`, keeping all output.
    ///
    /// The output before `checkpoint` must have been put back, though maybe at different indexes.
    /// That output can include a fatal error, which stopped parsing at `checkpoint`.
    /// `top_level_await.rs` takes such a checkpoint with the fatal error moved out, and puts it
    /// back before resuming.
    pub(crate) fn resume(&mut self, checkpoint: &ParserCheckpoint<'a>) {
        debug_assert!(!checkpoint.has_fatal_error);
        debug_assert_eq!(self.state.cover_parenthesized.len(), checkpoint.cover_parenthesized_len);
        self.lexer.resume(&checkpoint.lexer);
        self.token = checkpoint.cur_token;
        self.prev_token_end = checkpoint.prev_token_end;
    }

    pub(crate) fn lookahead<U>(&mut self, predicate: impl Fn(&mut ParserImpl<'a, C>) -> U) -> U {
        let checkpoint = self.checkpoint();
        let answer = predicate(self);
        self.rewind(checkpoint);
        answer
    }
}