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