quickjs-compile 0.10.1

Bytecode compiler for the pure-Rust QuickJS port
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
//! Serialisation of compiled bytecode.
//!
//! The format is our own — it deliberately does not interoperate with the C
//! implementation's binary blobs — but it keeps the same *semantics*: a compiled
//! function can be written out and read back without the source, which is what
//! `qjsc` relies on for ahead-of-time compilation.
//!
//! Layout, all integers big-endian:
//!
//! ```text
//! magic    4 bytes  "QJSB"
//! version  u16      format version
//! function          one function record, recursively
//!
//! function record:
//!   name        string (u32 length + UTF-8 bytes)
//!   kind        u8
//!   flags       u8    bit 0 = strict, bit 1 = arrow
//!   line, column u32 each
//!   defined_args u32  arity that counts towards `.length`
//!   args        u32 count, then name/flags records
//!   vars        u32 count, then name/flags/scope records
//!   closures    u32 count, then name/flags/type/index records
//!   cpool       u32 count, then constants
//!   code        u32 length + bytes
//!   stack_size  u32
//!   var_refs    u32
//!   positions   u32 count, then pc/line/column u32 each
//!   filename    optional string (tag u8: 0 none, 1 + string)
//!   source      optional string, present only when the writer kept it
//!   module      u8 tag: 0 = a script, 1 = module tables follow
//!                 requests  u32 count, then specifier + attribute pairs
//!                 imports   u32 count, then module/var_idx/name/is_star
//!                 exports   u32 count, then a tagged entry
//! ```
//!
//! The last three are not bytecode. They are what the *host* needs in order to run the
//! bytecode without the source: the file name a stack frame prints and a module records,
//! the source text `Function.prototype.toString` reports (dropped unless the writer asks,
//! which is what `qjsc`'s `--keep-source` is for), and the module tables — data the host
//! wires imports up from before the body runs.
//!
//! A version bump is required for any change to this layout; [`MAGIC`] plus
//! [`VERSION`] make a stale blob fail loudly instead of being misinterpreted.

use crate::bytecode::{
    Atom, ClosureType, ClosureVar, Constant, ExportEntry, Function, FunctionKind, ImportEntry,
    LineCol, ModuleMeta, ModuleRequest, VarDef, VarKind,
};
use std::fmt;

/// File magic.
pub const MAGIC: [u8; 4] = *b"QJSB";

/// Format version. Bumped whenever the layout below changes.
///
/// 9 added the file name, the optional source text and the module tables. A blob written
/// by 8 still *loads* its bytecode correctly, but it cannot say which file it came from
/// or what it imports, so it is rejected rather than half-run.
pub const VERSION: u16 = 9;

/// Why a blob could not be read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DecodeError {
    /// The magic number is wrong; this is not our bytecode.
    BadMagic,
    /// The format version is not one this build understands.
    BadVersion(u16),
    /// The blob ends in the middle of a value.
    Truncated,
    /// A discriminant is out of range.
    BadTag(&'static str, u8),
    /// An atom entry has an unknown kind tag.
    BadAtomTag(u8),
}

impl fmt::Display for DecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DecodeError::BadMagic => f.write_str("not QuickJS-RS bytecode (bad magic)"),
            DecodeError::BadVersion(v) => write!(f, "unsupported bytecode version {v}"),
            DecodeError::Truncated => f.write_str("truncated bytecode"),
            DecodeError::BadTag(what, tag) => write!(f, "invalid {what} tag {tag}"),
            DecodeError::BadAtomTag(tag) => write!(f, "invalid atom kind tag {tag}"),
        }
    }
}

impl std::error::Error for DecodeError {}

/// What to keep besides the bytecode.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Options {
    /// Keep the source text, which is what `Function.prototype.toString` and a stack
    /// trace's `file:line` context read from. Off by default: `qjsc` strips it unless
    /// asked (`--keep-source`), and a stripped blob is both smaller and not a copy of the
    /// original program.
    pub keep_source: bool,
}

/// Write a compiled function, including its nested functions, without its source text.
pub fn serialize(function: &Function) -> Vec<u8> {
    serialize_with(function, Options::default())
}

/// [`serialize`], with control over what is kept.
pub fn serialize_with(function: &Function, options: Options) -> Vec<u8> {
    let mut out = Vec::new();
    out.extend_from_slice(&MAGIC);
    out.extend_from_slice(&VERSION.to_be_bytes());
    write_function(&mut out, function, options);
    out
}

/// Read a compiled function back.
pub fn deserialize(bytes: &[u8]) -> Result<Function, DecodeError> {
    let mut reader = Reader { bytes, pos: 0 };
    if reader.take(4)? != MAGIC {
        return Err(DecodeError::BadMagic);
    }
    let version = u16::from_be_bytes(reader.array::<2>()?);
    if version != VERSION {
        return Err(DecodeError::BadVersion(version));
    }
    read_function(&mut reader)
}

/// One atom, tagged by kind so a canonical array index survives the round trip as
/// a number rather than turning back into its decimal spelling.
fn write_atom(out: &mut Vec<u8>, atom: &Atom) {
    match atom {
        Atom::Str(text) => {
            out.push(0);
            write_string(out, text);
        }
        Atom::Index(index) => {
            out.push(1);
            out.extend_from_slice(&index.to_be_bytes());
        }
        Atom::Null => out.push(2),
    }
}

fn read_atom(reader: &mut Reader<'_>) -> Result<Atom, DecodeError> {
    match reader.u8()? {
        0 => Ok(Atom::Str(reader.string()?)),
        1 => Ok(Atom::Index(u32::from_be_bytes(reader.array::<4>()?))),
        2 => Ok(Atom::Null),
        tag => Err(DecodeError::BadAtomTag(tag)),
    }
}

fn write_string(out: &mut Vec<u8>, text: &str) {
    out.extend_from_slice(&(text.len() as u32).to_be_bytes());
    out.extend_from_slice(text.as_bytes());
}

fn write_var(out: &mut Vec<u8>, var: &VarDef) {
    write_string(out, &var.name);
    let mut flags = 0u8;
    if var.is_const {
        flags |= 1;
    }
    if var.is_lexical {
        flags |= 2;
    }
    if var.is_captured {
        flags |= 4;
    }
    out.push(flags);
    out.push(var_kind_tag(var.kind));
    out.extend_from_slice(&var.scope_level.to_be_bytes());
    match var.scope_next {
        Some(next) => {
            out.push(1);
            out.extend_from_slice(&next.to_be_bytes());
        }
        None => out.push(0),
    }
}

fn write_function(out: &mut Vec<u8>, function: &Function, options: Options) {
    write_string(out, &function.name);
    out.push(kind_tag(function.kind));
    out.push(
        u8::from(function.strict)
            | (u8::from(function.is_arrow) << 1)
            | (u8::from(function.has_parameter_expressions) << 2),
    );
    out.extend_from_slice(&function.line.to_be_bytes());
    out.extend_from_slice(&function.column.to_be_bytes());
    out.extend_from_slice(&function.body_start.0.to_be_bytes());
    out.extend_from_slice(&function.body_start.1.to_be_bytes());

    out.extend_from_slice(&function.defined_args.to_be_bytes());
    out.extend_from_slice(&(function.args.len() as u32).to_be_bytes());
    for arg in &function.args {
        write_var(out, arg);
    }
    out.extend_from_slice(&(function.vars.len() as u32).to_be_bytes());
    for var in &function.vars {
        write_var(out, var);
    }

    out.extend_from_slice(&(function.closure_vars.len() as u32).to_be_bytes());
    for closure in &function.closure_vars {
        write_string(out, &closure.name);
        let mut flags = 0u8;
        if closure.is_const {
            flags |= 1;
        }
        if closure.is_lexical {
            flags |= 2;
        }
        out.push(flags);
        out.push(closure_type_tag(closure.closure_type));
        out.extend_from_slice(&closure.var_idx.to_be_bytes());
    }

    out.extend_from_slice(&(function.atoms.len() as u32).to_be_bytes());
    for atom in &function.atoms {
        write_atom(out, atom);
    }

    out.extend_from_slice(&(function.cpool.len() as u32).to_be_bytes());
    for constant in &function.cpool {
        write_constant(out, constant, options);
    }

    out.extend_from_slice(&(function.code.len() as u32).to_be_bytes());
    out.extend_from_slice(&function.code);
    out.extend_from_slice(&function.stack_size.to_be_bytes());
    out.extend_from_slice(&function.var_ref_count.to_be_bytes());
    // The eval-site table travels with the code for the same reason as the position
    // table: it is what lets a direct `eval` resolve a shadowed name to the right slot,
    // and it cannot be recomputed from the bytecode.
    out.extend_from_slice(&(function.eval_sites.len() as u32).to_be_bytes());
    for site in &function.eval_sites {
        out.extend_from_slice(&site.line.to_be_bytes());
        out.extend_from_slice(&site.column.to_be_bytes());
        out.extend_from_slice(&(site.bindings.len() as u32).to_be_bytes());
        for binding in &site.bindings {
            write_string(out, &binding.name);
            out.push(u8::from(binding.is_arg));
            out.extend_from_slice(&binding.index.to_be_bytes());
            out.extend_from_slice(&binding.owner.to_be_bytes());
        }
    }

    // The position table travels with the code: an AOT binary that dropped it would
    // lose `error.stack`'s file:line:col even though the bytecode is identical.
    out.extend_from_slice(&(function.positions.len() as u32).to_be_bytes());
    for entry in &function.positions {
        out.extend_from_slice(&entry.pc.to_be_bytes());
        out.extend_from_slice(&entry.line.to_be_bytes());
        out.extend_from_slice(&entry.column.to_be_bytes());
    }

    // The file name a frame prints. The parser never sees it, so it cannot be recovered
    // from the bytecode: it is the host's to supply, and an AOT binary that dropped it
    // would report every frame as `<input>`.
    write_optional_string(out, function.filename.as_deref());
    // The source text, only when the writer kept it.
    write_optional_string(
        out,
        if options.keep_source {
            function.source.as_deref()
        } else {
            None
        },
    );
    write_module_meta(out, function.module.as_deref());
}

fn write_optional_string(out: &mut Vec<u8>, text: Option<&str>) {
    match text {
        Some(text) => {
            out.push(1);
            write_string(out, text);
        }
        None => out.push(0),
    }
}

/// The module tables, which are data rather than instructions: the host needs them in
/// order to wire the body's import cells to their exporters before the body runs.
fn write_module_meta(out: &mut Vec<u8>, meta: Option<&ModuleMeta>) {
    let Some(meta) = meta else {
        out.push(0);
        return;
    };
    out.push(1);
    out.extend_from_slice(&(meta.requests.len() as u32).to_be_bytes());
    for request in &meta.requests {
        write_string(out, &request.specifier);
        out.extend_from_slice(&(request.attributes.len() as u32).to_be_bytes());
        for (key, value) in &request.attributes {
            write_string(out, key);
            write_string(out, value);
        }
    }
    out.extend_from_slice(&(meta.imports.len() as u32).to_be_bytes());
    for import in &meta.imports {
        out.extend_from_slice(&import.module.to_be_bytes());
        write_string(out, &import.name);
        out.extend_from_slice(&import.var_idx.to_be_bytes());
        out.push(u8::from(import.is_star));
    }
    out.extend_from_slice(&(meta.exports.len() as u32).to_be_bytes());
    for export in &meta.exports {
        match export {
            ExportEntry::Local {
                export_name,
                var_idx,
            } => {
                out.push(0);
                write_string(out, export_name);
                out.extend_from_slice(&var_idx.to_be_bytes());
            }
            ExportEntry::Indirect {
                export_name,
                module,
                import_name,
            } => {
                out.push(1);
                write_string(out, export_name);
                out.extend_from_slice(&module.to_be_bytes());
                write_string(out, import_name);
            }
            ExportEntry::Star { module } => {
                out.push(2);
                out.extend_from_slice(&module.to_be_bytes());
            }
            ExportEntry::StarAs {
                export_name,
                module,
            } => {
                out.push(3);
                write_string(out, export_name);
                out.extend_from_slice(&module.to_be_bytes());
            }
        }
    }
}

fn write_constant(out: &mut Vec<u8>, constant: &Constant, options: Options) {
    match constant {
        Constant::Number(value) => {
            out.push(0);
            out.extend_from_slice(&value.to_bits().to_be_bytes());
        }
        Constant::String(text) => {
            out.push(1);
            write_string(out, text);
        }
        Constant::BigInt { digits, radix } => {
            out.push(2);
            write_string(out, digits);
            out.push(*radix as u8);
        }
        Constant::Function(function) => {
            out.push(3);
            write_function(out, function, options);
        }
        Constant::Template { cooked, raw } => {
            out.push(4);
            out.extend_from_slice(&(cooked.len() as u32).to_be_bytes());
            for quasi in cooked {
                match quasi {
                    Some(text) => {
                        out.push(1);
                        write_string(out, text);
                    }
                    None => out.push(0),
                }
            }
            out.extend_from_slice(&(raw.len() as u32).to_be_bytes());
            for text in raw {
                write_string(out, text);
            }
        }
    }
}

struct Reader<'a> {
    bytes: &'a [u8],
    pos: usize,
}

impl<'a> Reader<'a> {
    fn take(&mut self, count: usize) -> Result<&'a [u8], DecodeError> {
        let end = self.pos.checked_add(count).ok_or(DecodeError::Truncated)?;
        if end > self.bytes.len() {
            return Err(DecodeError::Truncated);
        }
        let slice = &self.bytes[self.pos..end];
        self.pos = end;
        Ok(slice)
    }

    fn array<const N: usize>(&mut self) -> Result<[u8; N], DecodeError> {
        let slice = self.take(N)?;
        let mut out = [0u8; N];
        out.copy_from_slice(slice);
        Ok(out)
    }

    fn u8(&mut self) -> Result<u8, DecodeError> {
        Ok(self.array::<1>()?[0])
    }

    fn u16(&mut self) -> Result<u16, DecodeError> {
        Ok(u16::from_be_bytes(self.array::<2>()?))
    }

    fn u32(&mut self) -> Result<u32, DecodeError> {
        Ok(u32::from_be_bytes(self.array::<4>()?))
    }

    fn i32(&mut self) -> Result<i32, DecodeError> {
        Ok(i32::from_be_bytes(self.array::<4>()?))
    }

    fn string(&mut self) -> Result<String, DecodeError> {
        let length = self.u32()? as usize;
        let bytes = self.take(length)?;
        String::from_utf8(bytes.to_vec()).map_err(|_| DecodeError::Truncated)
    }
}

fn read_var(reader: &mut Reader<'_>) -> Result<VarDef, DecodeError> {
    let name = reader.string()?;
    let flags = reader.u8()?;
    let kind = var_kind_from_tag(reader.u8()?)?;
    let scope_level = reader.u32()?;
    let scope_next = match reader.u8()? {
        0 => None,
        1 => Some(reader.i32()?),
        other => return Err(DecodeError::BadTag("scope", other)),
    };
    Ok(VarDef {
        name,
        is_const: flags & 1 != 0,
        is_lexical: flags & 2 != 0,
        is_captured: flags & 4 != 0,
        kind,
        scope_level,
        scope_next,
    })
}

fn read_function(reader: &mut Reader<'_>) -> Result<Function, DecodeError> {
    let name = reader.string()?;
    let kind = kind_from_tag(reader.u8()?)?;
    let flags = reader.u8()?;
    let strict = flags & 1 != 0;
    let is_arrow = flags & 2 != 0;
    let has_parameter_expressions = flags & 4 != 0;
    let line = reader.u32()?;
    let column = reader.u32()?;
    let body_start = (reader.u32()?, reader.u32()?);

    let defined_args = reader.u32()?;
    let arg_count = reader.u32()? as usize;
    let mut args = Vec::with_capacity(arg_count);
    for _ in 0..arg_count {
        args.push(read_var(reader)?);
    }
    let var_count = reader.u32()? as usize;
    let mut vars = Vec::with_capacity(var_count);
    for _ in 0..var_count {
        vars.push(read_var(reader)?);
    }

    let closure_count = reader.u32()? as usize;
    let mut closure_vars = Vec::with_capacity(closure_count);
    for _ in 0..closure_count {
        let name = reader.string()?;
        let flags = reader.u8()?;
        let closure_type = closure_type_from_tag(reader.u8()?)?;
        let var_idx = reader.u16()?;
        closure_vars.push(ClosureVar {
            name,
            is_const: flags & 1 != 0,
            is_lexical: flags & 2 != 0,
            closure_type,
            var_idx,
        });
    }

    let atom_count = reader.u32()? as usize;
    let mut atoms = Vec::with_capacity(atom_count);
    for _ in 0..atom_count {
        atoms.push(read_atom(reader)?);
    }

    let cpool_count = reader.u32()? as usize;
    let mut cpool = Vec::with_capacity(cpool_count);
    for _ in 0..cpool_count {
        cpool.push(read_constant(reader)?);
    }

    let code_length = reader.u32()? as usize;
    let code = reader.take(code_length)?.to_vec();
    let stack_size = reader.u32()?;
    let var_ref_count = reader.u32()?;
    let eval_site_count = reader.u32()? as usize;
    let mut eval_sites = Vec::with_capacity(eval_site_count);
    for _ in 0..eval_site_count {
        let line = reader.u32()?;
        let column = reader.u32()?;
        let binding_count = reader.u32()? as usize;
        let mut bindings = Vec::with_capacity(binding_count);
        for _ in 0..binding_count {
            let name = reader.string()?;
            let is_arg = reader.take(1)?[0] != 0;
            let index = reader.u32()?;
            let owner = reader.u32()?;
            bindings.push(crate::bytecode::EvalVisible {
                name,
                is_arg,
                index,
                owner,
            });
        }
        eval_sites.push(crate::bytecode::EvalSite {
            line,
            column,
            bindings,
        });
    }
    let position_count = reader.u32()? as usize;
    let mut positions = Vec::with_capacity(position_count);
    for _ in 0..position_count {
        positions.push(LineCol {
            pc: reader.u32()?,
            line: reader.u32()?,
            column: reader.u32()?,
        });
    }
    // The harness fields, in the order `write_function` wrote them.
    let filename = read_optional_string(reader)?;
    let source = read_optional_string(reader)?;
    let module = read_module_meta(reader)?;
    Ok(Function {
        name,
        kind,
        strict,
        is_arrow,
        has_parameter_expressions,
        body_start,
        args,
        defined_args,
        vars,
        closure_vars,
        cpool,
        atoms,
        code,
        stack_size,
        positions,
        var_ref_count,
        source,
        line,
        column,
        filename,
        eval_sites,
        module,
    })
}

fn read_optional_string(reader: &mut Reader<'_>) -> Result<Option<String>, DecodeError> {
    match reader.u8()? {
        0 => Ok(None),
        1 => Ok(Some(reader.string()?)),
        other => Err(DecodeError::BadTag("optional string", other)),
    }
}

fn read_module_meta(reader: &mut Reader<'_>) -> Result<Option<Box<ModuleMeta>>, DecodeError> {
    match reader.u8()? {
        0 => return Ok(None),
        1 => {}
        other => return Err(DecodeError::BadTag("module", other)),
    }
    let request_count = reader.u32()? as usize;
    let mut requests = Vec::with_capacity(request_count);
    for _ in 0..request_count {
        let specifier = reader.string()?;
        let attribute_count = reader.u32()? as usize;
        let mut attributes = Vec::with_capacity(attribute_count);
        for _ in 0..attribute_count {
            let key = reader.string()?;
            let value = reader.string()?;
            attributes.push((key, value));
        }
        requests.push(ModuleRequest {
            specifier,
            attributes,
        });
    }
    let import_count = reader.u32()? as usize;
    let mut imports = Vec::with_capacity(import_count);
    for _ in 0..import_count {
        let module = reader.u32()?;
        let name = reader.string()?;
        let var_idx = reader.u32()?;
        let is_star = reader.u8()? != 0;
        imports.push(ImportEntry {
            module,
            name,
            var_idx,
            is_star,
        });
    }
    let export_count = reader.u32()? as usize;
    let mut exports = Vec::with_capacity(export_count);
    for _ in 0..export_count {
        exports.push(match reader.u8()? {
            0 => ExportEntry::Local {
                export_name: reader.string()?,
                var_idx: reader.u32()?,
            },
            1 => ExportEntry::Indirect {
                export_name: reader.string()?,
                module: reader.u32()?,
                import_name: reader.string()?,
            },
            2 => ExportEntry::Star {
                module: reader.u32()?,
            },
            3 => ExportEntry::StarAs {
                export_name: reader.string()?,
                module: reader.u32()?,
            },
            other => return Err(DecodeError::BadTag("export", other)),
        });
    }
    Ok(Some(Box::new(ModuleMeta {
        requests,
        imports,
        exports,
    })))
}

fn read_constant(reader: &mut Reader<'_>) -> Result<Constant, DecodeError> {
    match reader.u8()? {
        0 => Ok(Constant::Number(f64::from_bits(u64::from_be_bytes(
            reader.array::<8>()?,
        )))),
        1 => Ok(Constant::String(reader.string()?)),
        2 => {
            let digits = reader.string()?;
            let radix = reader.u8()? as u32;
            Ok(Constant::BigInt { digits, radix })
        }
        3 => Ok(Constant::Function(Box::new(read_function(reader)?))),
        4 => {
            let count = reader.u32()? as usize;
            let mut cooked = Vec::with_capacity(count);
            for _ in 0..count {
                cooked.push(match reader.u8()? {
                    0 => None,
                    1 => Some(reader.string()?),
                    other => return Err(DecodeError::BadTag("template", other)),
                });
            }
            let raw_count = reader.u32()? as usize;
            let mut raw = Vec::with_capacity(raw_count);
            for _ in 0..raw_count {
                raw.push(reader.string()?);
            }
            Ok(Constant::Template { cooked, raw })
        }
        other => Err(DecodeError::BadTag("constant", other)),
    }
}

fn kind_tag(kind: FunctionKind) -> u8 {
    match kind {
        FunctionKind::Normal => 0,
        FunctionKind::Generator => 1,
        FunctionKind::Async => 2,
        FunctionKind::AsyncGenerator => 3,
    }
}

fn kind_from_tag(tag: u8) -> Result<FunctionKind, DecodeError> {
    Ok(match tag {
        0 => FunctionKind::Normal,
        1 => FunctionKind::Generator,
        2 => FunctionKind::Async,
        3 => FunctionKind::AsyncGenerator,
        other => return Err(DecodeError::BadTag("function kind", other)),
    })
}

fn var_kind_tag(kind: VarKind) -> u8 {
    match kind {
        VarKind::Normal => 0,
        VarKind::FunctionDecl => 1,
        VarKind::NewFunctionDecl => 2,
        VarKind::Catch => 3,
        VarKind::FunctionName => 4,
        VarKind::PrivateField => 5,
        VarKind::PrivateMethod => 6,
        VarKind::PrivateGetter => 7,
        VarKind::PrivateSetter => 8,
        VarKind::PrivateGetterSetter => 9,
        VarKind::GlobalFunctionDecl => 10,
        VarKind::Using => 11,
        VarKind::UsingMethod => 12,
        VarKind::With => 13,
        VarKind::LexicalCatch => 14,
    }
}

fn var_kind_from_tag(tag: u8) -> Result<VarKind, DecodeError> {
    Ok(match tag {
        0 => VarKind::Normal,
        1 => VarKind::FunctionDecl,
        2 => VarKind::NewFunctionDecl,
        3 => VarKind::Catch,
        4 => VarKind::FunctionName,
        5 => VarKind::PrivateField,
        6 => VarKind::PrivateMethod,
        7 => VarKind::PrivateGetter,
        8 => VarKind::PrivateSetter,
        9 => VarKind::PrivateGetterSetter,
        10 => VarKind::GlobalFunctionDecl,
        11 => VarKind::Using,
        12 => VarKind::UsingMethod,
        13 => VarKind::With,
        14 => VarKind::LexicalCatch,
        other => return Err(DecodeError::BadTag("variable kind", other)),
    })
}

fn closure_type_tag(kind: ClosureType) -> u8 {
    match kind {
        ClosureType::Local => 0,
        ClosureType::Arg => 1,
        ClosureType::Ref => 2,
        ClosureType::GlobalRef => 3,
        ClosureType::GlobalDecl => 4,
        ClosureType::Global => 5,
        ClosureType::ModuleDecl => 6,
        ClosureType::ModuleImport => 7,
    }
}

fn closure_type_from_tag(tag: u8) -> Result<ClosureType, DecodeError> {
    Ok(match tag {
        0 => ClosureType::Local,
        1 => ClosureType::Arg,
        2 => ClosureType::Ref,
        3 => ClosureType::GlobalRef,
        4 => ClosureType::GlobalDecl,
        5 => ClosureType::Global,
        6 => ClosureType::ModuleDecl,
        7 => ClosureType::ModuleImport,
        other => return Err(DecodeError::BadTag("closure type", other)),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample() -> Function {
        Function {
            name: "<eval>".to_string(),
            kind: FunctionKind::Normal,
            strict: false,
            is_arrow: false,
            has_parameter_expressions: false,
            body_start: (1, 12),
            args: vec![],
            defined_args: 0,
            vars: vec![VarDef::var("<ret>"), VarDef::constant("k")],
            // A site with one binding of each shape, so the round trip covers the
            // table a direct `eval` depends on.
            eval_sites: vec![crate::bytecode::EvalSite {
                line: 3,
                column: 7,
                bindings: vec![
                    crate::bytecode::EvalVisible {
                        name: "a".to_string(),
                        is_arg: true,
                        index: 0,
                        owner: 0,
                    },
                    crate::bytecode::EvalVisible {
                        name: "b".to_string(),
                        is_arg: false,
                        index: 1,
                        owner: 2,
                    },
                ],
            }],
            closure_vars: vec![ClosureVar {
                name: "g".to_string(),
                is_const: false,
                is_lexical: false,
                closure_type: ClosureType::GlobalDecl,
                var_idx: 0,
            }],
            cpool: vec![Constant::Number(1.5), Constant::String("s".to_string())],
            // One of each kind, so the round trip covers the atom tag.
            atoms: vec![Atom::from_text("a"), Atom::from_text("2")],
            code: vec![0x2c, 0x00, 0x00],
            stack_size: 3,
            positions: vec![
                LineCol {
                    pc: 0,
                    line: 1,
                    column: 1,
                },
                LineCol {
                    pc: 2,
                    line: 3,
                    column: 7,
                },
            ],
            var_ref_count: 0,
            source: None,
            line: 1,
            column: 1,
            filename: None,
            module: None,
        }
    }

    #[test]
    fn round_trips() {
        let function = sample();
        let bytes = serialize(&function);
        let back = deserialize(&bytes).expect("decode");
        assert_eq!(back, function);
    }

    #[test]
    fn rejects_foreign_input() {
        assert_eq!(deserialize(b"JUNK\x00\x01"), Err(DecodeError::BadMagic));
    }

    #[test]
    fn rejects_a_future_version() {
        let mut bytes = serialize(&sample());
        bytes[4..6].copy_from_slice(&(VERSION + 1).to_be_bytes());
        assert_eq!(
            deserialize(&bytes),
            Err(DecodeError::BadVersion(VERSION + 1))
        );
    }

    #[test]
    fn rejects_truncated_input() {
        let bytes = serialize(&sample());
        assert_eq!(
            deserialize(&bytes[..bytes.len() - 1]),
            Err(DecodeError::Truncated)
        );
    }
}