js_compile/bytecode.rs
1//! The bytecode representation of a function.
2//!
3//! Compilation happens in two phases, exactly as in the reference implementation:
4//!
5//! * **Unresolved** ([`FunctionBuilder`]): jump targets are label ids and every
6//! variable is still described by its declaration, not its storage class.
7//! * **Resolved** ([`Function`]): jump targets are byte offsets and every
8//! variable reference names its storage class (`arg`, `loc`, `var_ref` or
9//! `var`), so the bytecode can be executed and serialised.
10//!
11//! The split matters for testing: each phase can be compared against the
12//! corresponding pass of the reference compiler.
13
14use crate::opcode::Opcode;
15use std::fmt;
16
17/// One entry of a function's atom table.
18///
19/// The reference keeps two kinds of atom in one namespace, and the distinction is
20/// visible in the bytecode: an *array-index* atom is not a string at all but a
21/// tagged `uint32`, which is why `{ 2: x }` disassembles as `define_field 2` while
22/// `{ "1.5": x }` prints `define_field "1.5"`. Collapsing the two would make the
23/// disassembly wrong and lose information on the way back in, so the kind is
24/// carried here.
25#[derive(Debug, Clone, PartialEq, Eq, Hash)]
26pub enum Atom {
27 /// An interned string.
28 Str(String),
29 /// A canonical array index, held as a number rather than a string.
30 Index(u32),
31}
32
33impl Atom {
34 /// The atom the reference's `JS_NewAtomStr` would make of `text`.
35 ///
36 /// A canonical array index no greater than `2^31 - 1` is never interned as a
37 /// string: the reference returns a tagged integer instead. Anything else —
38 /// `"007"`, `"1e2"`, `"-0"`, or an index past the tag range — stays a string.
39 pub fn from_text(text: &str) -> Atom {
40 match canonical_array_index(text) {
41 Some(index) => Atom::Index(index),
42 None => Atom::Str(text.to_string()),
43 }
44 }
45
46 /// The text form, for callers that only care about the name.
47 pub fn as_str(&self) -> Option<&str> {
48 match self {
49 Atom::Str(text) => Some(text),
50 Atom::Index(_) => None,
51 }
52 }
53}
54
55impl fmt::Display for Atom {
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 match self {
58 Atom::Str(text) => write!(f, "{text}"),
59 Atom::Index(index) => write!(f, "{index}"),
60 }
61 }
62}
63
64/// `is_num_string` from the reference: the canonical decimal spelling of an index
65/// small enough to be tagged (at most `2^31 - 1`).
66///
67/// Canonical means no sign, no leading zeros and no other characters, so `"10"`
68/// qualifies while `"007"`, `"-0"` and `"1e2"` do not.
69fn canonical_array_index(text: &str) -> Option<u32> {
70 // `2^31 - 1` has ten digits, which bounds how long a canonical index can be.
71 if text.is_empty() || text.len() > 10 {
72 return None;
73 }
74 let bytes = text.as_bytes();
75 if !bytes.iter().all(u8::is_ascii_digit) {
76 return None;
77 }
78 if bytes[0] == b'0' && bytes.len() != 1 {
79 return None;
80 }
81 let value: u32 = text.parse().ok()?;
82 (value <= 0x7fff_ffff).then_some(value)
83}
84
85/// How a function was declared. Determines the calling convention.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum FunctionKind {
88 /// A plain function.
89 Normal,
90 /// `function*`
91 Generator,
92 /// `async function`
93 Async,
94 /// `async function*`
95 AsyncGenerator,
96}
97
98impl FunctionKind {
99 /// Whether the function is a generator (plain or async).
100 pub fn is_generator(self) -> bool {
101 matches!(self, FunctionKind::Generator | FunctionKind::AsyncGenerator)
102 }
103
104 /// Whether the function is async (plain or generator).
105 pub fn is_async(self) -> bool {
106 matches!(self, FunctionKind::Async | FunctionKind::AsyncGenerator)
107 }
108}
109
110/// What a declared name is used for, which decides how it is displayed and how
111/// the function prologue initialises it.
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum VarKind {
114 /// An ordinary binding.
115 Normal,
116 /// A lexical binding holding a hoisted function declaration.
117 FunctionDecl,
118 /// A lexical binding holding a hoisted async/generator function declaration.
119 NewFunctionDecl,
120 /// A `catch` parameter.
121 Catch,
122 /// The name bound to a named function expression, visible inside itself.
123 FunctionName,
124 /// A private class field.
125 PrivateField,
126 /// A private class method.
127 PrivateMethod,
128 /// A private class getter.
129 PrivateGetter,
130 /// A private class setter.
131 PrivateSetter,
132 /// A private class accessor pair (`get` and `set` sharing one name).
133 PrivateGetterSetter,
134 /// A global function declaration.
135 GlobalFunctionDecl,
136 /// A `using` declaration's binding.
137 Using,
138 /// The hidden local holding a `using` declaration's cached dispose method.
139 UsingMethod,
140 /// The hidden local holding a `with` statement's boxed object.
141 ///
142 /// Marked rather than merely named so the runtime can find the active ones without
143 /// guessing from a name prefix: an `eval` inside a `with` has to resolve names
144 /// against these objects before it reaches the realm.
145 With,
146}
147
148impl VarKind {
149 /// The word the disassembler prints for this kind.
150 pub fn label(self) -> &'static str {
151 match self {
152 VarKind::Catch => "catch",
153 VarKind::FunctionDecl | VarKind::NewFunctionDecl | VarKind::GlobalFunctionDecl => {
154 "function"
155 }
156 _ => "",
157 }
158 }
159
160 /// Whether the binding is initialised when the function is entered.
161 pub fn is_hoisted_declaration(self) -> bool {
162 matches!(self, VarKind::FunctionDecl | VarKind::NewFunctionDecl)
163 }
164}
165
166/// A declared variable: an argument or a local.
167#[derive(Debug, Clone, PartialEq, Eq)]
168pub struct VarDef {
169 /// The name, as written.
170 pub name: String,
171 /// Whether the binding is immutable.
172 pub is_const: bool,
173 /// Whether the binding is block-scoped (`let`/`const`/`class`).
174 pub is_lexical: bool,
175 /// What the binding is used for.
176 pub kind: VarKind,
177 /// Whether a closure captures this variable, which forces it into a
178 /// heap-allocated reference cell.
179 pub is_captured: bool,
180 /// The lexical scope the binding belongs to.
181 ///
182 /// Scope 0 is the function scope, where `var` and hoisted function
183 /// declarations live; the body and every block introduce a child scope. A
184 /// binding only exists between its scope's entry and exit, which is what the
185 /// runtime uses to swap `let`/`const` bindings in and out.
186 pub scope_level: u32,
187 /// Index of the next block-scoped variable in the enclosing scope chain, or
188 /// `None` for a `var` (which is visible in the whole function).
189 ///
190 /// The reference stores this in `JSVarDef::scope_next` and only fills it in
191 /// when `scope_level != 0`; the interpreter walks the chain to instantiate
192 /// and close the `let`/`const` bindings that are live at a given point.
193 pub scope_next: Option<i32>,
194}
195
196impl VarDef {
197 /// A plain `var` binding.
198 pub fn var(name: impl Into<String>) -> VarDef {
199 VarDef {
200 name: name.into(),
201 is_const: false,
202 is_lexical: false,
203 kind: VarKind::Normal,
204 is_captured: false,
205 scope_level: 0,
206 scope_next: None,
207 }
208 }
209
210 /// Whether reading this binding can hit the temporal dead zone, i.e. it is
211 /// `let`/`const`/`class` and therefore starts out uninitialised.
212 pub fn needs_check(&self) -> bool {
213 self.is_lexical
214 }
215
216 /// A `let` binding.
217 pub fn lexical(name: impl Into<String>) -> VarDef {
218 VarDef {
219 is_lexical: true,
220 ..VarDef::var(name)
221 }
222 }
223
224 /// A `const` binding.
225 pub fn constant(name: impl Into<String>) -> VarDef {
226 VarDef {
227 is_lexical: true,
228 is_const: true,
229 ..VarDef::var(name)
230 }
231 }
232
233 /// The word the disassembler prints for this definition.
234 pub fn label(&self) -> &'static str {
235 let kind = self.kind.label();
236 if !kind.is_empty() {
237 return kind;
238 }
239 if self.is_const {
240 "const"
241 } else if self.is_lexical {
242 "let"
243 } else {
244 "var"
245 }
246 }
247}
248
249/// Where a captured variable actually lives, and therefore how a closure
250/// reaches it.
251#[derive(Debug, Clone, Copy, PartialEq, Eq)]
252pub enum ClosureType {
253 /// A local of the parent function (`[loc<n>]`).
254 Local,
255 /// An argument of the parent function (`[arg<n>]`).
256 Arg,
257 /// A reference cell in the parent function (`[ref<n>]`).
258 Ref,
259 /// A global, reached through the reference table by index.
260 GlobalRef,
261 /// A global declared in this script.
262 GlobalDecl,
263 /// A global reached by name.
264 Global,
265 /// A module-level declaration.
266 ModuleDecl,
267 /// A module import binding.
268 ModuleImport,
269}
270
271impl ClosureType {
272 /// The suffix the disassembler prints.
273 pub fn describe(self) -> &'static str {
274 match self {
275 ClosureType::Local => "loc",
276 ClosureType::Arg => "arg",
277 ClosureType::Ref => "ref",
278 ClosureType::GlobalDecl => "global_decl",
279 ClosureType::Global => "global",
280 ClosureType::ModuleDecl => "module_decl",
281 ClosureType::ModuleImport => "module_import",
282 ClosureType::GlobalRef => "global_ref",
283 }
284 }
285}
286
287/// One captured variable of a function.
288#[derive(Debug, Clone, PartialEq, Eq)]
289pub struct ClosureVar {
290 /// The name, as written in the enclosing function.
291 pub name: String,
292 /// Whether the captured binding is immutable.
293 pub is_const: bool,
294 /// Whether the captured binding is block-scoped.
295 pub is_lexical: bool,
296 /// How the closure reaches it.
297 pub closure_type: ClosureType,
298 /// Index into the parent's locals, arguments or reference cells.
299 pub var_idx: u16,
300}
301
302/// A constant in the pool.
303#[derive(Debug, Clone, PartialEq)]
304pub enum Constant {
305 /// A number.
306 Number(f64),
307 /// A string.
308 String(String),
309 /// A BigInt literal: digits and radix.
310 BigInt {
311 /// Digits, without prefix or separators.
312 digits: String,
313 /// 2, 8, 10 or 16.
314 radix: u32,
315 },
316 /// A nested function, referenced by `fclosure`.
317 Function(Box<Function>),
318 /// A template object: one call site's chunks.
319 ///
320 /// The *raw* text is carried as well as the cooked text because `String.raw` reads
321 /// it back verbatim, and a tagged template may legally contain an invalid escape
322 /// sequence whose cooked form is `undefined`.
323 Template {
324 /// Cooked text; `None` for a chunk with an invalid escape sequence.
325 cooked: Vec<Option<String>>,
326 /// Source text of each chunk, verbatim.
327 raw: Vec<String>,
328 },
329}
330
331impl Constant {
332 /// A short description for disassembly, matching the reference's
333 /// `JS_PrintValue` for the cases the compiler can produce.
334 pub fn describe(&self) -> String {
335 match self {
336 Constant::Number(n) => format_number(*n),
337 Constant::String(s) => format!("\"{}\"", escape_js_string(s)),
338 // The reference prints BigInts in decimal, whatever the source radix.
339 Constant::BigInt { digits, .. } => format!("{digits}n"),
340 Constant::Function(f) => {
341 // The reference prints the function's name atom, which is `<null>`
342 // for an anonymous function expression.
343 if f.name.is_empty() {
344 "[bytecode <null>]".to_string()
345 } else {
346 format!("[bytecode {}]", f.name)
347 }
348 }
349 Constant::Template { cooked, .. } => {
350 let parts: Vec<String> = cooked
351 .iter()
352 .map(|q| q.clone().unwrap_or_else(|| "undefined".to_string()))
353 .collect();
354 format!("template object [{}]", parts.join(", "))
355 }
356 }
357 }
358}
359
360/// Format a number the way the reference implementation prints it.
361fn format_number(value: f64) -> String {
362 if value.is_nan() {
363 return "NaN".to_string();
364 }
365 if value.is_infinite() {
366 return if value > 0.0 {
367 "inf".to_string()
368 } else {
369 "-inf".to_string()
370 };
371 }
372 if value == value.trunc() && value.abs() < 1e21 {
373 return format!("{}", value as i64);
374 }
375 format!("{value}")
376}
377
378/// Escape a string for the double-quoted form the disassembler prints.
379fn escape_js_string(text: &str) -> String {
380 let mut out = String::with_capacity(text.len());
381 for c in text.chars() {
382 match c {
383 '"' => out.push_str("\\\""),
384 '\\' => out.push_str("\\\\"),
385 '\n' => out.push_str("\\n"),
386 '\r' => out.push_str("\\r"),
387 '\t' => out.push_str("\\t"),
388 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
389 c => out.push(c),
390 }
391 }
392 out
393}
394
395/// An operand of an instruction during compilation, before addresses are known.
396#[derive(Debug, Clone, PartialEq, Eq)]
397pub enum Operand {
398 /// No operand.
399 None,
400 /// A label, resolved to a byte offset.
401 Label(u32),
402 /// A local slot index.
403 Loc(u32),
404 /// An argument slot index.
405 Arg(u32),
406 /// A closure variable index.
407 VarRef(u32),
408 /// A constant pool index.
409 Const(u32),
410 /// An atom (an interned name), stored as its UTF-8 text before interning.
411 Atom(String),
412 /// A small unsigned immediate.
413 U8(u8),
414 /// A small signed immediate.
415 I8(i8),
416 /// A medium unsigned immediate.
417 U16(u16),
418 /// A medium signed immediate.
419 I16(i16),
420 /// A signed 32-bit immediate.
421 I32(i32),
422 /// An unsigned 32-bit immediate.
423 U32(u32),
424}
425
426/// A resolved instruction: opcode plus the operands encoded in its payload.
427#[derive(Debug, Clone, PartialEq)]
428pub struct Instruction {
429 /// The instruction.
430 pub op: Opcode,
431 /// Operands in the order the encoding stores them.
432 pub operands: Vec<Operand>,
433}
434
435impl Instruction {
436 /// An instruction with no operands.
437 pub fn new(op: Opcode) -> Instruction {
438 Instruction {
439 op,
440 operands: Vec::new(),
441 }
442 }
443
444 /// An instruction with one operand.
445 pub fn with(op: Opcode, operand: Operand) -> Instruction {
446 Instruction {
447 op,
448 operands: vec![operand],
449 }
450 }
451}
452
453/// Where a variable lives in the resolved function.
454#[derive(Debug, Clone, Copy, PartialEq, Eq)]
455pub enum Storage {
456 /// Argument slot.
457 Arg(u32),
458 /// Local slot.
459 Loc(u32),
460 /// Closure reference.
461 VarRef(u32),
462 /// Global, by atom.
463 Global,
464}
465
466/// A stretch of bytecode and the source position it came from.
467///
468/// One entry per run of instructions that share a position, ordered by `pc`, which is
469/// what [`Function::position_at`] binary searches. This is the port of the reference's
470/// `pc2line` table: it is how a stack trace says `file:line:col` for a frame that is
471/// deep inside a function rather than at its first statement.
472#[derive(Debug, Clone, Copy, PartialEq, Eq)]
473pub struct LineCol {
474 /// Byte offset in [`Function::code`] where this position takes over.
475 pub pc: u32,
476 /// 1-based line.
477 pub line: u32,
478 /// 1-based column, in UTF-16 code units like every other position here.
479 pub column: u32,
480}
481
482/// A compiled function.
483#[derive(Debug, Clone, PartialEq)]
484pub struct Function {
485 /// The function's name; `<eval>` for a script body.
486 pub name: String,
487 /// The declaration form.
488 pub kind: FunctionKind,
489 /// Whether the body is strict.
490 pub strict: bool,
491 /// Whether this came from an arrow function.
492 ///
493 /// An arrow has no `this` and no `new.target` of its own, so the runtime has to know
494 /// to look outward for both — an `eval` inside an arrow sees the enclosing function's
495 /// receiver, not the arrow's.
496 pub is_arrow: bool,
497 /// Whether the parameter list contains a default expression, and so gets a variable
498 /// environment of its own (`PARAM_SCOPE` in the compiler).
499 ///
500 /// The runtime needs this for two things a direct `eval` can observe: where a `var`
501 /// it declares belongs (the parameter environment, while the defaults are still being
502 /// evaluated), and which bindings a closure created there may see.
503 pub has_parameter_expressions: bool,
504 /// Where the body begins in source order, as `(line, column)`.
505 ///
506 /// A closure whose creation site is before this was created by a default expression,
507 /// so it sees the parameter environment and not the body's. Recorded as a position
508 /// rather than a bytecode offset because the instruction stream is rebuilt (frame
509 /// prologues are prepended) after the point where the compiler knows the boundary.
510 /// `(0, 0)` means "unknown", which is read as "the whole function is its body".
511 pub body_start: (u32, u32),
512 /// Parameters.
513 pub args: Vec<VarDef>,
514 /// How many parameters count towards `Function.prototype.length`.
515 ///
516 /// A parameter with a default or a rest parameter ends the count, because `.length`
517 /// is the arity the function can be called with before anything is substituted.
518 pub defined_args: u32,
519 /// Locals, including the implicit return-value slot named `<ret>`.
520 pub vars: Vec<VarDef>,
521 /// Captured variables of enclosing functions.
522 pub closure_vars: Vec<ClosureVar>,
523 /// Constant pool.
524 pub cpool: Vec<Constant>,
525 /// Atom table: the names this function mentions. The runtime shares one
526 /// interned table across the whole program; indexing it per function keeps
527 /// the bytecode self-contained and makes disassembly readable.
528 pub atoms: Vec<Atom>,
529 /// Resolved bytecode.
530 pub code: Vec<u8>,
531 /// Maximum value-stack depth.
532 pub stack_size: u32,
533 /// Source positions, ordered by bytecode offset.
534 pub positions: Vec<LineCol>,
535 /// Number of reference cells allocated on entry.
536 pub var_ref_count: u32,
537 /// Source text, kept for `Function.prototype.toString` and stack traces.
538 pub source: Option<String>,
539 /// Line of the function's declaration.
540 pub line: u32,
541 /// Column of the function's declaration.
542 pub column: u32,
543 /// File name, if known.
544 pub filename: Option<String>,
545 /// What each direct `eval(...)` call in this function can see.
546 ///
547 /// Slot resolution for ordinary code happens at compile time, but a direct `eval`
548 /// resolves names at *run* time, from a string the compiler never reads. Without
549 /// this table the runtime has to guess by name across the whole frame, which picks
550 /// the wrong binding when a name is declared twice in sibling scopes:
551 ///
552 /// ```text
553 /// for (let i = 0; i < 3; i++) f(eval); // this `i`
554 /// for (let i = 0; i < 3; i++) f(eval); // and this one
555 /// ```
556 ///
557 /// The compiler knows exactly which of them is in scope at each call, so it records
558 /// the answer here. It is data, not an instruction, so the bytecode stays identical
559 /// to the reference's.
560 pub eval_sites: Vec<EvalSite>,
561}
562
563/// One direct `eval(...)` call site and the bindings visible at it.
564#[derive(Debug, Clone, PartialEq)]
565pub struct EvalSite {
566 /// Source position of the call, which is how the runtime finds the site: it asks
567 /// for the position of the `call` instruction it is executing.
568 pub line: u32,
569 /// Column of the call.
570 pub column: u32,
571 /// Visible bindings, innermost scope first, so the first name match wins.
572 pub bindings: Vec<EvalVisible>,
573}
574
575/// One binding an `eval` can see.
576#[derive(Debug, Clone, PartialEq)]
577pub struct EvalVisible {
578 /// The name the eval would write.
579 pub name: String,
580 /// Whether it is a parameter of the function rather than a local.
581 pub is_arg: bool,
582 /// The slot index within that table.
583 pub index: u32,
584 /// How many frames up the binding lives: `0` is the function containing the
585 /// `eval`, `1` its caller's definition and so on. A direct `eval` sees the whole
586 /// chain, and the slot for a name declared in an enclosing function is only known
587 /// at compile time.
588 pub owner: u32,
589}
590
591impl Function {
592 /// Name the script this function belongs to.
593 ///
594 /// Nested functions inherit it, because a stack trace names every frame with the
595 /// file the code came from and the parser does not know file names — the host
596 /// does, after the source has already been compiled.
597 pub fn set_filename(&mut self, name: &str) {
598 self.filename = Some(name.to_string());
599 for constant in &mut self.cpool {
600 if let Constant::Function(inner) = constant {
601 inner.set_filename(name);
602 }
603 }
604 }
605
606 /// The source position of the instruction at `pc`.
607 ///
608 /// The last entry at or before `pc` wins, so a position applies until the next one
609 /// starts. `None` when the function carries no positions at all — a script compiled
610 /// without source information.
611 pub fn position_at(&self, pc: u32) -> Option<(u32, u32)> {
612 let index = match self.positions.binary_search_by_key(&pc, |entry| entry.pc) {
613 Ok(index) => index,
614 Err(0) => return None,
615 Err(index) => index - 1,
616 };
617 self.positions
618 .get(index)
619 .map(|entry| (entry.line, entry.column))
620 }
621
622 /// Decode the instruction stream back into instructions.
623 ///
624 /// Labels are already resolved, so a `label` operand is an absolute byte
625 /// offset.
626 pub fn instructions(&self) -> Vec<(usize, Instruction)> {
627 let mut out = Vec::new();
628 let mut pos = 0usize;
629 while pos < self.code.len() {
630 let Some(op) = Opcode::from_u8(self.code[pos]) else {
631 break;
632 };
633 let info = op.info();
634 let mut operands = Vec::new();
635 let payload = &self.code[pos + 1..(pos + info.size as usize).min(self.code.len())];
636 crate::disasm::decode_operands(info.format, payload, &mut operands);
637 out.push((pos, Instruction { op, operands }));
638 pos += info.size as usize;
639 }
640 out
641 }
642
643 /// Byte offsets that are the target of a jump, which the disassembler marks.
644 pub fn jump_targets(&self) -> Vec<usize> {
645 let mut targets = Vec::new();
646 for (pc, instruction) in self.instructions() {
647 if instruction.op.info().format.is_label()
648 && let Some(target) = instruction.jump_target(pc)
649 {
650 targets.push(target as usize);
651 }
652 }
653 targets
654 }
655
656 /// Total number of variable slots, as the serialiser stores them.
657 pub fn slot_count(&self) -> u32 {
658 self.args.len() as u32 + self.vars.len() as u32
659 }
660}
661
662impl fmt::Display for FunctionKind {
663 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
664 let text = match self {
665 FunctionKind::Normal => "function",
666 FunctionKind::Generator => "generator",
667 FunctionKind::Async => "async function",
668 FunctionKind::AsyncGenerator => "async generator",
669 };
670 f.write_str(text)
671 }
672}