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
//! Own the single IR allocation during parsing and consume temporary state at finish.
use crate::engine::compiler::model::ir::function::FunctionIr;
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::names::NameId;
use crate::engine::compiler::names::NameTable;

use super::context::FunctionParseContext;
use crate::engine::api::error::Error;

use std::ops::{Deref, DerefMut};

#[derive(Debug)]
pub(in crate::engine::compiler) struct FunctionBuilder {
    pub(in crate::engine::compiler) ir: Box<FunctionIr>,
    pub(in crate::engine::compiler) context: ParseContextStorage,
}

impl FunctionBuilder {
    pub(in crate::engine::compiler) fn new(
        parent: Option<ParentLink>,
        kind: FunctionKind,
        source: FunctionSourceInfo,
        options: FunctionIrOptions,
        names: &mut NameTable,
    ) -> Result<Self, Error> {
        let ir = FunctionIr::new(parent, kind, source, options, names)?;
        let context = FunctionParseContext::new(ir.body_scope);
        Ok(Self {
            ir: Box::new(ir),
            context: ParseContextStorage(Some(Box::new(context))),
        })
    }

    /// Release construction-only state as soon as an ordinary/arrow body is
    /// complete. Class aggregate initializers retain it while suspended.
    pub(in crate::engine::compiler) fn finish_parsing(&mut self) -> Result<(), Error> {
        let Some(context) = self.context.0.take() else {
            return Ok(());
        };
        if context.current_scope != self.ir.body_scope {
            return Err(Error::internal("function scope roots are malformed"));
        }
        if !context.break_controls.is_empty() {
            return Err(Error::internal("function parser controls are not closed"));
        }
        self.ir.body_parsed = context.in_function_body;
        self.ir.release_growth();
        Ok(())
    }

    /// Transfer the same IR allocation; arena growth and final collection move
    /// pointers instead of the wide function record.
    pub(in crate::engine::compiler) fn finish(mut self) -> Result<Box<FunctionIr>, Error> {
        self.finish_parsing()?;
        Ok(self.ir)
    }
}

#[derive(Debug)]
pub(in crate::engine::compiler) struct ParseContextStorage(Option<Box<FunctionParseContext>>);

impl Deref for ParseContextStorage {
    type Target = FunctionParseContext;
    fn deref(&self) -> &Self::Target {
        self.0.as_deref().expect("function is still being parsed")
    }
}
impl DerefMut for ParseContextStorage {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.0
            .as_deref_mut()
            .expect("function is still being parsed")
    }
}

// Construction algorithms share the same IR, while parser state is always
// explicit through `context`. These borrows cannot outlive the builder.
impl Deref for FunctionBuilder {
    type Target = FunctionIr;
    fn deref(&self) -> &FunctionIr {
        &self.ir
    }
}
impl DerefMut for FunctionBuilder {
    fn deref_mut(&mut self) -> &mut FunctionIr {
        &mut self.ir
    }
}

use crate::engine::api::error::ErrorKind;
use crate::engine::code::bytecode::Instruction;
use crate::engine::compiler::lexer::Span;
use crate::engine::compiler::model::ir::IdentifierAccess;
use crate::engine::compiler::model::ir::IdentifierReferenceAccess;
use crate::engine::compiler::model::ir::IrConstant;
use crate::engine::compiler::model::ir::IrOp;
use crate::engine::compiler::model::ir::SpannedIrOp;
use crate::engine::compiler::model::scope::ScopeId;
use crate::engine::compiler::parser::context::AnonymousFunctionDefinition;
use crate::engine::compiler::parser::context::Parser;
use crate::engine::compiler::parser::diagnostics::source_offset;
use crate::engine::compiler::relocation::insert_hoist_fragment;
use crate::engine::value::JsString;
use crate::engine::value::PrimitiveValue as Value;
use crate::source::SourceOffset;

impl<'source> Parser<'source> {
    pub(in crate::engine::compiler) fn emit_value(&mut self, value: Value) -> Result<(), Error> {
        self.emit_value_with_site(value, None)
    }

    pub(in crate::engine::compiler) fn emit_atom_string(
        &mut self,
        value: JsString,
    ) -> Result<(), Error> {
        let index = self.add_constant(IrConstant::AtomString(value))?;
        self.emit(IrOp::PushConstant(index)).map(|_| ())
    }

    pub(in crate::engine::compiler) fn emit_value_with_site(
        &mut self,
        value: Value,
        site: Option<SourceOffset>,
    ) -> Result<(), Error> {
        if let Value::Int(value) = value {
            return self
                .emit_with_site(IrOp::Bytecode(Instruction::PushI32(value)), site)
                .map(|_| ());
        }
        let index = self.add_constant(IrConstant::Primitive(value))?;
        self.emit_with_site(IrOp::PushConstant(index), site)
            .map(|_| ())
    }

    pub(in crate::engine::compiler) fn add_constant(
        &mut self,
        constant: IrConstant,
    ) -> Result<u32, Error> {
        self.current_ir_mut().append_constant(constant)
    }

    pub(in crate::engine::compiler) fn emit_instruction(
        &mut self,
        instruction: Instruction,
    ) -> Result<usize, Error> {
        self.emit(IrOp::Bytecode(instruction))
    }

    pub(in crate::engine::compiler) fn take_anonymous_function_definition(
        &mut self,
    ) -> Option<AnonymousFunctionDefinition> {
        self.anonymous_function_definition.take()
    }

    pub(in crate::engine::compiler) fn emit_anonymous_set_name(
        &mut self,
        definition: AnonymousFunctionDefinition,
        instruction: Instruction,
    ) -> Result<usize, Error> {
        if !matches!(
            instruction,
            Instruction::SetName(_) | Instruction::SetNameComputed
        ) {
            return Err(Error::internal(
                "anonymous definition received a non-naming instruction",
            ));
        }
        match definition {
            AnonymousFunctionDefinition::Function => self.emit_instruction(instruction),
            AnonymousFunctionDefinition::Class {
                owner,
                static_initializer_start: Some(at),
            } => {
                if owner != self.current_function {
                    return Err(Error::internal(
                        "anonymous class static initializer changed defining function",
                    ));
                }
                insert_hoist_fragment(
                    self.current_ir_mut(),
                    at,
                    vec![SpannedIrOp {
                        op: IrOp::Bytecode(instruction),
                        pc_site: None,
                    }],
                )?;
                Ok(at)
            }
            AnonymousFunctionDefinition::Class {
                static_initializer_start: None,
                ..
            } => self.emit_instruction(instruction),
        }
    }

    pub(in crate::engine::compiler) fn emit_instruction_at(
        &mut self,
        instruction: Instruction,
        site: SourceOffset,
    ) -> Result<usize, Error> {
        self.emit_at(IrOp::Bytecode(instruction), site)
    }

    pub(in crate::engine::compiler) fn emit_identifier(
        &mut self,
        name: NameId,
        span: Span,
        access: IdentifierAccess,
    ) -> Result<usize, Error> {
        self.emit_identifier_at(name, span, access, source_offset(span)?)
    }

    pub(in crate::engine::compiler) fn emit_identifier_at(
        &mut self,
        name: NameId,
        span: Span,
        access: IdentifierAccess,
        pc_site: SourceOffset,
    ) -> Result<usize, Error> {
        let scope = self.current_ir().context.current_scope;
        let span = self.current_ir_mut().operands.add_span(span)?;
        self.emit_at(
            IrOp::Identifier {
                name,
                span,
                scope,
                access,
            },
            pc_site,
        )
    }

    pub(in crate::engine::compiler) fn emit_identifier_inherited(
        &mut self,
        name: NameId,
        span: Span,
        scope: ScopeId,
        access: IdentifierAccess,
    ) -> Result<usize, Error> {
        let span = self.current_ir_mut().operands.add_span(span)?;
        self.emit(IrOp::Identifier {
            name,
            span,
            scope,
            access,
        })
    }

    pub(in crate::engine::compiler) fn emit_identifier_reference_inherited(
        &mut self,
        name: NameId,
        span: Span,
        scope: ScopeId,
        access: IdentifierReferenceAccess,
    ) -> Result<usize, Error> {
        let span = self.current_ir_mut().operands.add_span(span)?;
        self.emit(IrOp::IdentifierReference {
            name,
            span,
            scope,
            access,
        })
    }

    /// Materialize an `emit_source_pos` which appeared before an expression's
    /// first real opcode. If the RHS emitted its own marker before that same
    /// opcode, QuickJS's later `OP_line_num` wins and the pending marker is
    /// intentionally discarded.
    pub(in crate::engine::compiler) fn inherit_source_marker_at(
        &mut self,
        first_operation: usize,
        marker: SourceOffset,
    ) -> Result<(), Error> {
        let operation = self
            .current_ir_mut()
            .ops
            .get_mut(first_operation)
            .ok_or_else(|| Error::internal("assignment RHS emitted no operation"))?;
        if operation.pc_site.is_none() {
            operation.pc_site = Some(marker);
        }
        Ok(())
    }

    pub(in crate::engine::compiler) fn emit(&mut self, operation: IrOp) -> Result<usize, Error> {
        self.emit_with_site(operation, None)
    }

    pub(in crate::engine::compiler) fn emit_at(
        &mut self,
        operation: IrOp,
        site: SourceOffset,
    ) -> Result<usize, Error> {
        self.emit_with_site(operation, Some(site))
    }

    // Let constant opcode callers specialize stack effects instead of paying
    // a second runtime opcode dispatch for every emitted operation.
    #[inline]
    pub(in crate::engine::compiler) fn emit_with_site(
        &mut self,
        operation: IrOp,
        pc_site: Option<SourceOffset>,
    ) -> Result<usize, Error> {
        let (popped, pushed) = operation.stack_effect();
        let function = self.current_ir_mut();
        function.context.last_member_reference = None;
        function.context.last_identifier_reference = None;
        function.context.last_optional_chain = None;
        function.context.stack_depth = function
            .context
            .stack_depth
            .checked_sub(popped)
            .ok_or_else(|| Error::internal("compiler produced a stack underflow"))?;
        function.context.stack_depth = function
            .context
            .stack_depth
            .checked_add(pushed)
            .ok_or_else(|| Error::new(ErrorKind::JsInternal, "stack overflow"))?;
        let index = function.ops.len();
        function.ops.push(SpannedIrOp {
            op: operation,
            pc_site,
        });
        Ok(index)
    }

    pub(in crate::engine::compiler) fn patch_jump(
        &mut self,
        instruction_index: usize,
        target: usize,
    ) -> Result<(), Error> {
        let target = u32::try_from(target)
            .map_err(|_| Error::new(ErrorKind::JsInternal, "out of memory"))?;
        let operation = self
            .current_ir_mut()
            .ops
            .get_mut(instruction_index)
            .ok_or_else(|| Error::internal("missing jump instruction"))?;
        match &mut operation.op {
            IrOp::Bytecode(
                Instruction::IfFalse(value)
                | Instruction::IfTrue(value)
                | Instruction::Goto(value)
                | Instruction::Catch(value)
                | Instruction::Gosub(value),
            ) => {
                *value = target;
                Ok(())
            }
            _ => Err(Error::internal("attempted to patch a non-jump instruction")),
        }
    }

    pub(in crate::engine::compiler) fn current_ir(&self) -> &FunctionBuilder {
        &self.functions[self.current_function]
    }

    pub(in crate::engine::compiler) fn current_ir_mut(&mut self) -> &mut FunctionBuilder {
        &mut self.functions[self.current_function]
    }
}

#[cfg(test)]
mod tests {
    use super::{FunctionBuilder, FunctionParseContext, ParseContextStorage};
    use crate::engine::compiler::model::scope::ScopeId;
    use crate::engine::compiler::parser::context::{BreakControlContext, BreakControlKind, Parser};
    use crate::engine::value::JsString;

    fn parsed_builder() -> FunctionBuilder {
        let mut tree = Parser::parse("0;", JsString::from_static("<finish-contract>")).unwrap();
        let ir = tree.functions.remove(0);
        let context = FunctionParseContext::new(ir.body_scope);
        FunctionBuilder {
            ir,
            context: ParseContextStorage(Some(Box::new(context))),
        }
    }

    #[test]
    fn unfinished_scope_cannot_enter_resolution() {
        let mut builder = parsed_builder();
        builder.context.current_scope = ScopeId(0);
        assert_eq!(
            builder.finish().unwrap_err().message(),
            "function scope roots are malformed"
        );
    }

    #[test]
    fn pending_abrupt_targets_cannot_enter_resolution() {
        let mut builder = parsed_builder();
        builder.context.break_controls.push(BreakControlContext {
            kind: BreakControlKind::Loop,
            label_name: None,
            scope: builder.ir.body_scope,
            entry_depth: 0,
            drop_count: 0,
            break_jumps: vec![0],
            continue_jumps: Vec::new(),
            finally_gosubs: Vec::new(),
        });
        assert_eq!(
            builder.finish().unwrap_err().message(),
            "function parser controls are not closed"
        );
    }
}