Skip to main content

js_compile/
serialize.rs

1//! Serialisation of compiled bytecode.
2//!
3//! The format is our own — it deliberately does not interoperate with the C
4//! implementation's binary blobs — but it keeps the same *semantics*: a compiled
5//! function can be written out and read back without the source, which is what
6//! `qjsc` relies on for ahead-of-time compilation.
7//!
8//! Layout, all integers big-endian:
9//!
10//! ```text
11//! magic    4 bytes  "QJSB"
12//! version  u16      format version
13//! function          one function record, recursively
14//!
15//! function record:
16//!   name        string (u32 length + UTF-8 bytes)
17//!   kind        u8
18//!   flags       u8    bit 0 = strict, bit 1 = arrow
19//!   line, column u32 each
20//!   defined_args u32  arity that counts towards `.length`
21//!   args        u32 count, then name/flags records
22//!   vars        u32 count, then name/flags/scope records
23//!   closures    u32 count, then name/flags/type/index records
24//!   cpool       u32 count, then constants
25//!   code        u32 length + bytes
26//!   stack_size  u32
27//!   var_refs    u32
28//!   positions   u32 count, then pc/line/column u32 each
29//!   filename    optional string (tag u8: 0 none, 1 + string)
30//!   source      optional string, present only when the writer kept it
31//!   module      u8 tag: 0 = a script, 1 = module tables follow
32//!                 requests  u32 count, then specifier + attribute pairs
33//!                 imports   u32 count, then module/var_idx/name/is_star
34//!                 exports   u32 count, then a tagged entry
35//! ```
36//!
37//! The last three are not bytecode. They are what the *host* needs in order to run the
38//! bytecode without the source: the file name a stack frame prints and a module records,
39//! the source text `Function.prototype.toString` reports (dropped unless the writer asks,
40//! which is what `qjsc`'s `--keep-source` is for), and the module tables — data the host
41//! wires imports up from before the body runs.
42//!
43//! A version bump is required for any change to this layout; [`MAGIC`] plus
44//! [`VERSION`] make a stale blob fail loudly instead of being misinterpreted.
45
46use crate::bytecode::{
47    Atom, ClosureType, ClosureVar, Constant, ExportEntry, Function, FunctionKind, ImportEntry,
48    LineCol, ModuleMeta, ModuleRequest, VarDef, VarKind,
49};
50use js_parse::Wtf8;
51use std::fmt;
52
53/// File magic.
54pub const MAGIC: [u8; 4] = *b"QJSB";
55
56/// Format version. Bumped whenever the layout below changes — and *only* then.
57///
58/// A product built by `qjsc` links the **published** `quickjs-pure` unless it is given a
59/// path, so the reader on the other side of this format can be an older release. Bumping
60/// for a change the old reader could still decode makes every such product refuse to load.
61/// (Widening a text field from UTF-8 to WTF-8 is that kind of change: the framing is
62/// unchanged, and only a blob whose literal holds an unpaired surrogate can be rejected by
63/// an old reader.)
64///
65/// 9 added the file name, the optional source text and the module tables. A blob written
66/// by 8 still *loads* its bytecode correctly, but it cannot say which file it came from
67/// or what it imports, so it is rejected rather than half-run.
68pub const VERSION: u16 = 9;
69
70/// Why a blob could not be read.
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub enum DecodeError {
73    /// The magic number is wrong; this is not our bytecode.
74    BadMagic,
75    /// The format version is not one this build understands.
76    BadVersion(u16),
77    /// The blob ends in the middle of a value.
78    Truncated,
79    /// A discriminant is out of range.
80    BadTag(&'static str, u8),
81    /// An atom entry has an unknown kind tag.
82    BadAtomTag(u8),
83}
84
85impl fmt::Display for DecodeError {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        match self {
88            DecodeError::BadMagic => f.write_str("not QuickJS-RS bytecode (bad magic)"),
89            DecodeError::BadVersion(v) => write!(f, "unsupported bytecode version {v}"),
90            DecodeError::Truncated => f.write_str("truncated bytecode"),
91            DecodeError::BadTag(what, tag) => write!(f, "invalid {what} tag {tag}"),
92            DecodeError::BadAtomTag(tag) => write!(f, "invalid atom kind tag {tag}"),
93        }
94    }
95}
96
97impl std::error::Error for DecodeError {}
98
99/// What to keep besides the bytecode.
100#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
101pub struct Options {
102    /// Keep the source text, which is what `Function.prototype.toString` and a stack
103    /// trace's `file:line` context read from. Off by default: `qjsc` strips it unless
104    /// asked (`--keep-source`), and a stripped blob is both smaller and not a copy of the
105    /// original program.
106    pub keep_source: bool,
107}
108
109/// Write a compiled function, including its nested functions, without its source text.
110pub fn serialize(function: &Function) -> Vec<u8> {
111    serialize_with(function, Options::default())
112}
113
114/// [`serialize`], with control over what is kept.
115pub fn serialize_with(function: &Function, options: Options) -> Vec<u8> {
116    let mut out = Vec::new();
117    out.extend_from_slice(&MAGIC);
118    out.extend_from_slice(&VERSION.to_be_bytes());
119    write_function(&mut out, function, options);
120    out
121}
122
123/// Read a compiled function back.
124pub fn deserialize(bytes: &[u8]) -> Result<Function, DecodeError> {
125    let mut reader = Reader { bytes, pos: 0 };
126    if reader.take(4)? != MAGIC {
127        return Err(DecodeError::BadMagic);
128    }
129    let version = u16::from_be_bytes(reader.array::<2>()?);
130    if version != VERSION {
131        return Err(DecodeError::BadVersion(version));
132    }
133    read_function(&mut reader)
134}
135
136/// One atom, tagged by kind so a canonical array index survives the round trip as
137/// a number rather than turning back into its decimal spelling.
138fn write_atom(out: &mut Vec<u8>, atom: &Atom) {
139    match atom {
140        Atom::Str(text) => {
141            out.push(0);
142            write_wtf8(out, text);
143        }
144        Atom::Index(index) => {
145            out.push(1);
146            out.extend_from_slice(&index.to_be_bytes());
147        }
148        Atom::Null => out.push(2),
149    }
150}
151
152fn read_atom(reader: &mut Reader<'_>) -> Result<Atom, DecodeError> {
153    match reader.u8()? {
154        0 => Ok(Atom::Str(reader.wtf8()?)),
155        1 => Ok(Atom::Index(u32::from_be_bytes(reader.array::<4>()?))),
156        2 => Ok(Atom::Null),
157        tag => Err(DecodeError::BadAtomTag(tag)),
158    }
159}
160
161fn write_string(out: &mut Vec<u8>, text: &str) {
162    out.extend_from_slice(&(text.len() as u32).to_be_bytes());
163    out.extend_from_slice(text.as_bytes());
164}
165
166/// A string that may hold an unpaired surrogate, which [`write_string`] already writes
167/// byte-for-byte: WTF-8 is a self-synchronising encoding, so the length prefix is all the
168/// framing it needs.
169fn write_wtf8(out: &mut Vec<u8>, text: &Wtf8) {
170    out.extend_from_slice(&(text.as_bytes().len() as u32).to_be_bytes());
171    out.extend_from_slice(text.as_bytes());
172}
173
174fn write_var(out: &mut Vec<u8>, var: &VarDef) {
175    write_string(out, &var.name);
176    let mut flags = 0u8;
177    if var.is_const {
178        flags |= 1;
179    }
180    if var.is_lexical {
181        flags |= 2;
182    }
183    if var.is_captured {
184        flags |= 4;
185    }
186    out.push(flags);
187    out.push(var_kind_tag(var.kind));
188    out.extend_from_slice(&var.scope_level.to_be_bytes());
189    match var.scope_next {
190        Some(next) => {
191            out.push(1);
192            out.extend_from_slice(&next.to_be_bytes());
193        }
194        None => out.push(0),
195    }
196}
197
198fn write_function(out: &mut Vec<u8>, function: &Function, options: Options) {
199    write_string(out, &function.name);
200    out.push(kind_tag(function.kind));
201    out.push(
202        u8::from(function.strict)
203            | (u8::from(function.is_arrow) << 1)
204            | (u8::from(function.has_parameter_expressions) << 2)
205            | (u8::from(function.simple_parameter_list) << 3)
206            | (u8::from(function.is_derived_constructor) << 4),
207    );
208    out.extend_from_slice(&function.line.to_be_bytes());
209    out.extend_from_slice(&function.column.to_be_bytes());
210    out.extend_from_slice(&function.body_start.0.to_be_bytes());
211    out.extend_from_slice(&function.body_start.1.to_be_bytes());
212
213    out.extend_from_slice(&function.defined_args.to_be_bytes());
214    out.extend_from_slice(&(function.args.len() as u32).to_be_bytes());
215    for arg in &function.args {
216        write_var(out, arg);
217    }
218    out.extend_from_slice(&(function.vars.len() as u32).to_be_bytes());
219    for var in &function.vars {
220        write_var(out, var);
221    }
222
223    out.extend_from_slice(&(function.closure_vars.len() as u32).to_be_bytes());
224    for closure in &function.closure_vars {
225        write_string(out, &closure.name);
226        let mut flags = 0u8;
227        if closure.is_const {
228            flags |= 1;
229        }
230        if closure.is_lexical {
231            flags |= 2;
232        }
233        out.push(flags);
234        out.push(closure_type_tag(closure.closure_type));
235        out.extend_from_slice(&closure.var_idx.to_be_bytes());
236    }
237
238    out.extend_from_slice(&(function.atoms.len() as u32).to_be_bytes());
239    for atom in &function.atoms {
240        write_atom(out, atom);
241    }
242
243    out.extend_from_slice(&(function.cpool.len() as u32).to_be_bytes());
244    for constant in &function.cpool {
245        write_constant(out, constant, options);
246    }
247
248    out.extend_from_slice(&(function.code.len() as u32).to_be_bytes());
249    out.extend_from_slice(&function.code);
250    out.extend_from_slice(&function.stack_size.to_be_bytes());
251    out.extend_from_slice(&function.var_ref_count.to_be_bytes());
252    // The eval-site table travels with the code for the same reason as the position
253    // table: it is what lets a direct `eval` resolve a shadowed name to the right slot,
254    // and it cannot be recomputed from the bytecode.
255    out.extend_from_slice(&(function.eval_sites.len() as u32).to_be_bytes());
256    for site in &function.eval_sites {
257        out.extend_from_slice(&site.line.to_be_bytes());
258        out.extend_from_slice(&site.column.to_be_bytes());
259        out.extend_from_slice(&(site.bindings.len() as u32).to_be_bytes());
260        for binding in &site.bindings {
261            write_string(out, &binding.name);
262            out.push(u8::from(binding.is_arg));
263            out.extend_from_slice(&binding.index.to_be_bytes());
264            out.extend_from_slice(&binding.owner.to_be_bytes());
265        }
266        // Whether the call site has an `arguments` binding; see `EvalSite`.
267        out.push(u8::from(site.arguments_allowed));
268        // The private names a class body around the call site declares, so an AOT product
269        // runs `eval("this.#x")` the same way the interpreter does.
270        out.extend_from_slice(&(site.private_names.len() as u32).to_be_bytes());
271        for private in &site.private_names {
272            write_string(out, &private.name);
273            out.push(match private.kind {
274                crate::bytecode::EvalPrivateKind::Field => 0,
275                crate::bytecode::EvalPrivateKind::Method => 1,
276                crate::bytecode::EvalPrivateKind::Getter => 2,
277                crate::bytecode::EvalPrivateKind::Setter => 3,
278            });
279            match &private.setter {
280                Some(setter) => {
281                    out.push(1);
282                    write_string(out, setter);
283                }
284                None => out.push(0),
285            }
286        }
287    }
288
289    // The position table travels with the code: an AOT binary that dropped it would
290    // lose `error.stack`'s file:line:col even though the bytecode is identical.
291    out.extend_from_slice(&(function.positions.len() as u32).to_be_bytes());
292    for entry in &function.positions {
293        out.extend_from_slice(&entry.pc.to_be_bytes());
294        out.extend_from_slice(&entry.line.to_be_bytes());
295        out.extend_from_slice(&entry.column.to_be_bytes());
296    }
297
298    // The file name a frame prints. The parser never sees it, so it cannot be recovered
299    // from the bytecode: it is the host's to supply, and an AOT binary that dropped it
300    // would report every frame as `<input>`.
301    write_optional_string(out, function.filename.as_deref());
302    // The source text, only when the writer kept it.
303    write_optional_string(
304        out,
305        if options.keep_source {
306            function.source.as_deref()
307        } else {
308            None
309        },
310    );
311    write_module_meta(out, function.module.as_deref());
312}
313
314fn write_optional_string(out: &mut Vec<u8>, text: Option<&str>) {
315    match text {
316        Some(text) => {
317            out.push(1);
318            write_string(out, text);
319        }
320        None => out.push(0),
321    }
322}
323
324/// The module tables, which are data rather than instructions: the host needs them in
325/// order to wire the body's import cells to their exporters before the body runs.
326fn write_module_meta(out: &mut Vec<u8>, meta: Option<&ModuleMeta>) {
327    let Some(meta) = meta else {
328        out.push(0);
329        return;
330    };
331    out.push(1);
332    out.extend_from_slice(&(meta.requests.len() as u32).to_be_bytes());
333    for request in &meta.requests {
334        write_string(out, &request.specifier);
335        out.extend_from_slice(&(request.attributes.len() as u32).to_be_bytes());
336        for (key, value) in &request.attributes {
337            write_string(out, key);
338            write_string(out, value);
339        }
340    }
341    out.extend_from_slice(&(meta.imports.len() as u32).to_be_bytes());
342    for import in &meta.imports {
343        out.extend_from_slice(&import.module.to_be_bytes());
344        write_string(out, &import.name);
345        out.extend_from_slice(&import.var_idx.to_be_bytes());
346        out.push(u8::from(import.is_star));
347    }
348    out.extend_from_slice(&(meta.exports.len() as u32).to_be_bytes());
349    for export in &meta.exports {
350        match export {
351            ExportEntry::Local {
352                export_name,
353                var_idx,
354            } => {
355                out.push(0);
356                write_string(out, export_name);
357                out.extend_from_slice(&var_idx.to_be_bytes());
358            }
359            ExportEntry::Indirect {
360                export_name,
361                module,
362                import_name,
363            } => {
364                out.push(1);
365                write_string(out, export_name);
366                out.extend_from_slice(&module.to_be_bytes());
367                write_string(out, import_name);
368            }
369            ExportEntry::Star { module } => {
370                out.push(2);
371                out.extend_from_slice(&module.to_be_bytes());
372            }
373            ExportEntry::StarAs {
374                export_name,
375                module,
376            } => {
377                out.push(3);
378                write_string(out, export_name);
379                out.extend_from_slice(&module.to_be_bytes());
380            }
381        }
382    }
383}
384
385fn write_constant(out: &mut Vec<u8>, constant: &Constant, options: Options) {
386    match constant {
387        Constant::Number(value) => {
388            out.push(0);
389            out.extend_from_slice(&value.to_bits().to_be_bytes());
390        }
391        Constant::String(text) => {
392            out.push(1);
393            write_wtf8(out, text);
394        }
395        Constant::BigInt { digits, radix } => {
396            out.push(2);
397            write_string(out, digits);
398            out.push(*radix as u8);
399        }
400        Constant::Function(function) => {
401            out.push(3);
402            write_function(out, function, options);
403        }
404        Constant::Template { site, cooked, raw } => {
405            out.push(4);
406            out.extend_from_slice(&site.to_be_bytes());
407            out.extend_from_slice(&(cooked.len() as u32).to_be_bytes());
408            for quasi in cooked {
409                match quasi {
410                    Some(text) => {
411                        out.push(1);
412                        write_wtf8(out, text);
413                    }
414                    None => out.push(0),
415                }
416            }
417            out.extend_from_slice(&(raw.len() as u32).to_be_bytes());
418            for text in raw {
419                write_string(out, text);
420            }
421        }
422    }
423}
424
425struct Reader<'a> {
426    bytes: &'a [u8],
427    pos: usize,
428}
429
430impl<'a> Reader<'a> {
431    fn take(&mut self, count: usize) -> Result<&'a [u8], DecodeError> {
432        let end = self.pos.checked_add(count).ok_or(DecodeError::Truncated)?;
433        if end > self.bytes.len() {
434            return Err(DecodeError::Truncated);
435        }
436        let slice = &self.bytes[self.pos..end];
437        self.pos = end;
438        Ok(slice)
439    }
440
441    fn array<const N: usize>(&mut self) -> Result<[u8; N], DecodeError> {
442        let slice = self.take(N)?;
443        let mut out = [0u8; N];
444        out.copy_from_slice(slice);
445        Ok(out)
446    }
447
448    fn u8(&mut self) -> Result<u8, DecodeError> {
449        Ok(self.array::<1>()?[0])
450    }
451
452    fn u16(&mut self) -> Result<u16, DecodeError> {
453        Ok(u16::from_be_bytes(self.array::<2>()?))
454    }
455
456    fn u32(&mut self) -> Result<u32, DecodeError> {
457        Ok(u32::from_be_bytes(self.array::<4>()?))
458    }
459
460    fn i32(&mut self) -> Result<i32, DecodeError> {
461        Ok(i32::from_be_bytes(self.array::<4>()?))
462    }
463
464    fn string(&mut self) -> Result<String, DecodeError> {
465        let length = self.u32()? as usize;
466        let bytes = self.take(length)?;
467        String::from_utf8(bytes.to_vec()).map_err(|_| DecodeError::Truncated)
468    }
469
470    /// A string constant or atom, which may be WTF-8 rather than UTF-8.
471    ///
472    /// Not `string()`: a constant holding `"\uD800"` is not valid UTF-8, and treating that
473    /// as a truncated blob would make a bundle that loads fine in one build fail in the
474    /// next for no stated reason.
475    fn wtf8(&mut self) -> Result<Wtf8, DecodeError> {
476        let length = self.u32()? as usize;
477        let bytes = self.take(length)?;
478        Wtf8::from_wtf8_bytes(bytes).ok_or(DecodeError::Truncated)
479    }
480}
481
482fn read_var(reader: &mut Reader<'_>) -> Result<VarDef, DecodeError> {
483    let name = reader.string()?;
484    let flags = reader.u8()?;
485    let kind = var_kind_from_tag(reader.u8()?)?;
486    let scope_level = reader.u32()?;
487    let scope_next = match reader.u8()? {
488        0 => None,
489        1 => Some(reader.i32()?),
490        other => return Err(DecodeError::BadTag("scope", other)),
491    };
492    Ok(VarDef {
493        name,
494        is_const: flags & 1 != 0,
495        is_lexical: flags & 2 != 0,
496        is_captured: flags & 4 != 0,
497        kind,
498        scope_level,
499        scope_next,
500    })
501}
502
503fn read_function(reader: &mut Reader<'_>) -> Result<Function, DecodeError> {
504    let name = reader.string()?;
505    let kind = kind_from_tag(reader.u8()?)?;
506    let flags = reader.u8()?;
507    let strict = flags & 1 != 0;
508    let is_arrow = flags & 2 != 0;
509    let has_parameter_expressions = flags & 4 != 0;
510    let simple_parameter_list = flags & 8 != 0;
511    let is_derived_constructor = flags & 16 != 0;
512    let line = reader.u32()?;
513    let column = reader.u32()?;
514    let body_start = (reader.u32()?, reader.u32()?);
515
516    let defined_args = reader.u32()?;
517    let arg_count = reader.u32()? as usize;
518    let mut args = Vec::with_capacity(arg_count);
519    for _ in 0..arg_count {
520        args.push(read_var(reader)?);
521    }
522    let var_count = reader.u32()? as usize;
523    let mut vars = Vec::with_capacity(var_count);
524    for _ in 0..var_count {
525        vars.push(read_var(reader)?);
526    }
527
528    let closure_count = reader.u32()? as usize;
529    let mut closure_vars = Vec::with_capacity(closure_count);
530    for _ in 0..closure_count {
531        let name = reader.string()?;
532        let flags = reader.u8()?;
533        let closure_type = closure_type_from_tag(reader.u8()?)?;
534        let var_idx = reader.u16()?;
535        closure_vars.push(ClosureVar {
536            name,
537            is_const: flags & 1 != 0,
538            is_lexical: flags & 2 != 0,
539            closure_type,
540            var_idx,
541        });
542    }
543
544    let atom_count = reader.u32()? as usize;
545    let mut atoms = Vec::with_capacity(atom_count);
546    for _ in 0..atom_count {
547        atoms.push(read_atom(reader)?);
548    }
549
550    let cpool_count = reader.u32()? as usize;
551    let mut cpool = Vec::with_capacity(cpool_count);
552    for _ in 0..cpool_count {
553        cpool.push(read_constant(reader)?);
554    }
555
556    let code_length = reader.u32()? as usize;
557    let code = reader.take(code_length)?.to_vec();
558    let stack_size = reader.u32()?;
559    let var_ref_count = reader.u32()?;
560    let eval_site_count = reader.u32()? as usize;
561    let mut eval_sites = Vec::with_capacity(eval_site_count);
562    for _ in 0..eval_site_count {
563        let line = reader.u32()?;
564        let column = reader.u32()?;
565        let binding_count = reader.u32()? as usize;
566        let mut bindings = Vec::with_capacity(binding_count);
567        for _ in 0..binding_count {
568            let name = reader.string()?;
569            let is_arg = reader.take(1)?[0] != 0;
570            let index = reader.u32()?;
571            let owner = reader.u32()?;
572            bindings.push(crate::bytecode::EvalVisible {
573                name,
574                is_arg,
575                index,
576                owner,
577            });
578        }
579        let arguments_allowed = reader.take(1)?[0] != 0;
580        let private_count = reader.u32()? as usize;
581        let mut private_names = Vec::with_capacity(private_count);
582        for _ in 0..private_count {
583            let name = reader.string()?;
584            let kind = match reader.take(1)?[0] {
585                0 => crate::bytecode::EvalPrivateKind::Field,
586                1 => crate::bytecode::EvalPrivateKind::Method,
587                2 => crate::bytecode::EvalPrivateKind::Getter,
588                _ => crate::bytecode::EvalPrivateKind::Setter,
589            };
590            let setter = if reader.take(1)?[0] != 0 {
591                Some(reader.string()?)
592            } else {
593                None
594            };
595            private_names.push(crate::bytecode::EvalPrivate { name, kind, setter });
596        }
597        eval_sites.push(crate::bytecode::EvalSite {
598            line,
599            column,
600            bindings,
601            private_names,
602            arguments_allowed,
603        });
604    }
605    let position_count = reader.u32()? as usize;
606    let mut positions = Vec::with_capacity(position_count);
607    for _ in 0..position_count {
608        positions.push(LineCol {
609            pc: reader.u32()?,
610            line: reader.u32()?,
611            column: reader.u32()?,
612        });
613    }
614    // The harness fields, in the order `write_function` wrote them.
615    let filename = read_optional_string(reader)?;
616    let source = read_optional_string(reader)?;
617    let module = read_module_meta(reader)?;
618    Ok(Function {
619        name,
620        kind,
621        strict,
622        is_derived_constructor,
623        is_arrow,
624        has_parameter_expressions,
625        simple_parameter_list,
626        body_start,
627        args,
628        defined_args,
629        vars,
630        closure_vars,
631        cpool,
632        atoms,
633        code,
634        stack_size,
635        positions,
636        var_ref_count,
637        source,
638        line,
639        column,
640        filename,
641        eval_sites,
642        module,
643    })
644}
645
646fn read_optional_string(reader: &mut Reader<'_>) -> Result<Option<String>, DecodeError> {
647    match reader.u8()? {
648        0 => Ok(None),
649        1 => Ok(Some(reader.string()?)),
650        other => Err(DecodeError::BadTag("optional string", other)),
651    }
652}
653
654fn read_module_meta(reader: &mut Reader<'_>) -> Result<Option<Box<ModuleMeta>>, DecodeError> {
655    match reader.u8()? {
656        0 => return Ok(None),
657        1 => {}
658        other => return Err(DecodeError::BadTag("module", other)),
659    }
660    let request_count = reader.u32()? as usize;
661    let mut requests = Vec::with_capacity(request_count);
662    for _ in 0..request_count {
663        let specifier = reader.string()?;
664        let attribute_count = reader.u32()? as usize;
665        let mut attributes = Vec::with_capacity(attribute_count);
666        for _ in 0..attribute_count {
667            let key = reader.string()?;
668            let value = reader.string()?;
669            attributes.push((key, value));
670        }
671        requests.push(ModuleRequest {
672            specifier,
673            attributes,
674        });
675    }
676    let import_count = reader.u32()? as usize;
677    let mut imports = Vec::with_capacity(import_count);
678    for _ in 0..import_count {
679        let module = reader.u32()?;
680        let name = reader.string()?;
681        let var_idx = reader.u32()?;
682        let is_star = reader.u8()? != 0;
683        imports.push(ImportEntry {
684            module,
685            name,
686            var_idx,
687            is_star,
688        });
689    }
690    let export_count = reader.u32()? as usize;
691    let mut exports = Vec::with_capacity(export_count);
692    for _ in 0..export_count {
693        exports.push(match reader.u8()? {
694            0 => ExportEntry::Local {
695                export_name: reader.string()?,
696                var_idx: reader.u32()?,
697            },
698            1 => ExportEntry::Indirect {
699                export_name: reader.string()?,
700                module: reader.u32()?,
701                import_name: reader.string()?,
702            },
703            2 => ExportEntry::Star {
704                module: reader.u32()?,
705            },
706            3 => ExportEntry::StarAs {
707                export_name: reader.string()?,
708                module: reader.u32()?,
709            },
710            other => return Err(DecodeError::BadTag("export", other)),
711        });
712    }
713    Ok(Some(Box::new(ModuleMeta {
714        requests,
715        imports,
716        exports,
717    })))
718}
719
720fn read_constant(reader: &mut Reader<'_>) -> Result<Constant, DecodeError> {
721    match reader.u8()? {
722        0 => Ok(Constant::Number(f64::from_bits(u64::from_be_bytes(
723            reader.array::<8>()?,
724        )))),
725        1 => Ok(Constant::String(reader.wtf8()?)),
726        2 => {
727            let digits = reader.string()?;
728            let radix = reader.u8()? as u32;
729            Ok(Constant::BigInt { digits, radix })
730        }
731        3 => Ok(Constant::Function(Box::new(read_function(reader)?))),
732        4 => {
733            let site = reader.u32()?;
734            let count = reader.u32()? as usize;
735            let mut cooked = Vec::with_capacity(count);
736            for _ in 0..count {
737                cooked.push(match reader.u8()? {
738                    0 => None,
739                    1 => Some(reader.wtf8()?),
740                    other => return Err(DecodeError::BadTag("template", other)),
741                });
742            }
743            let raw_count = reader.u32()? as usize;
744            let mut raw = Vec::with_capacity(raw_count);
745            for _ in 0..raw_count {
746                raw.push(reader.string()?);
747            }
748            Ok(Constant::Template { site, cooked, raw })
749        }
750        other => Err(DecodeError::BadTag("constant", other)),
751    }
752}
753
754fn kind_tag(kind: FunctionKind) -> u8 {
755    match kind {
756        FunctionKind::Normal => 0,
757        FunctionKind::Generator => 1,
758        FunctionKind::Async => 2,
759        FunctionKind::AsyncGenerator => 3,
760    }
761}
762
763fn kind_from_tag(tag: u8) -> Result<FunctionKind, DecodeError> {
764    Ok(match tag {
765        0 => FunctionKind::Normal,
766        1 => FunctionKind::Generator,
767        2 => FunctionKind::Async,
768        3 => FunctionKind::AsyncGenerator,
769        other => return Err(DecodeError::BadTag("function kind", other)),
770    })
771}
772
773fn var_kind_tag(kind: VarKind) -> u8 {
774    match kind {
775        VarKind::Normal => 0,
776        VarKind::FunctionDecl => 1,
777        VarKind::NewFunctionDecl => 2,
778        VarKind::Catch => 3,
779        VarKind::FunctionName => 4,
780        VarKind::PrivateField => 5,
781        VarKind::PrivateMethod => 6,
782        VarKind::PrivateGetter => 7,
783        VarKind::PrivateSetter => 8,
784        VarKind::PrivateGetterSetter => 9,
785        VarKind::GlobalFunctionDecl => 10,
786        VarKind::Using => 11,
787        VarKind::UsingMethod => 12,
788        VarKind::With => 13,
789        VarKind::LexicalCatch => 14,
790    }
791}
792
793fn var_kind_from_tag(tag: u8) -> Result<VarKind, DecodeError> {
794    Ok(match tag {
795        0 => VarKind::Normal,
796        1 => VarKind::FunctionDecl,
797        2 => VarKind::NewFunctionDecl,
798        3 => VarKind::Catch,
799        4 => VarKind::FunctionName,
800        5 => VarKind::PrivateField,
801        6 => VarKind::PrivateMethod,
802        7 => VarKind::PrivateGetter,
803        8 => VarKind::PrivateSetter,
804        9 => VarKind::PrivateGetterSetter,
805        10 => VarKind::GlobalFunctionDecl,
806        11 => VarKind::Using,
807        12 => VarKind::UsingMethod,
808        13 => VarKind::With,
809        14 => VarKind::LexicalCatch,
810        other => return Err(DecodeError::BadTag("variable kind", other)),
811    })
812}
813
814fn closure_type_tag(kind: ClosureType) -> u8 {
815    match kind {
816        ClosureType::Local => 0,
817        ClosureType::Arg => 1,
818        ClosureType::Ref => 2,
819        ClosureType::GlobalRef => 3,
820        ClosureType::GlobalDecl => 4,
821        ClosureType::Global => 5,
822        ClosureType::ModuleDecl => 6,
823        ClosureType::ModuleImport => 7,
824    }
825}
826
827fn closure_type_from_tag(tag: u8) -> Result<ClosureType, DecodeError> {
828    Ok(match tag {
829        0 => ClosureType::Local,
830        1 => ClosureType::Arg,
831        2 => ClosureType::Ref,
832        3 => ClosureType::GlobalRef,
833        4 => ClosureType::GlobalDecl,
834        5 => ClosureType::Global,
835        6 => ClosureType::ModuleDecl,
836        7 => ClosureType::ModuleImport,
837        other => return Err(DecodeError::BadTag("closure type", other)),
838    })
839}
840
841#[cfg(test)]
842mod tests {
843    use super::*;
844
845    fn sample() -> Function {
846        Function {
847            name: "<eval>".to_string(),
848            kind: FunctionKind::Normal,
849            strict: false,
850            is_derived_constructor: false,
851            is_arrow: false,
852            has_parameter_expressions: false,
853            simple_parameter_list: false,
854            body_start: (1, 12),
855            args: vec![],
856            defined_args: 0,
857            vars: vec![VarDef::var("<ret>"), VarDef::constant("k")],
858            // A site with one binding of each shape, so the round trip covers the
859            // table a direct `eval` depends on.
860            eval_sites: vec![crate::bytecode::EvalSite {
861                line: 3,
862                column: 7,
863                bindings: vec![
864                    crate::bytecode::EvalVisible {
865                        name: "a".to_string(),
866                        is_arg: true,
867                        index: 0,
868                        owner: 0,
869                    },
870                    crate::bytecode::EvalVisible {
871                        name: "b".to_string(),
872                        is_arg: false,
873                        index: 1,
874                        owner: 2,
875                    },
876                ],
877                // One private name of each shape the kind tag can take, and the setter
878                // suffix, so the round trip covers all of it.
879                private_names: vec![
880                    crate::bytecode::EvalPrivate {
881                        name: "#f".to_string(),
882                        kind: crate::bytecode::EvalPrivateKind::Field,
883                        setter: None,
884                    },
885                    crate::bytecode::EvalPrivate {
886                        name: "#a".to_string(),
887                        kind: crate::bytecode::EvalPrivateKind::Getter,
888                        setter: Some("#a<set>".to_string()),
889                    },
890                ],
891                arguments_allowed: false,
892            }],
893            closure_vars: vec![ClosureVar {
894                name: "g".to_string(),
895                is_const: false,
896                is_lexical: false,
897                closure_type: ClosureType::GlobalDecl,
898                var_idx: 0,
899            }],
900            cpool: vec![Constant::Number(1.5), Constant::String(Wtf8::new("s"))],
901            // One of each kind, so the round trip covers the atom tag.
902            atoms: vec![Atom::from_text("a"), Atom::from_text("2")],
903            code: vec![0x2c, 0x00, 0x00],
904            stack_size: 3,
905            positions: vec![
906                LineCol {
907                    pc: 0,
908                    line: 1,
909                    column: 1,
910                },
911                LineCol {
912                    pc: 2,
913                    line: 3,
914                    column: 7,
915                },
916            ],
917            var_ref_count: 0,
918            source: None,
919            line: 1,
920            column: 1,
921            filename: None,
922            module: None,
923        }
924    }
925
926    #[test]
927    fn round_trips() {
928        let function = sample();
929        let bytes = serialize(&function);
930        let back = deserialize(&bytes).expect("decode");
931        assert_eq!(back, function);
932    }
933
934    #[test]
935    fn rejects_foreign_input() {
936        assert_eq!(deserialize(b"JUNK\x00\x01"), Err(DecodeError::BadMagic));
937    }
938
939    #[test]
940    fn rejects_a_future_version() {
941        let mut bytes = serialize(&sample());
942        bytes[4..6].copy_from_slice(&(VERSION + 1).to_be_bytes());
943        assert_eq!(
944            deserialize(&bytes),
945            Err(DecodeError::BadVersion(VERSION + 1))
946        );
947    }
948
949    #[test]
950    fn rejects_truncated_input() {
951        let bytes = serialize(&sample());
952        assert_eq!(
953            deserialize(&bytes[..bytes.len() - 1]),
954            Err(DecodeError::Truncated)
955        );
956    }
957}