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 = 10;
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            | (u8::from(function.is_script_body) << 5),
208    );
209    out.extend_from_slice(&function.line.to_be_bytes());
210    out.extend_from_slice(&function.column.to_be_bytes());
211    out.extend_from_slice(&function.body_start.0.to_be_bytes());
212    out.extend_from_slice(&function.body_start.1.to_be_bytes());
213
214    out.extend_from_slice(&function.defined_args.to_be_bytes());
215    out.extend_from_slice(&(function.args.len() as u32).to_be_bytes());
216    for arg in &function.args {
217        write_var(out, arg);
218    }
219    out.extend_from_slice(&(function.vars.len() as u32).to_be_bytes());
220    for var in &function.vars {
221        write_var(out, var);
222    }
223
224    out.extend_from_slice(&(function.closure_vars.len() as u32).to_be_bytes());
225    for closure in &function.closure_vars {
226        write_string(out, &closure.name);
227        let mut flags = 0u8;
228        if closure.is_const {
229            flags |= 1;
230        }
231        if closure.is_lexical {
232            flags |= 2;
233        }
234        if closure.is_function_decl {
235            flags |= 4;
236        }
237        out.push(flags);
238        out.push(closure_type_tag(closure.closure_type));
239        out.extend_from_slice(&closure.var_idx.to_be_bytes());
240    }
241
242    out.extend_from_slice(&(function.atoms.len() as u32).to_be_bytes());
243    for atom in &function.atoms {
244        write_atom(out, atom);
245    }
246
247    out.extend_from_slice(&(function.cpool.len() as u32).to_be_bytes());
248    for constant in &function.cpool {
249        write_constant(out, constant, options);
250    }
251
252    out.extend_from_slice(&(function.code.len() as u32).to_be_bytes());
253    out.extend_from_slice(&function.code);
254    out.extend_from_slice(&function.stack_size.to_be_bytes());
255    out.extend_from_slice(&function.var_ref_count.to_be_bytes());
256    // The eval-site table travels with the code for the same reason as the position
257    // table: it is what lets a direct `eval` resolve a shadowed name to the right slot,
258    // and it cannot be recomputed from the bytecode.
259    out.extend_from_slice(&(function.eval_sites.len() as u32).to_be_bytes());
260    for site in &function.eval_sites {
261        out.extend_from_slice(&site.line.to_be_bytes());
262        out.extend_from_slice(&site.column.to_be_bytes());
263        out.extend_from_slice(&(site.bindings.len() as u32).to_be_bytes());
264        for binding in &site.bindings {
265            write_string(out, &binding.name);
266            out.push(u8::from(binding.is_arg));
267            out.extend_from_slice(&binding.index.to_be_bytes());
268            out.extend_from_slice(&binding.owner.to_be_bytes());
269        }
270        // Whether the call site has an `arguments` binding; see `EvalSite`.
271        out.push(u8::from(site.arguments_allowed));
272        // The private names a class body around the call site declares, so an AOT product
273        // runs `eval("this.#x")` the same way the interpreter does.
274        out.extend_from_slice(&(site.private_names.len() as u32).to_be_bytes());
275        for private in &site.private_names {
276            write_string(out, &private.name);
277            out.push(match private.kind {
278                crate::bytecode::EvalPrivateKind::Field => 0,
279                crate::bytecode::EvalPrivateKind::Method => 1,
280                crate::bytecode::EvalPrivateKind::Getter => 2,
281                crate::bytecode::EvalPrivateKind::Setter => 3,
282            });
283            match &private.setter {
284                Some(setter) => {
285                    out.push(1);
286                    write_string(out, setter);
287                }
288                None => out.push(0),
289            }
290        }
291    }
292
293    // The position table travels with the code: an AOT binary that dropped it would
294    // lose `error.stack`'s file:line:col even though the bytecode is identical.
295    out.extend_from_slice(&(function.positions.len() as u32).to_be_bytes());
296    for entry in &function.positions {
297        out.extend_from_slice(&entry.pc.to_be_bytes());
298        out.extend_from_slice(&entry.line.to_be_bytes());
299        out.extend_from_slice(&entry.column.to_be_bytes());
300    }
301
302    // The file name a frame prints. The parser never sees it, so it cannot be recovered
303    // from the bytecode: it is the host's to supply, and an AOT binary that dropped it
304    // would report every frame as `<input>`.
305    write_optional_string(out, function.filename.as_deref());
306    // The source text, only when the writer kept it.
307    write_optional_string(
308        out,
309        if options.keep_source {
310            function.source.as_deref()
311        } else {
312            None
313        },
314    );
315    write_module_meta(out, function.module.as_deref());
316}
317
318fn write_optional_string(out: &mut Vec<u8>, text: Option<&str>) {
319    match text {
320        Some(text) => {
321            out.push(1);
322            write_string(out, text);
323        }
324        None => out.push(0),
325    }
326}
327
328/// The module tables, which are data rather than instructions: the host needs them in
329/// order to wire the body's import cells to their exporters before the body runs.
330fn write_module_meta(out: &mut Vec<u8>, meta: Option<&ModuleMeta>) {
331    let Some(meta) = meta else {
332        out.push(0);
333        return;
334    };
335    out.push(1);
336    out.extend_from_slice(&(meta.requests.len() as u32).to_be_bytes());
337    for request in &meta.requests {
338        write_string(out, &request.specifier);
339        out.extend_from_slice(&(request.attributes.len() as u32).to_be_bytes());
340        for (key, value) in &request.attributes {
341            write_string(out, key);
342            write_string(out, value);
343        }
344        out.push(phase_tag(request.phase));
345    }
346    out.extend_from_slice(&(meta.imports.len() as u32).to_be_bytes());
347    for import in &meta.imports {
348        out.extend_from_slice(&import.module.to_be_bytes());
349        write_string(out, &import.name);
350        out.extend_from_slice(&import.var_idx.to_be_bytes());
351        out.push(u8::from(import.is_star));
352        out.push(phase_tag(import.phase));
353    }
354    out.extend_from_slice(&(meta.exports.len() as u32).to_be_bytes());
355    for export in &meta.exports {
356        match export {
357            ExportEntry::Local {
358                export_name,
359                var_idx,
360            } => {
361                out.push(0);
362                write_string(out, export_name);
363                out.extend_from_slice(&var_idx.to_be_bytes());
364            }
365            ExportEntry::Indirect {
366                export_name,
367                module,
368                import_name,
369            } => {
370                out.push(1);
371                write_string(out, export_name);
372                out.extend_from_slice(&module.to_be_bytes());
373                write_string(out, import_name);
374            }
375            ExportEntry::Star { module } => {
376                out.push(2);
377                out.extend_from_slice(&module.to_be_bytes());
378            }
379            ExportEntry::StarAs {
380                export_name,
381                module,
382            } => {
383                out.push(3);
384                write_string(out, export_name);
385                out.extend_from_slice(&module.to_be_bytes());
386            }
387        }
388    }
389}
390
391fn write_constant(out: &mut Vec<u8>, constant: &Constant, options: Options) {
392    match constant {
393        Constant::Number(value) => {
394            out.push(0);
395            out.extend_from_slice(&value.to_bits().to_be_bytes());
396        }
397        Constant::String(text) => {
398            out.push(1);
399            write_wtf8(out, text);
400        }
401        Constant::BigInt { digits, radix } => {
402            out.push(2);
403            write_string(out, digits);
404            out.push(*radix as u8);
405        }
406        Constant::Function(function) => {
407            out.push(3);
408            write_function(out, function, options);
409        }
410        Constant::Template { site, cooked, raw } => {
411            out.push(4);
412            out.extend_from_slice(&site.to_be_bytes());
413            out.extend_from_slice(&(cooked.len() as u32).to_be_bytes());
414            for quasi in cooked {
415                match quasi {
416                    Some(text) => {
417                        out.push(1);
418                        write_wtf8(out, text);
419                    }
420                    None => out.push(0),
421                }
422            }
423            out.extend_from_slice(&(raw.len() as u32).to_be_bytes());
424            for text in raw {
425                write_string(out, text);
426            }
427        }
428    }
429}
430
431struct Reader<'a> {
432    bytes: &'a [u8],
433    pos: usize,
434}
435
436impl<'a> Reader<'a> {
437    fn take(&mut self, count: usize) -> Result<&'a [u8], DecodeError> {
438        let end = self.pos.checked_add(count).ok_or(DecodeError::Truncated)?;
439        if end > self.bytes.len() {
440            return Err(DecodeError::Truncated);
441        }
442        let slice = &self.bytes[self.pos..end];
443        self.pos = end;
444        Ok(slice)
445    }
446
447    fn array<const N: usize>(&mut self) -> Result<[u8; N], DecodeError> {
448        let slice = self.take(N)?;
449        let mut out = [0u8; N];
450        out.copy_from_slice(slice);
451        Ok(out)
452    }
453
454    fn u8(&mut self) -> Result<u8, DecodeError> {
455        Ok(self.array::<1>()?[0])
456    }
457
458    fn u16(&mut self) -> Result<u16, DecodeError> {
459        Ok(u16::from_be_bytes(self.array::<2>()?))
460    }
461
462    fn u32(&mut self) -> Result<u32, DecodeError> {
463        Ok(u32::from_be_bytes(self.array::<4>()?))
464    }
465
466    fn i32(&mut self) -> Result<i32, DecodeError> {
467        Ok(i32::from_be_bytes(self.array::<4>()?))
468    }
469
470    fn string(&mut self) -> Result<String, DecodeError> {
471        let length = self.u32()? as usize;
472        let bytes = self.take(length)?;
473        String::from_utf8(bytes.to_vec()).map_err(|_| DecodeError::Truncated)
474    }
475
476    /// A string constant or atom, which may be WTF-8 rather than UTF-8.
477    ///
478    /// Not `string()`: a constant holding `"\uD800"` is not valid UTF-8, and treating that
479    /// as a truncated blob would make a bundle that loads fine in one build fail in the
480    /// next for no stated reason.
481    fn wtf8(&mut self) -> Result<Wtf8, DecodeError> {
482        let length = self.u32()? as usize;
483        let bytes = self.take(length)?;
484        Wtf8::from_wtf8_bytes(bytes).ok_or(DecodeError::Truncated)
485    }
486}
487
488fn read_var(reader: &mut Reader<'_>) -> Result<VarDef, DecodeError> {
489    let name = reader.string()?;
490    let flags = reader.u8()?;
491    let kind = var_kind_from_tag(reader.u8()?)?;
492    let scope_level = reader.u32()?;
493    let scope_next = match reader.u8()? {
494        0 => None,
495        1 => Some(reader.i32()?),
496        other => return Err(DecodeError::BadTag("scope", other)),
497    };
498    Ok(VarDef {
499        name,
500        is_const: flags & 1 != 0,
501        is_lexical: flags & 2 != 0,
502        is_captured: flags & 4 != 0,
503        kind,
504        scope_level,
505        scope_next,
506    })
507}
508
509fn read_function(reader: &mut Reader<'_>) -> Result<Function, DecodeError> {
510    let name = reader.string()?;
511    let kind = kind_from_tag(reader.u8()?)?;
512    let flags = reader.u8()?;
513    let strict = flags & 1 != 0;
514    let is_arrow = flags & 2 != 0;
515    let has_parameter_expressions = flags & 4 != 0;
516    let simple_parameter_list = flags & 8 != 0;
517    let is_derived_constructor = flags & 16 != 0;
518    let is_script_body = flags & 32 != 0;
519    let line = reader.u32()?;
520    let column = reader.u32()?;
521    let body_start = (reader.u32()?, reader.u32()?);
522
523    let defined_args = reader.u32()?;
524    let arg_count = reader.u32()? as usize;
525    let mut args = Vec::with_capacity(arg_count);
526    for _ in 0..arg_count {
527        args.push(read_var(reader)?);
528    }
529    let var_count = reader.u32()? as usize;
530    let mut vars = Vec::with_capacity(var_count);
531    for _ in 0..var_count {
532        vars.push(read_var(reader)?);
533    }
534
535    let closure_count = reader.u32()? as usize;
536    let mut closure_vars = Vec::with_capacity(closure_count);
537    for _ in 0..closure_count {
538        let name = reader.string()?;
539        let flags = reader.u8()?;
540        let closure_type = closure_type_from_tag(reader.u8()?)?;
541        let var_idx = reader.u16()?;
542        closure_vars.push(ClosureVar {
543            name,
544            is_const: flags & 1 != 0,
545            is_lexical: flags & 2 != 0,
546            is_function_decl: flags & 4 != 0,
547            closure_type,
548            var_idx,
549        });
550    }
551
552    let atom_count = reader.u32()? as usize;
553    let mut atoms = Vec::with_capacity(atom_count);
554    for _ in 0..atom_count {
555        atoms.push(read_atom(reader)?);
556    }
557
558    let cpool_count = reader.u32()? as usize;
559    let mut cpool = Vec::with_capacity(cpool_count);
560    for _ in 0..cpool_count {
561        cpool.push(read_constant(reader)?);
562    }
563
564    let code_length = reader.u32()? as usize;
565    let code = reader.take(code_length)?.to_vec();
566    let stack_size = reader.u32()?;
567    let var_ref_count = reader.u32()?;
568    let eval_site_count = reader.u32()? as usize;
569    let mut eval_sites = Vec::with_capacity(eval_site_count);
570    for _ in 0..eval_site_count {
571        let line = reader.u32()?;
572        let column = reader.u32()?;
573        let binding_count = reader.u32()? as usize;
574        let mut bindings = Vec::with_capacity(binding_count);
575        for _ in 0..binding_count {
576            let name = reader.string()?;
577            let is_arg = reader.take(1)?[0] != 0;
578            let index = reader.u32()?;
579            let owner = reader.u32()?;
580            bindings.push(crate::bytecode::EvalVisible {
581                name,
582                is_arg,
583                index,
584                owner,
585            });
586        }
587        let arguments_allowed = reader.take(1)?[0] != 0;
588        let private_count = reader.u32()? as usize;
589        let mut private_names = Vec::with_capacity(private_count);
590        for _ in 0..private_count {
591            let name = reader.string()?;
592            let kind = match reader.take(1)?[0] {
593                0 => crate::bytecode::EvalPrivateKind::Field,
594                1 => crate::bytecode::EvalPrivateKind::Method,
595                2 => crate::bytecode::EvalPrivateKind::Getter,
596                _ => crate::bytecode::EvalPrivateKind::Setter,
597            };
598            let setter = if reader.take(1)?[0] != 0 {
599                Some(reader.string()?)
600            } else {
601                None
602            };
603            private_names.push(crate::bytecode::EvalPrivate { name, kind, setter });
604        }
605        eval_sites.push(crate::bytecode::EvalSite {
606            line,
607            column,
608            bindings,
609            private_names,
610            arguments_allowed,
611        });
612    }
613    let position_count = reader.u32()? as usize;
614    let mut positions = Vec::with_capacity(position_count);
615    for _ in 0..position_count {
616        positions.push(LineCol {
617            pc: reader.u32()?,
618            line: reader.u32()?,
619            column: reader.u32()?,
620        });
621    }
622    // The harness fields, in the order `write_function` wrote them.
623    let filename = read_optional_string(reader)?;
624    let source = read_optional_string(reader)?;
625    let module = read_module_meta(reader)?;
626    Ok(Function {
627        name,
628        kind,
629        strict,
630        is_derived_constructor,
631        is_script_body,
632        is_arrow,
633        has_parameter_expressions,
634        simple_parameter_list,
635        body_start,
636        args,
637        defined_args,
638        vars,
639        closure_vars,
640        cpool,
641        atoms,
642        code,
643        stack_size,
644        positions,
645        var_ref_count,
646        source,
647        line,
648        column,
649        filename,
650        eval_sites,
651        module,
652    })
653}
654
655fn read_optional_string(reader: &mut Reader<'_>) -> Result<Option<String>, DecodeError> {
656    match reader.u8()? {
657        0 => Ok(None),
658        1 => Ok(Some(reader.string()?)),
659        other => Err(DecodeError::BadTag("optional string", other)),
660    }
661}
662
663/// The one-byte encoding of an [`ImportPhase`](js_parse::ast::ImportPhase).
664fn phase_tag(phase: js_parse::ast::ImportPhase) -> u8 {
665    match phase {
666        js_parse::ast::ImportPhase::Evaluation => 0,
667        js_parse::ast::ImportPhase::Defer => 1,
668        js_parse::ast::ImportPhase::Source => 2,
669    }
670}
671
672fn read_phase_tag(tag: u8) -> Result<js_parse::ast::ImportPhase, DecodeError> {
673    match tag {
674        0 => Ok(js_parse::ast::ImportPhase::Evaluation),
675        1 => Ok(js_parse::ast::ImportPhase::Defer),
676        2 => Ok(js_parse::ast::ImportPhase::Source),
677        other => Err(DecodeError::BadTag("import phase", other)),
678    }
679}
680
681fn read_module_meta(reader: &mut Reader<'_>) -> Result<Option<Box<ModuleMeta>>, DecodeError> {
682    match reader.u8()? {
683        0 => return Ok(None),
684        1 => {}
685        other => return Err(DecodeError::BadTag("module", other)),
686    }
687    let request_count = reader.u32()? as usize;
688    let mut requests = Vec::with_capacity(request_count);
689    for _ in 0..request_count {
690        let specifier = reader.string()?;
691        let attribute_count = reader.u32()? as usize;
692        let mut attributes = Vec::with_capacity(attribute_count);
693        for _ in 0..attribute_count {
694            let key = reader.string()?;
695            let value = reader.string()?;
696            attributes.push((key, value));
697        }
698        let phase = read_phase_tag(reader.u8()?)?;
699        requests.push(ModuleRequest {
700            specifier,
701            attributes,
702            phase,
703        });
704    }
705    let import_count = reader.u32()? as usize;
706    let mut imports = Vec::with_capacity(import_count);
707    for _ in 0..import_count {
708        let module = reader.u32()?;
709        let name = reader.string()?;
710        let var_idx = reader.u32()?;
711        let is_star = reader.u8()? != 0;
712        let phase = read_phase_tag(reader.u8()?)?;
713        imports.push(ImportEntry {
714            module,
715            name,
716            var_idx,
717            is_star,
718            phase,
719        });
720    }
721    let export_count = reader.u32()? as usize;
722    let mut exports = Vec::with_capacity(export_count);
723    for _ in 0..export_count {
724        exports.push(match reader.u8()? {
725            0 => ExportEntry::Local {
726                export_name: reader.string()?,
727                var_idx: reader.u32()?,
728            },
729            1 => ExportEntry::Indirect {
730                export_name: reader.string()?,
731                module: reader.u32()?,
732                import_name: reader.string()?,
733            },
734            2 => ExportEntry::Star {
735                module: reader.u32()?,
736            },
737            3 => ExportEntry::StarAs {
738                export_name: reader.string()?,
739                module: reader.u32()?,
740            },
741            other => return Err(DecodeError::BadTag("export", other)),
742        });
743    }
744    Ok(Some(Box::new(ModuleMeta {
745        requests,
746        imports,
747        exports,
748    })))
749}
750
751fn read_constant(reader: &mut Reader<'_>) -> Result<Constant, DecodeError> {
752    match reader.u8()? {
753        0 => Ok(Constant::Number(f64::from_bits(u64::from_be_bytes(
754            reader.array::<8>()?,
755        )))),
756        1 => Ok(Constant::String(reader.wtf8()?)),
757        2 => {
758            let digits = reader.string()?;
759            let radix = reader.u8()? as u32;
760            Ok(Constant::BigInt { digits, radix })
761        }
762        3 => Ok(Constant::Function(Box::new(read_function(reader)?))),
763        4 => {
764            let site = reader.u32()?;
765            let count = reader.u32()? as usize;
766            let mut cooked = Vec::with_capacity(count);
767            for _ in 0..count {
768                cooked.push(match reader.u8()? {
769                    0 => None,
770                    1 => Some(reader.wtf8()?),
771                    other => return Err(DecodeError::BadTag("template", other)),
772                });
773            }
774            let raw_count = reader.u32()? as usize;
775            let mut raw = Vec::with_capacity(raw_count);
776            for _ in 0..raw_count {
777                raw.push(reader.string()?);
778            }
779            Ok(Constant::Template { site, cooked, raw })
780        }
781        other => Err(DecodeError::BadTag("constant", other)),
782    }
783}
784
785fn kind_tag(kind: FunctionKind) -> u8 {
786    match kind {
787        FunctionKind::Normal => 0,
788        FunctionKind::Generator => 1,
789        FunctionKind::Async => 2,
790        FunctionKind::AsyncGenerator => 3,
791    }
792}
793
794fn kind_from_tag(tag: u8) -> Result<FunctionKind, DecodeError> {
795    Ok(match tag {
796        0 => FunctionKind::Normal,
797        1 => FunctionKind::Generator,
798        2 => FunctionKind::Async,
799        3 => FunctionKind::AsyncGenerator,
800        other => return Err(DecodeError::BadTag("function kind", other)),
801    })
802}
803
804fn var_kind_tag(kind: VarKind) -> u8 {
805    match kind {
806        VarKind::Normal => 0,
807        VarKind::FunctionDecl => 1,
808        VarKind::NewFunctionDecl => 2,
809        VarKind::Catch => 3,
810        VarKind::FunctionName => 4,
811        VarKind::PrivateField => 5,
812        VarKind::PrivateMethod => 6,
813        VarKind::PrivateGetter => 7,
814        VarKind::PrivateSetter => 8,
815        VarKind::PrivateGetterSetter => 9,
816        VarKind::GlobalFunctionDecl => 10,
817        VarKind::Using => 11,
818        VarKind::UsingMethod => 12,
819        VarKind::With => 13,
820        VarKind::LexicalCatch => 14,
821    }
822}
823
824fn var_kind_from_tag(tag: u8) -> Result<VarKind, DecodeError> {
825    Ok(match tag {
826        0 => VarKind::Normal,
827        1 => VarKind::FunctionDecl,
828        2 => VarKind::NewFunctionDecl,
829        3 => VarKind::Catch,
830        4 => VarKind::FunctionName,
831        5 => VarKind::PrivateField,
832        6 => VarKind::PrivateMethod,
833        7 => VarKind::PrivateGetter,
834        8 => VarKind::PrivateSetter,
835        9 => VarKind::PrivateGetterSetter,
836        10 => VarKind::GlobalFunctionDecl,
837        11 => VarKind::Using,
838        12 => VarKind::UsingMethod,
839        13 => VarKind::With,
840        14 => VarKind::LexicalCatch,
841        other => return Err(DecodeError::BadTag("variable kind", other)),
842    })
843}
844
845fn closure_type_tag(kind: ClosureType) -> u8 {
846    match kind {
847        ClosureType::Local => 0,
848        ClosureType::Arg => 1,
849        ClosureType::Ref => 2,
850        ClosureType::GlobalRef => 3,
851        ClosureType::GlobalDecl => 4,
852        ClosureType::Global => 5,
853        ClosureType::ModuleDecl => 6,
854        ClosureType::ModuleImport => 7,
855    }
856}
857
858fn closure_type_from_tag(tag: u8) -> Result<ClosureType, DecodeError> {
859    Ok(match tag {
860        0 => ClosureType::Local,
861        1 => ClosureType::Arg,
862        2 => ClosureType::Ref,
863        3 => ClosureType::GlobalRef,
864        4 => ClosureType::GlobalDecl,
865        5 => ClosureType::Global,
866        6 => ClosureType::ModuleDecl,
867        7 => ClosureType::ModuleImport,
868        other => return Err(DecodeError::BadTag("closure type", other)),
869    })
870}
871
872#[cfg(test)]
873mod tests {
874    use super::*;
875
876    fn sample() -> Function {
877        Function {
878            name: "<eval>".to_string(),
879            kind: FunctionKind::Normal,
880            strict: false,
881            is_derived_constructor: false,
882            is_arrow: false,
883            is_script_body: true,
884            has_parameter_expressions: false,
885            simple_parameter_list: false,
886            body_start: (1, 12),
887            args: vec![],
888            defined_args: 0,
889            vars: vec![VarDef::var("<ret>"), VarDef::constant("k")],
890            // A site with one binding of each shape, so the round trip covers the
891            // table a direct `eval` depends on.
892            eval_sites: vec![crate::bytecode::EvalSite {
893                line: 3,
894                column: 7,
895                bindings: vec![
896                    crate::bytecode::EvalVisible {
897                        name: "a".to_string(),
898                        is_arg: true,
899                        index: 0,
900                        owner: 0,
901                    },
902                    crate::bytecode::EvalVisible {
903                        name: "b".to_string(),
904                        is_arg: false,
905                        index: 1,
906                        owner: 2,
907                    },
908                ],
909                // One private name of each shape the kind tag can take, and the setter
910                // suffix, so the round trip covers all of it.
911                private_names: vec![
912                    crate::bytecode::EvalPrivate {
913                        name: "#f".to_string(),
914                        kind: crate::bytecode::EvalPrivateKind::Field,
915                        setter: None,
916                    },
917                    crate::bytecode::EvalPrivate {
918                        name: "#a".to_string(),
919                        kind: crate::bytecode::EvalPrivateKind::Getter,
920                        setter: Some("#a<set>".to_string()),
921                    },
922                ],
923                arguments_allowed: false,
924            }],
925            closure_vars: vec![ClosureVar {
926                name: "g".to_string(),
927                is_const: false,
928                is_lexical: false,
929                is_function_decl: false,
930                closure_type: ClosureType::GlobalDecl,
931                var_idx: 0,
932            }],
933            cpool: vec![Constant::Number(1.5), Constant::String(Wtf8::new("s"))],
934            // One of each kind, so the round trip covers the atom tag.
935            atoms: vec![Atom::from_text("a"), Atom::from_text("2")],
936            code: vec![0x2c, 0x00, 0x00],
937            stack_size: 3,
938            positions: vec![
939                LineCol {
940                    pc: 0,
941                    line: 1,
942                    column: 1,
943                },
944                LineCol {
945                    pc: 2,
946                    line: 3,
947                    column: 7,
948                },
949            ],
950            var_ref_count: 0,
951            source: None,
952            line: 1,
953            column: 1,
954            filename: None,
955            module: None,
956        }
957    }
958
959    #[test]
960    fn round_trips() {
961        let function = sample();
962        let bytes = serialize(&function);
963        let back = deserialize(&bytes).expect("decode");
964        assert_eq!(back, function);
965    }
966
967    #[test]
968    fn rejects_foreign_input() {
969        assert_eq!(deserialize(b"JUNK\x00\x01"), Err(DecodeError::BadMagic));
970    }
971
972    #[test]
973    fn rejects_a_future_version() {
974        let mut bytes = serialize(&sample());
975        bytes[4..6].copy_from_slice(&(VERSION + 1).to_be_bytes());
976        assert_eq!(
977            deserialize(&bytes),
978            Err(DecodeError::BadVersion(VERSION + 1))
979        );
980    }
981
982    #[test]
983    fn rejects_truncated_input() {
984        let bytes = serialize(&sample());
985        assert_eq!(
986            deserialize(&bytes[..bytes.len() - 1]),
987            Err(DecodeError::Truncated)
988        );
989    }
990}