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