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