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
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
//! Runtime-independent compilation products.
pub mod metadata;
use crate::engine::code::bytecode::Instruction;
use crate::engine::code::debug::Pc2LineTable;

use crate::engine::value::{JsString, PrimitiveValue};
use oxide_regexp::CompiledRegExp;

use metadata::*;
use std::{error::Error, fmt, rc::Rc};

/// Why a value cannot enter a runtime-independent constant pool draft.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UnlinkedConstantError {
    /// A template site must contain one or more aligned cooked/raw segments.
    InvalidTemplateObject,
}

impl fmt::Display for UnlinkedConstantError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidTemplateObject => formatter.write_str(
                "a template object requires equal non-empty cooked and raw segment lists",
            ),
        }
    }
}

impl Error for UnlinkedConstantError {}

/// Private representation keeps runtime independence structural.
///
/// Making the enum itself crate-visible would let any module construct
/// `Primitive(PrimitiveValue::Object(_))` and bypass the checked constructor.
#[derive(Debug)]
enum UnlinkedConstantKind {
    Primitive(PrimitiveValue),
    /// Source String lowered through QuickJS `emit_push_const(..., as_atom=1)`.
    /// The register lowering interns it into the runtime's atom table, as it
    /// does every string constant not spelling an integer index.
    AtomString(PrimitiveValue),
    /// Runtime-independent RegExp literal source and its compile-once matcher
    /// program. Both payloads are reference-counted leaves with no heap or
    /// atom identity, so the draft can be lowered into any runtime.
    RegExp {
        pattern: JsString,
        program: Rc<CompiledRegExp>,
    },
    /// Runtime-independent template-site data. The register lowering replaces
    /// this pair with the runtime's template object: a frozen cooked Array whose
    /// `raw` property points at the corresponding frozen raw Array.
    TemplateObject {
        cooked: Box<[Option<JsString>]>,
        raw: Box<[JsString]>,
    },
    Child(Box<UnlinkedFunction>),
}

/// One constant in a compiler draft, before the register lowering.
///
/// Primitive constants may contain undefined, null, booleans, numbers,
/// BigInts, and strings. RegExp constants own only pure-Rust String/Rc leaves.
/// Symbols are ECMAScript primitives but runtime-owned atom identities, so a
/// draft has no symbol constant.
#[derive(Debug)]
pub struct UnlinkedConstant(UnlinkedConstantKind);

impl UnlinkedConstant {
    /// Construct a runtime-independent primitive constant.
    ///
    /// # Errors
    ///
    /// Rejects object and symbol roots so an unlinked function cannot retain or
    /// combine runtime domains.
    pub fn primitive<T: TryInto<PrimitiveValue>>(value: T) -> Result<Self, UnlinkedConstantError>
    where
        UnlinkedConstantError: From<T::Error>,
    {
        let primitive = value.try_into().map_err(UnlinkedConstantError::from)?;
        Ok(Self(UnlinkedConstantKind::Primitive(primitive)))
    }

    /// Mark one compiler-produced String value for runtime atom
    /// canonicalization. Keeping this distinct from an ordinary primitive
    /// constant preserves QuickJS's non-atom constant-pool paths.
    #[must_use]
    pub fn atom_string(value: crate::engine::value::JsString) -> Self {
        Self(UnlinkedConstantKind::AtomString(PrimitiveValue::String(
            value,
        )))
    }

    /// Store one compile-once RegExp literal payload.
    #[must_use]
    pub fn regexp(pattern: JsString, program: Rc<CompiledRegExp>) -> Self {
        Self(UnlinkedConstantKind::RegExp { pattern, program })
    }

    /// Store one checked runtime-independent template-site payload.
    pub fn template_object(
        cooked: Vec<Option<JsString>>,
        raw: Vec<JsString>,
    ) -> Result<Self, UnlinkedConstantError> {
        if cooked.is_empty() || cooked.len() != raw.len() {
            return Err(UnlinkedConstantError::InvalidTemplateObject);
        }
        Ok(Self(UnlinkedConstantKind::TemplateObject {
            cooked: cooked.into_boxed_slice(),
            raw: raw.into_boxed_slice(),
        }))
    }

    /// Store one recursively compiled child-function draft.
    #[must_use]
    pub fn child(function: UnlinkedFunction) -> Self {
        Self(UnlinkedConstantKind::Child(Box::new(function)))
    }

    /// Borrow the primitive value, or return `None` for another constant kind.
    #[must_use]
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn as_primitive(&self) -> Option<&PrimitiveValue> {
        match &self.0 {
            UnlinkedConstantKind::Primitive(value) | UnlinkedConstantKind::AtomString(value) => {
                Some(value)
            }
            UnlinkedConstantKind::RegExp { .. }
            | UnlinkedConstantKind::TemplateObject { .. }
            | UnlinkedConstantKind::Child(_) => None,
        }
    }

    /// Borrow a RegExp literal payload, or return `None` for other constants.
    #[must_use]
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn as_regexp(&self) -> Option<(&JsString, &Rc<CompiledRegExp>)> {
        match &self.0 {
            UnlinkedConstantKind::RegExp { pattern, program } => Some((pattern, program)),
            UnlinkedConstantKind::Primitive(_)
            | UnlinkedConstantKind::AtomString(_)
            | UnlinkedConstantKind::TemplateObject { .. }
            | UnlinkedConstantKind::Child(_) => None,
        }
    }

    /// Borrow a template-site payload, or return `None` for other constants.
    #[must_use]
    pub fn as_template_object(&self) -> Option<(&[Option<JsString>], &[JsString])> {
        match &self.0 {
            UnlinkedConstantKind::TemplateObject { cooked, raw } => Some((cooked, raw)),
            _ => None,
        }
    }

    /// Borrow the child draft, or return `None` for another constant kind.
    #[must_use]
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn as_child(&self) -> Option<&UnlinkedFunction> {
        match &self.0 {
            UnlinkedConstantKind::Primitive(_)
            | UnlinkedConstantKind::AtomString(_)
            | UnlinkedConstantKind::RegExp { .. }
            | UnlinkedConstantKind::TemplateObject { .. } => None,
            UnlinkedConstantKind::Child(function) => Some(function),
        }
    }
}

impl TryFrom<PrimitiveValue> for UnlinkedConstant {
    type Error = UnlinkedConstantError;

    fn try_from(value: PrimitiveValue) -> Result<Self, Self::Error> {
        Self::primitive(value)
    }
}

/// Mutable compiler output which has not entered a runtime domain yet.
///
/// The draft owns its vectors, but its fields stay private. The register
/// lowering (`compiler::register`) reads it through the accessors, lowers its
/// child functions first, interns the atoms it needs into the runtime, and
/// publishes each lowered unit into the runtime's code store, which validates
/// it. The lowering checks the stack code's operand-stack flow as it goes.
/// Published code therefore has no mutation path back to this draft.
#[derive(Debug)]
pub struct UnlinkedFunction {
    code: Vec<Instruction>,
    constants: Vec<UnlinkedConstant>,
    metadata: FunctionMetadata,
    parameter_environment: Option<ParameterEnvironmentLayout>,
    func_name: Option<crate::engine::value::JsString>,
    argument_definitions: Vec<UnlinkedVariableDefinition>,
    local_definitions: Vec<UnlinkedVariableDefinition>,
    closure_variables: Vec<ClosureVariable>,
    eval_environments: Vec<EvalEnvironment<JsString>>,
    debug: Option<UnlinkedFunctionDebug>,
}

/// Runtime-independent form of QuickJS's `JSVarDef`/argument metadata.
///
/// Names remain optional because synthetic locals do not have an observable
/// identifier. The register lowering interns a name where the lowered code
/// needs it as a property key.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UnlinkedVariableDefinition {
    pub name: Option<crate::engine::value::JsString>,
    pub is_lexical: bool,
    pub is_const: bool,
    /// The lexical binding belongs to a nested scope evaluated wholly before
    /// the formal-parameter/body boundary.  Parameter-environment cells use
    /// their dedicated layout and leave this flag clear.
    pub is_parameter_initializer: bool,
    pub kind: ClosureVariableKind,
}

impl UnlinkedVariableDefinition {
    /// Construct an ordinary mutable argument/local definition.
    #[must_use]
    pub const fn ordinary(name: Option<crate::engine::value::JsString>) -> Self {
        Self {
            name,
            is_lexical: false,
            is_const: false,
            is_parameter_initializer: false,
            kind: ClosureVariableKind::Normal,
        }
    }

    /// Construct a block-scoped mutable or immutable definition.
    #[must_use]
    pub const fn lexical(name: Option<crate::engine::value::JsString>, is_const: bool) -> Self {
        Self {
            name,
            is_lexical: true,
            is_const,
            is_parameter_initializer: false,
            kind: ClosureVariableKind::Normal,
        }
    }

    /// Retain compiler-authored parameter-initializer scope provenance for the
    /// register lowering.
    #[must_use]
    pub const fn with_parameter_initializer(mut self, value: bool) -> Self {
        self.is_parameter_initializer = value;
        self
    }

    fn function_name(name: Option<crate::engine::value::JsString>, is_const: bool) -> Self {
        Self {
            name,
            is_lexical: false,
            is_const,
            is_parameter_initializer: false,
            kind: ClosureVariableKind::FunctionName,
        }
    }

    fn arg_eval_variable_object() -> Self {
        Self {
            name: Some(crate::engine::value::JsString::from_static("<arg_var>")),
            is_lexical: false,
            is_const: false,
            is_parameter_initializer: false,
            kind: ClosureVariableKind::ArgEvalVariableObject,
        }
    }

    pub fn with_object() -> Self {
        Self {
            name: Some(crate::engine::value::JsString::from_static("<with>")),
            is_lexical: false,
            is_const: false,
            is_parameter_initializer: false,
            kind: ClosureVariableKind::WithObject,
        }
    }
}

/// Runtime-independent debug payload produced by the compiler.
///
/// The register lowering copies the filename into every lowered function.
/// Function source is an independent byte copy so a nested closure does not
/// retain its complete enclosing script.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UnlinkedFunctionDebug {
    pub filename: crate::engine::value::JsString,
    pub pc2line: Option<Pc2LineTable>,
    pub source: Option<Box<[u8]>>,
}

impl UnlinkedFunction {
    /// Assemble a compiler draft with producer-authored binding definitions.
    /// The register lowering lays out the function's registers and captures
    /// from them.
    #[must_use]
    pub fn new(
        code: Vec<Instruction>,
        constants: Vec<UnlinkedConstant>,
        metadata: FunctionMetadata,
        argument_definitions: Vec<UnlinkedVariableDefinition>,
        local_definitions: Vec<UnlinkedVariableDefinition>,
        closure_variables: Vec<ClosureVariable>,
    ) -> Self {
        Self {
            code,
            constants,
            metadata,
            parameter_environment: None,
            func_name: None,
            argument_definitions,
            local_definitions,
            closure_variables,
            eval_environments: Vec::new(),
            debug: None,
        }
    }

    /// Attach the compiler-produced lexical-environment descriptors used by
    /// syntactic direct-eval instructions in this function.
    #[must_use]
    pub fn with_eval_environments(
        mut self,
        eval_environments: Vec<EvalEnvironment<JsString>>,
    ) -> Self {
        self.eval_environments = eval_environments;
        self
    }

    /// Attach the exact parentless parameter-scope ABI. An empty layout is
    /// retained rather than folded into `None` because environment existence
    /// is observable independently from authored BoundName count.
    #[must_use]
    pub fn with_parameter_environment(
        mut self,
        layout: Option<ParameterEnvironmentLayout>,
    ) -> Self {
        self.parameter_environment = layout;
        if let Some(index) = self
            .parameter_environment
            .as_ref()
            .and_then(|layout| layout.arg_eval_variable_object_local)
            && let Some(definition) = self.local_definitions.get_mut(usize::from(index))
        {
            *definition = UnlinkedVariableDefinition::arg_eval_variable_object();
        }
        self
    }

    /// Attach the source-level intrinsic name of a function expression.
    #[must_use]
    pub fn with_name(mut self, name: Option<crate::engine::value::JsString>) -> Self {
        self.func_name = name.clone();
        if let Some(index) = self.metadata.function_name_local
            && let Some(definition) = self.local_definitions.get_mut(usize::from(index))
        {
            *definition = UnlinkedVariableDefinition::function_name(name, self.metadata.strict);
        }
        self
    }

    /// Attach compiler-produced source metadata before lowering.
    #[must_use]
    pub fn with_debug(mut self, debug: UnlinkedFunctionDebug) -> Self {
        self.debug = Some(debug);
        self
    }

    #[must_use]
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn code(&self) -> &[Instruction] {
        &self.code
    }

    #[must_use]
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn constants(&self) -> &[UnlinkedConstant] {
        &self.constants
    }

    #[must_use]
    #[cfg_attr(not(test), allow(dead_code))]
    pub const fn metadata(&self) -> &FunctionMetadata {
        &self.metadata
    }

    #[must_use]
    #[cfg_attr(not(test), allow(dead_code))]
    pub const fn parameter_environment(&self) -> Option<&ParameterEnvironmentLayout> {
        self.parameter_environment.as_ref()
    }

    #[must_use]
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn func_name(&self) -> Option<&crate::engine::value::JsString> {
        self.func_name.as_ref()
    }

    #[must_use]
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn closure_variables(&self) -> &[ClosureVariable] {
        &self.closure_variables
    }

    #[must_use]
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn argument_definitions(&self) -> &[UnlinkedVariableDefinition] {
        &self.argument_definitions
    }

    #[must_use]
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn local_definitions(&self) -> &[UnlinkedVariableDefinition] {
        &self.local_definitions
    }

    #[must_use]
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn eval_environments(&self) -> &[EvalEnvironment<JsString>] {
        &self.eval_environments
    }

    /// Moves every function's source text out of the tree, children before
    /// their parent: the order the register lowering publishes units in.
    pub(crate) fn take_sources(&mut self, sources: &mut Vec<Option<Box<[u8]>>>) {
        for constant in &mut self.constants {
            if let UnlinkedConstantKind::Child(child) = &mut constant.0 {
                child.take_sources(sources);
            }
        }
        sources.push(self.debug.as_mut().and_then(|debug| debug.source.take()));
    }

    #[cfg_attr(not(test), allow(dead_code))]
    #[must_use]
    pub const fn debug(&self) -> Option<&UnlinkedFunctionDebug> {
        self.debug.as_ref()
    }
}

impl From<std::convert::Infallible> for UnlinkedConstantError {
    fn from(value: std::convert::Infallible) -> Self {
        match value {}
    }
}