quickjs-oxide 0.4.1

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
//! QuickJS-shaped private field, method, and accessor declaration
//! lowering.
//!
//! Each `#name` owns a lexical cell in the class body's dedicated private-name
//! scope. Data fields initialize that cell with a fresh private identity;
//! methods initialize it with the callable whose HomeObject carries the class
//! side's brand. Aggregate initializer children install the corresponding
//! brand or consume field identities through `DefinePrivateField`.

use crate::engine::api::error::Error;
use crate::engine::api::error::ErrorKind;
use crate::engine::code::bytecode::Instruction;
use crate::engine::compiler::MAX_LOCAL_VARIABLES;
use crate::engine::compiler::lexer::Punctuator;
use crate::engine::compiler::lexer::Span;
use crate::engine::compiler::model::bindings::BindingKind;
use crate::engine::compiler::model::bindings::BindingStorage;
use crate::engine::compiler::model::ir::IrConstant;
use crate::engine::compiler::model::ir::PrivateFieldAccess;
use crate::engine::compiler::model::scope::ScopeKind;
use crate::engine::compiler::names::NameId;
use crate::engine::compiler::parser::context::Parser;
use crate::engine::compiler::parser::diagnostics::source_offset;
use crate::engine::compiler::private_reference;
use crate::engine::value::JsString;
use crate::engine::value::PrimitiveValue as Value;

use super::{ClassElementState, ClassMethodFlavor};
use crate::engine::code::bytecode::DefineMethodKind;

impl<'source> Parser<'source> {
    fn register_private_binding(
        &mut self,
        name: NameId,
        span: Span,
        kind: BindingKind,
    ) -> Result<u16, Error> {
        let scope = self.current_ir().context.current_scope;
        if self
            .current_ir()
            .scopes
            .get(scope.index())
            .is_none_or(|scope| scope.kind != ScopeKind::ClassPrivate)
        {
            return Err(Error::internal(
                "private field declaration escaped the class-private scope",
            ));
        }
        if self.current_ir().binding_id_in_scope(scope, name).is_some() {
            return Err(self.syntax_here("private class field is already defined"));
        }
        let function = self.current_ir_mut();
        if function.locals.len() >= MAX_LOCAL_VARIABLES {
            return Err(
                Error::new(ErrorKind::JsInternal, "too many local variables").with_span(span),
            );
        }
        let local = u16::try_from(function.locals.len())
            .map_err(|_| Error::new(ErrorKind::JsInternal, "too many local variables"))?;
        function.locals.push(name);
        function.add_binding(
            scope,
            scope,
            name,
            BindingStorage::Local(local),
            kind,
            Some(span),
        );
        Ok(local)
    }

    /// Preflight and register or pair the source-visible private accessor
    /// binding. QuickJS performs this primary-name step before parsing the
    /// accessor function, but reserves a setter's synthetic `<set>` storage
    /// only after the complete parameter list and body have been accepted.
    fn register_private_accessor_primary(
        &mut self,
        name: NameId,
        span: Span,
        is_static: bool,
        method_kind: DefineMethodKind,
    ) -> Result<u16, Error> {
        let incoming = match method_kind {
            DefineMethodKind::Getter => BindingKind::PrivateGetter { is_static },
            DefineMethodKind::Setter => BindingKind::PrivateSetter { is_static },
            DefineMethodKind::Method => {
                return Err(Error::internal(
                    "ordinary private method reached accessor registration",
                ));
            }
        };
        let scope = self.current_ir().context.current_scope;
        let existing = self.current_ir().binding_id_in_scope(scope, name);

        let primary_local = if let Some(binding_id) = existing {
            let (existing_kind, storage) = {
                let binding = self
                    .current_ir()
                    .bindings
                    .get(binding_id.0)
                    .ok_or_else(|| Error::internal("private accessor binding disappeared"))?;
                (binding.kind, binding.storage)
            };
            let pairable = matches!(
                (existing_kind, incoming),
                (
                    BindingKind::PrivateGetter {
                        is_static: existing_static
                    },
                    BindingKind::PrivateSetter {
                        is_static: incoming_static
                    }
                ) | (
                    BindingKind::PrivateSetter {
                        is_static: existing_static
                    },
                    BindingKind::PrivateGetter {
                        is_static: incoming_static
                    }
                ) if existing_static == incoming_static
            );
            if !pairable {
                return Err(self.syntax_here("private class field is already defined"));
            }
            self.current_ir_mut().bindings[binding_id.0].kind =
                BindingKind::PrivateGetterSetter { is_static };
            match storage {
                BindingStorage::Local(local) => local,
                BindingStorage::Argument(_)
                | BindingStorage::External(_)
                | BindingStorage::Module(_)
                | BindingStorage::Global => {
                    return Err(Error::internal(
                        "private accessor primary binding has invalid storage",
                    ));
                }
            }
        } else {
            self.register_private_binding(name, span, incoming)?
        };
        Ok(primary_local)
    }

    fn register_private_setter_storage(
        &mut self,
        name: NameId,
        span: Span,
        is_static: bool,
    ) -> Result<u16, Error> {
        let setter_name = private_reference::private_setter_binding_name(&mut self.names, name);
        self.register_private_binding(setter_name, span, BindingKind::PrivateSetter { is_static })
    }

    pub(super) fn parse_private_class_field(
        &mut self,
        elements: &mut ClassElementState,
        is_static: bool,
        name: NameId,
        span: Span,
    ) -> Result<(), Error> {
        if self.names.name(name) == "#constructor" {
            return Err(self.syntax_here("invalid method name"));
        }

        let local =
            self.register_private_binding(name, span, BindingKind::PrivateField { is_static })?;
        // Unlike a normal lexical initializer, this opcode allocates and stores
        // the private Atom without ever constructing a public Symbol Value.
        self.emit_instruction_at(
            Instruction::InitializePrivateName(local),
            source_offset(span)?,
        )?;

        let child = self.ensure_class_initializer(elements, is_static, span)?;
        let parent = self.enter_class_field_initializer(child);
        self.emit_instruction(Instruction::PushThis)?;

        if self.consume_punctuator(Punctuator::Equal)? {
            self.parse_assignment()?;
        } else {
            self.emit_instruction(Instruction::Undefined)?;
            self.anonymous_function_definition = None;
        }

        if let Some(definition) = self.take_anonymous_function_definition() {
            let js_name = JsString::try_from_utf8(self.names.name(name))?;
            let name_constant = self.add_constant(IrConstant::Primitive(Value::String(js_name)))?;
            self.emit_anonymous_set_name(definition, Instruction::SetName(name_constant))?;
        }
        let scope = self.current_ir().context.current_scope;
        self.emit_private_field_operation(
            name,
            span,
            scope,
            PrivateFieldAccess::Define,
            source_offset(span)?,
        )?;
        self.emit_instruction(Instruction::Drop)?;
        self.leave_class_field_initializer(parent);
        self.anonymous_function_definition = None;
        self.consume_statement_terminator()
    }

    /// Parse and publish an ordinary, async, generator, or async-generator
    /// private method.
    /// The body is parsed before the namespace binding is registered, matching
    /// QuickJS's diagnostic priority when a malformed body and a duplicate
    /// private spelling coexist.
    pub(super) fn parse_private_class_method(
        &mut self,
        elements: &mut ClassElementState,
        is_static: bool,
        name: NameId,
        span: Span,
        function_span: Span,
        flavor: ClassMethodFlavor,
    ) -> Result<(), Error> {
        if self.names.name(name) == "#constructor" {
            return Err(self.syntax_here("invalid method name"));
        }

        let method = match flavor {
            ClassMethodFlavor::Ordinary => {
                self.parse_object_method_definition(function_span, DefineMethodKind::Method)?
            }
            ClassMethodFlavor::Generator => {
                self.parse_generator_method_definition(function_span)?
            }
            ClassMethodFlavor::Async => self.parse_async_method_definition(function_span)?,
            ClassMethodFlavor::AsyncGenerator => {
                self.parse_async_generator_method_definition(function_span)?
            }
        };
        // A private method needs HomeObject even when its authored body never
        // mentions `super`: the runtime derives its unforgeable brand from the
        // callable's HomeObject, as pinned QuickJS does.
        self.functions[method].needs_home_object = true;

        let local =
            self.register_private_binding(name, span, BindingKind::PrivateMethod { is_static })?;
        let initializer = self.ensure_class_initializer(elements, is_static, span)?;
        self.functions[initializer].class_private_brand = true;

        // The surrounding class stack already holds the relevant HomeObject
        // immediately below the method closure. Initialization consumes the
        // closure, preserves that HomeObject, and stores a typed callable cell.
        self.emit_instruction_at(
            Instruction::InitializePrivateMethod(local),
            source_offset(span)?,
        )?;
        self.anonymous_function_definition = None;
        Ok(())
    }

    /// Parse and publish a private getter or setter. QuickJS performs the
    /// private-namespace duplicate/pairing check before parsing the accessor's
    /// parameters and body, so a conflicting spelling wins over any malformed
    /// function syntax. No `SetName` is emitted: pinned QuickJS leaves both
    /// private accessor function names as the empty string.
    pub(super) fn parse_private_class_accessor(
        &mut self,
        elements: &mut ClassElementState,
        is_static: bool,
        name: NameId,
        span: Span,
        function_span: Span,
        method_kind: DefineMethodKind,
    ) -> Result<(), Error> {
        if self.names.name(name) == "#constructor" {
            return Err(self.syntax_here("invalid method name"));
        }
        if method_kind == DefineMethodKind::Method {
            return Err(Error::internal(
                "ordinary private method reached accessor lowering",
            ));
        }

        let primary = self.register_private_accessor_primary(name, span, is_static, method_kind)?;
        let accessor = self.parse_object_method_definition(function_span, method_kind)?;
        // Brand checks recover the private side's HomeObject from the callable
        // even when the body itself never evaluates `super`.
        self.functions[accessor].needs_home_object = true;

        let local = if method_kind == DefineMethodKind::Setter {
            self.register_private_setter_storage(name, span, is_static)?
        } else {
            primary
        };

        let initializer = self.ensure_class_initializer(elements, is_static, span)?;
        self.functions[initializer].class_private_brand = true;
        self.emit_instruction_at(
            Instruction::InitializePrivateAccessor(local),
            source_offset(span)?,
        )?;
        self.anonymous_function_definition = None;
        Ok(())
    }
}

#[cfg(test)]
mod tests {

    use crate::engine::compiler::lexer::Lexer;

    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::SuperCapabilities;

    use crate::engine::compiler::names::NameTable;
    use crate::engine::compiler::parser::builder::FunctionBuilder;
    use crate::engine::compiler::parser::context::InMode;
    use crate::engine::compiler::parser::context::ModuleDeclarationExport;

    use crate::source::SourceOffset;

    use super::*;

    fn private_accessor_parser(source: &str) -> Parser<'_> {
        let mut lexer = Lexer::new(source);
        let first_token = lexer.next_token().unwrap();
        let source_span = first_token.span;
        let mut names = NameTable::new();
        let root = FunctionBuilder::new(
            None,
            FunctionKind::Script,
            FunctionSourceInfo {
                span: source_span,
                definition: SourceOffset::try_from_usize(0).unwrap(),
                range: None,
            },
            FunctionIrOptions {
                function_name: Some(names.intern("<private-accessor-order-test>")),
                private_name_binding: false,
                class_constructor: false,
                derived_class_constructor: false,
                parameters: Vec::new(),
                defined_argument_count: 0,
                has_simple_parameter_list: true,
                rest_parameter: None,
                strict: true,
                super_capabilities: SuperCapabilities::NONE,
            },
            &mut names,
        )
        .unwrap();
        let mut parser = Parser {
            token_context: (
                lexer.context(),
                crate::engine::compiler::lexer::LexicalGoal::Div,
            ),
            lexer,
            token: first_token,
            previous_end: None,
            current_function: 0,
            in_mode: InMode::Allow,
            functions: vec![root],
            names,
            module: None,
            module_declaration_export: ModuleDeclarationExport::None,
            module_declaration_export_target: None,
            anonymous_function_definition: None,
            pending_unsupported: None,
            lookahead: Default::default(),
            stack_guard: crate::engine::compiler::stack_guard::ParserStackGuard::new(),
        };
        parser.push_scope(ScopeKind::ClassPrivate);
        parser
    }

    #[test]
    fn malformed_setter_does_not_reserve_synthetic_storage_before_body_parse() {
        let mut parser = private_accessor_parser("(...rest) {}");
        let padding = parser.names.intern("<padding>");
        parser.functions[0]
            .locals
            .resize(MAX_LOCAL_VARIABLES - 1, padding);
        let span = parser.current().span;
        let mut elements = ClassElementState::default();

        let value = parser.names.intern("#value");
        let error = parser
            .parse_private_class_accessor(
                &mut elements,
                false,
                value,
                span,
                span,
                DefineMethodKind::Setter,
            )
            .unwrap_err();
        assert_eq!(
            error.message(),
            "invalid number of arguments for getter or setter"
        );

        let root = &parser.functions[0];
        assert_eq!(root.locals.len(), MAX_LOCAL_VARIABLES);
        assert!(
            root.binding_id_in_scope(root.context.current_scope, value)
                .is_some()
        );
        assert!(
            root.binding_id_in_scope(
                root.context.current_scope,
                parser.names.intern("#value<set>")
            )
            .is_none()
        );
    }
}