quickjs-oxide 0.4.0

A safe Rust JavaScript engine targeting semantic parity with QuickJS
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
use crate::engine::api::error::Error;
use crate::engine::code::bytecode::Instruction;
use crate::engine::code::function::metadata::ClassInitializerKind;
use crate::engine::code::function::metadata::FunctionKind as BytecodeFunctionKind;
use crate::engine::compiler::lexer::LexContext;
use crate::engine::compiler::lexer::LexicalGoal;
use crate::engine::compiler::lexer::Punctuator;
use crate::engine::compiler::lexer::Span;
use crate::engine::compiler::lexer::TemplatePartKind;
use crate::engine::compiler::lexer::TokenKind;
use crate::engine::compiler::model::ir::IrConstant;
use crate::engine::compiler::model::ir::IrOp;
use crate::engine::compiler::model::ir::function::FunctionIrOptions;
use crate::engine::compiler::model::ir::function::FunctionKind;
use crate::engine::compiler::model::ir::function::FunctionSourceInfo;
use crate::engine::compiler::model::ir::function::ParentLink;
use crate::engine::compiler::model::ir::function::SuperCapabilities;
use crate::engine::compiler::parser::builder::FunctionBuilder;
use crate::engine::compiler::parser::context::AnonymousFunctionDefinition;
use crate::engine::compiler::parser::context::ForHeadDelimiter;
use crate::engine::compiler::parser::context::Parser;
use crate::engine::compiler::parser::diagnostics::IdentifierContext;
use crate::engine::compiler::parser::diagnostics::source_offset;
use crate::engine::compiler::parser::tokens::for_head_regexp_allowed_after;
use crate::engine::compiler::stack_guard::ParserStackFrame;
use crate::source::SourceOffset;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum ArrowHead {
    Identifier,
    Parenthesized,
}

impl<'source> Parser<'source> {
    pub(super) fn parse_arrow_function(&mut self, head: ArrowHead) -> Result<(), Error> {
        self.parse_arrow_function_with_kind(
            head,
            self.current().span,
            self.lexer.context(),
            BytecodeFunctionKind::Normal,
        )
    }

    pub(super) fn parse_async_arrow_function(&mut self, head: ArrowHead) -> Result<(), Error> {
        let function_span = self.current().span;
        let parent_context = self.lexer.context();
        // Pinned QuickJS commits the token immediately after `async` in the
        // parent function before creating the async arrow. Keep that token
        // intact so the single-parameter `async await =>` asymmetry survives.
        self.advance()?;
        self.parse_arrow_function_with_kind(
            head,
            function_span,
            parent_context,
            BytecodeFunctionKind::Async,
        )
    }

    fn parse_arrow_function_with_kind(
        &mut self,
        head: ArrowHead,
        function_span: Span,
        parent_context: LexContext,
        execution_kind: BytecodeFunctionKind,
    ) -> Result<(), Error> {
        if !matches!(
            execution_kind,
            BytecodeFunctionKind::Normal | BytecodeFunctionKind::Async
        ) {
            return Err(Error::internal(
                "arrow parser received an invalid execution kind",
            ));
        }
        let parent = self.current_function;
        let parent_strict = self.functions[parent].strict;
        let mut parameter_tokens = Vec::new();
        let child = self.functions.len();
        let parent_scope = self.functions[parent].context.current_scope;
        let parent_execution_kind = self.functions[parent].execution_kind;
        let parent_is_class_static_block = self.functions[parent].class_initializer_kind
            == Some(ClassInitializerKind::StaticBlock);
        let super_capabilities = SuperCapabilities {
            super_call_allowed: self.functions[parent].super_call_allowed,
            super_allowed: self.functions[parent].super_allowed,
        };
        self.functions.push(FunctionBuilder::new(
            Some(ParentLink {
                function: parent,
                definition_scope: parent_scope,
            }),
            FunctionKind::Arrow,
            FunctionSourceInfo {
                span: function_span,
                definition: source_offset(function_span)?,
                range: None,
            },
            FunctionIrOptions {
                function_name: None,
                private_name_binding: false,
                class_constructor: false,
                derived_class_constructor: false,
                defined_argument_count: 0,
                has_simple_parameter_list: true,
                rest_parameter: None,
                parameters: Vec::new(),
                strict: parent_strict,
                super_capabilities,
            },
            &mut self.names,
        )?);
        self.functions[child].execution_kind = execution_kind;
        self.functions[child].arguments_forbidden = self.functions[parent].arguments_forbidden;
        self.current_function = child;

        let mut parameter_context = parent_context;
        parameter_context.strict = parent_strict;
        // QuickJS classifies arrow formal parameters from the new arrow plus
        // its immediate parse parent, not from a flattened lexer context.
        // Preserve the already-read current token for its single-parameter
        // quirk, but reset future yield/await classification at every arrow
        // boundary before parsing parenthesized parameters and defaults.
        parameter_context.generator = matches!(
            parent_execution_kind,
            BytecodeFunctionKind::Generator | BytecodeFunctionKind::AsyncGenerator
        );
        parameter_context.async_function = execution_kind == BytecodeFunctionKind::Async
            || matches!(
                parent_execution_kind,
                BytecodeFunctionKind::Async | BytecodeFunctionKind::AsyncGenerator
            )
            || parent_is_class_static_block;
        self.set_future_lex_context(parameter_context);

        match head {
            ArrowHead::Identifier => {
                let token = *self.current();
                let TokenKind::Identifier(identifier) = token.kind else {
                    return Err(Error::internal(
                        "identifier arrow lookahead lost its parameter token",
                    ));
                };
                self.validate_identifier(
                    &identifier,
                    token.span,
                    false,
                    IdentifierContext::Argument,
                )?;
                let parameter = self.intern_identifier(&identifier);
                self.register_plain_identifier_parameter(parameter, token.span)?;
                parameter_tokens.push((identifier, token.span));
                self.advance()?;
            }
            ArrowHead::Parenthesized => {
                let parameter_scan = self.parenthesized_parameter_scan();
                if parameter_scan.is_some_and(|scan| scan.has_assignment) {
                    self.activate_parameter_environment_from_scan(
                        parameter_scan.and_then(|scan| scan.bound_name_count),
                    )?;
                }
                self.expect_punctuator(Punctuator::LeftParen)?;
                if !self.consume_punctuator(Punctuator::RightParen)? {
                    loop {
                        let is_rest = self.consume_punctuator(Punctuator::Ellipsis)?;
                        let pattern = match self.current().kind {
                            TokenKind::Punctuator(Punctuator::LeftBracket) => Some(true),
                            TokenKind::Punctuator(Punctuator::LeftBrace) => Some(false),
                            _ => None,
                        };
                        if let Some(array_pattern) = pattern {
                            let span = self.current().span;
                            self.activate_pattern_parameter_initialization()?;
                            if is_rest {
                                let start = self.register_rest_pattern_parameter()?;
                                let has_initializer = if array_pattern {
                                    self.parse_array_rest_parameter_binding_pattern(start)?
                                } else {
                                    self.parse_object_rest_parameter_binding_pattern(start)?
                                };
                                self.finish_pattern_parameter_length(start, has_initializer)?;
                                if !self.is_punctuator(Punctuator::RightParen) {
                                    return Err(self.syntax_here("expecting ')'"));
                                }
                                self.advance()?;
                                break;
                            }
                            let argument = self.append_pattern_parameter(span)?;
                            let has_initializer = if array_pattern {
                                self.parse_array_parameter_binding_pattern(argument)?
                            } else {
                                self.parse_object_parameter_binding_pattern(argument)?
                            };
                            self.finish_pattern_parameter_length(argument, has_initializer)?;
                            if self.consume_punctuator(Punctuator::RightParen)? {
                                break;
                            }
                            self.expect_punctuator(Punctuator::Comma)?;
                            if self.consume_punctuator(Punctuator::RightParen)? {
                                break;
                            }
                            continue;
                        }
                        let token = *self.current();
                        let TokenKind::Identifier(identifier) = token.kind else {
                            return Err(self.syntax_here("missing formal parameter"));
                        };
                        self.validate_identifier(
                            &identifier,
                            token.span,
                            false,
                            IdentifierContext::Argument,
                        )?;
                        let parameter = self.intern_identifier(&identifier);
                        parameter_tokens.push((identifier, token.span));
                        self.advance()?;
                        if is_rest {
                            self.register_rest_identifier_parameter(parameter, token.span)?;
                            if !self.is_punctuator(Punctuator::RightParen) {
                                return Err(self.syntax_here("expecting ')'"));
                            }
                            self.advance()?;
                            break;
                        }
                        if self.is_punctuator(Punctuator::Equal) {
                            self.parse_default_identifier_parameter(parameter, token.span)?;
                        } else {
                            self.register_plain_identifier_parameter(parameter, token.span)?;
                        }
                        if self.consume_punctuator(Punctuator::RightParen)? {
                            break;
                        }
                        self.expect_punctuator(Punctuator::Comma)?;
                        if self.consume_punctuator(Punctuator::RightParen)? {
                            break;
                        }
                    }
                }
            }
        }

        if !self.is_punctuator(Punctuator::Arrow) || self.current().line_terminator_before {
            return Err(self.syntax_here("expecting '=>'"));
        }
        self.advance_expression_start()?;
        let mut child_context = parent_context;
        child_context.strict = parent_strict;
        child_context.generator = false;
        child_context.async_function = execution_kind == BytecodeFunctionKind::Async;
        self.relex_current_with_context(child_context)?;
        let block_body = self.is_punctuator(Punctuator::LeftBrace);
        if block_body {
            self.advance()?;
        }
        let has_use_strict = if block_body {
            self.directive_prologue_has_use_strict(parent_strict)?
        } else {
            false
        };
        let strict = parent_strict || has_use_strict;
        if block_body {
            child_context.strict = strict;
            self.relex_current_with_context(child_context)?;
        }
        let has_simple_parameter_list = self.functions[child].has_simple_parameter_list;
        if has_use_strict && !has_simple_parameter_list {
            return Err(Error::syntax(
                "\"use strict\" not allowed in function with default or destructuring parameter",
                self.current().span,
            ));
        }
        if strict {
            // QuickJS checks parameter names once the body starts, at its
            // first token.
            let strict_validation_span = self.current().span;
            for (identifier, _) in &parameter_tokens {
                self.validate_identifier(
                    identifier,
                    strict_validation_span,
                    true,
                    IdentifierContext::Argument,
                )?;
            }
        }
        let parameters = &self.functions[child].parameter_names;
        for (index, parameter) in parameters.iter().enumerate() {
            if parameters[..index].contains(parameter) {
                return Err(Error::syntax(
                    "duplicate argument names not allowed in this context",
                    self.current().span,
                ));
            }
        }

        self.functions[child].strict = strict;
        self.finish_identifier_parameter_environment()?;
        self.functions[child].context.in_function_body = true;

        // Every arrow is one parser edge; a braced body adds its own frame
        // cost, matching the pinned first-throw depths for concise (`x=>`)
        // and block-bodied (`x=>{`) arrow chains.
        let range_end = self.parse_recursion(ParserStackFrame::Arrow, |parser| {
            if block_body {
                parser
                    .parse_recursion(ParserStackFrame::ArrowBlockBody, Self::parse_function_body)?;
                let closing_brace = parser.current().span;
                parser.relex_current_with_context(parent_context)?;
                parser.expect_punctuator(Punctuator::RightBrace)?;
                Ok(closing_brace.end.byte_offset)
            } else {
                parser.parse_assignment()?;
                parser.emit_instruction(Instruction::Return)?;
                let range_end = parser
                    .previous_end
                    .unwrap_or(parser.current().span.start.byte_offset);
                parser.relex_current_with_context(parent_context)?;
                Ok(range_end)
            }
        })?;
        self.functions[child].source.range = Some(
            source_offset(function_span)?
                ..SourceOffset::try_from_usize(range_end)
                    .map_err(|error| Error::internal(error.to_string()))?,
        );
        self.functions[child].finish_parsing()?;
        self.current_function = parent;
        let constant = self.add_constant(IrConstant::Child(child))?;
        self.emit(IrOp::MakeClosure(constant))?;
        self.anonymous_function_definition = Some(AnonymousFunctionDefinition::Function);
        Ok(())
    }

    /// Non-committing QuickJS-style ArrowParameters probe. The scanner owns
    /// no IR or scope state: it balances the cover grammar, respects template
    /// substitutions and RegExp lexical goals, and accepts `=>` only when no
    /// LineTerminator separates it from the closing parenthesis.
    fn parenthesized_arrow_ahead(&self, opening: Span) -> bool {
        if let Some(arrow) = self.cached_parenthesized_arrow(opening.start.byte_offset) {
            return arrow;
        }
        let mut lexer = self.lexer.clone();
        lexer.seek(opening.start);
        let Ok(first) = self.probe_token(&mut lexer, LexicalGoal::Div) else {
            return false;
        };
        if !matches!(first.kind, TokenKind::Punctuator(Punctuator::LeftParen)) {
            return false;
        }

        let mut delimiters = self.delimiter_stack();
        delimiters.push(ForHeadDelimiter::Parenthesis);
        let mut parentheses = vec![opening.start.byte_offset];
        let mut closed_parenthesis = None;
        let mut goal = LexicalGoal::Div;
        let mut regexp_allowed = true;
        loop {
            let requested_goal = goal;
            goal = LexicalGoal::Div;
            let Ok(mut token) = self.probe_token(&mut lexer, requested_goal) else {
                return false;
            };
            if let Some(start) = closed_parenthesis.take() {
                self.cache_parenthesized_arrow(
                    start,
                    !token.line_terminator_before
                        && matches!(token.kind, TokenKind::Punctuator(Punctuator::Arrow)),
                );
            }
            if requested_goal == LexicalGoal::Div
                && regexp_allowed
                && matches!(
                    token.kind,
                    TokenKind::Punctuator(Punctuator::Divide | Punctuator::DivideAssign)
                )
            {
                lexer.seek(token.span.start);
                let Ok(regexp) = self.probe_token(&mut lexer, LexicalGoal::RegExp) else {
                    return false;
                };
                token = regexp;
            }

            match &token.kind {
                TokenKind::Punctuator(Punctuator::LeftParen) => {
                    if delimiters.len() >= 255 {
                        return false;
                    }
                    delimiters.push(ForHeadDelimiter::Parenthesis);
                    parentheses.push(token.span.start.byte_offset);
                }
                TokenKind::Punctuator(Punctuator::LeftBracket) => {
                    if delimiters.len() >= 255 {
                        return false;
                    }
                    delimiters.push(ForHeadDelimiter::Bracket);
                }
                TokenKind::Punctuator(Punctuator::LeftBrace) => {
                    if delimiters.len() >= 255 {
                        return false;
                    }
                    delimiters.push(ForHeadDelimiter::Brace);
                }
                TokenKind::Punctuator(Punctuator::RightParen) => {
                    if delimiters.pop() != Some(ForHeadDelimiter::Parenthesis) {
                        return false;
                    }
                    let start = parentheses.pop().expect("balanced parenthesis probe");
                    if delimiters.is_empty() {
                        let Ok(arrow) = self.probe_token(&mut lexer, LexicalGoal::Div) else {
                            return false;
                        };
                        let result = !arrow.line_terminator_before
                            && matches!(arrow.kind, TokenKind::Punctuator(Punctuator::Arrow));
                        self.cache_parenthesized_arrow(start, result);
                        return result;
                    }
                    closed_parenthesis = Some(start);
                }
                TokenKind::Punctuator(Punctuator::RightBracket) => {
                    if delimiters.pop() != Some(ForHeadDelimiter::Bracket) {
                        return false;
                    }
                }
                TokenKind::Punctuator(Punctuator::RightBrace) => {
                    if delimiters.last() == Some(&ForHeadDelimiter::Template) {
                        goal = LexicalGoal::TemplateContinuation;
                        regexp_allowed = true;
                        continue;
                    }
                    if delimiters.pop() != Some(ForHeadDelimiter::Brace) {
                        return false;
                    }
                }
                TokenKind::Template(part) => match part.kind {
                    TemplatePartKind::Head => {
                        if delimiters.len() >= 255 {
                            return false;
                        }
                        delimiters.push(ForHeadDelimiter::Template);
                    }
                    TemplatePartKind::Middle => {
                        if delimiters.last() != Some(&ForHeadDelimiter::Template) {
                            return false;
                        }
                    }
                    TemplatePartKind::Tail => {
                        if delimiters.pop() != Some(ForHeadDelimiter::Template) {
                            return false;
                        }
                    }
                    TemplatePartKind::NoSubstitution => {}
                },
                TokenKind::Eof => return false,
                _ => {}
            }
            regexp_allowed = for_head_regexp_allowed_after(&token.kind);
        }
    }

    pub(super) fn arrow_head_ahead(&self) -> Option<ArrowHead> {
        match &self.current().kind {
            TokenKind::Identifier(_) => {
                if !self.arrow_may_follow_current() {
                    return None;
                }
                let mut lexer = self.lexer.clone();
                lexer.seek(self.current().span.end);
                let next = self.probe_token(&mut lexer, LexicalGoal::Div).ok()?;
                (!next.line_terminator_before
                    && matches!(next.kind, TokenKind::Punctuator(Punctuator::Arrow)))
                .then_some(ArrowHead::Identifier)
            }
            TokenKind::Punctuator(Punctuator::LeftParen)
                if self.parenthesized_arrow_ahead(self.current().span) =>
            {
                Some(ArrowHead::Parenthesized)
            }
            _ => None,
        }
    }

    /// Reject the ordinary ASCII non-arrow cases before cloning the lexer and
    /// maintaining its token cache. Comments/Unicode still use the complete
    /// scanner, including Annex B trivia and LineTerminator restrictions.
    fn arrow_may_follow_current(&self) -> bool {
        let bytes = self.lexer.source().as_bytes();
        let mut offset = self.current().span.end.byte_offset;
        while matches!(bytes.get(offset), Some(b' ' | b'\t' | 0x0b | 0x0c)) {
            offset += 1;
        }
        match bytes.get(offset) {
            Some(b'=') => bytes.get(offset + 1) == Some(&b'>'),
            Some(b'/' | b'<' | b'-' | 0x80..=0xff) => true,
            _ => false,
        }
    }

    pub(super) fn async_arrow_ahead(&self) -> Option<ArrowHead> {
        let TokenKind::Identifier(identifier) = &self.current().kind else {
            return None;
        };
        if !self.is_unescaped_name(identifier, "async") {
            return None;
        }
        let mut lexer = self.lexer.clone();
        lexer.seek(self.current().span.end);
        let Ok(parameter) = self.probe_token(&mut lexer, LexicalGoal::Div) else {
            return None;
        };
        if parameter.line_terminator_before {
            return None;
        }
        match parameter.kind {
            TokenKind::Identifier(identifier) if !identifier.escaped_reserved_word => {
                let Ok(arrow) = self.probe_token(&mut lexer, LexicalGoal::Div) else {
                    return None;
                };
                (!arrow.line_terminator_before
                    && matches!(arrow.kind, TokenKind::Punctuator(Punctuator::Arrow)))
                .then_some(ArrowHead::Identifier)
            }
            TokenKind::Punctuator(Punctuator::LeftParen) => self
                .parenthesized_arrow_ahead(parameter.span)
                .then_some(ArrowHead::Parenthesized),
            _ => None,
        }
    }
}