use crate::opcode::Opcode;
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Atom {
Str(String),
Index(u32),
}
impl Atom {
pub fn from_text(text: &str) -> Atom {
match canonical_array_index(text) {
Some(index) => Atom::Index(index),
None => Atom::Str(text.to_string()),
}
}
pub fn as_str(&self) -> Option<&str> {
match self {
Atom::Str(text) => Some(text),
Atom::Index(_) => None,
}
}
}
impl fmt::Display for Atom {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Atom::Str(text) => write!(f, "{text}"),
Atom::Index(index) => write!(f, "{index}"),
}
}
}
fn canonical_array_index(text: &str) -> Option<u32> {
if text.is_empty() || text.len() > 10 {
return None;
}
let bytes = text.as_bytes();
if !bytes.iter().all(u8::is_ascii_digit) {
return None;
}
if bytes[0] == b'0' && bytes.len() != 1 {
return None;
}
let value: u32 = text.parse().ok()?;
(value <= 0x7fff_ffff).then_some(value)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FunctionKind {
Normal,
Generator,
Async,
AsyncGenerator,
}
impl FunctionKind {
pub fn is_generator(self) -> bool {
matches!(self, FunctionKind::Generator | FunctionKind::AsyncGenerator)
}
pub fn is_async(self) -> bool {
matches!(self, FunctionKind::Async | FunctionKind::AsyncGenerator)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VarKind {
Normal,
FunctionDecl,
NewFunctionDecl,
Catch,
FunctionName,
PrivateField,
PrivateMethod,
PrivateGetter,
PrivateSetter,
PrivateGetterSetter,
GlobalFunctionDecl,
Using,
UsingMethod,
With,
}
impl VarKind {
pub fn label(self) -> &'static str {
match self {
VarKind::Catch => "catch",
VarKind::FunctionDecl | VarKind::NewFunctionDecl | VarKind::GlobalFunctionDecl => {
"function"
}
_ => "",
}
}
pub fn is_hoisted_declaration(self) -> bool {
matches!(self, VarKind::FunctionDecl | VarKind::NewFunctionDecl)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VarDef {
pub name: String,
pub is_const: bool,
pub is_lexical: bool,
pub kind: VarKind,
pub is_captured: bool,
pub scope_level: u32,
pub scope_next: Option<i32>,
}
impl VarDef {
pub fn var(name: impl Into<String>) -> VarDef {
VarDef {
name: name.into(),
is_const: false,
is_lexical: false,
kind: VarKind::Normal,
is_captured: false,
scope_level: 0,
scope_next: None,
}
}
pub fn needs_check(&self) -> bool {
self.is_lexical
}
pub fn lexical(name: impl Into<String>) -> VarDef {
VarDef {
is_lexical: true,
..VarDef::var(name)
}
}
pub fn constant(name: impl Into<String>) -> VarDef {
VarDef {
is_lexical: true,
is_const: true,
..VarDef::var(name)
}
}
pub fn label(&self) -> &'static str {
let kind = self.kind.label();
if !kind.is_empty() {
return kind;
}
if self.is_const {
"const"
} else if self.is_lexical {
"let"
} else {
"var"
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClosureType {
Local,
Arg,
Ref,
GlobalRef,
GlobalDecl,
Global,
ModuleDecl,
ModuleImport,
}
impl ClosureType {
pub fn describe(self) -> &'static str {
match self {
ClosureType::Local => "loc",
ClosureType::Arg => "arg",
ClosureType::Ref => "ref",
ClosureType::GlobalDecl => "global_decl",
ClosureType::Global => "global",
ClosureType::ModuleDecl => "module_decl",
ClosureType::ModuleImport => "module_import",
ClosureType::GlobalRef => "global_ref",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClosureVar {
pub name: String,
pub is_const: bool,
pub is_lexical: bool,
pub closure_type: ClosureType,
pub var_idx: u16,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Constant {
Number(f64),
String(String),
BigInt {
digits: String,
radix: u32,
},
Function(Box<Function>),
Template {
cooked: Vec<Option<String>>,
raw: Vec<String>,
},
}
impl Constant {
pub fn describe(&self) -> String {
match self {
Constant::Number(n) => format_number(*n),
Constant::String(s) => format!("\"{}\"", escape_js_string(s)),
Constant::BigInt { digits, .. } => format!("{digits}n"),
Constant::Function(f) => {
if f.name.is_empty() {
"[bytecode <null>]".to_string()
} else {
format!("[bytecode {}]", f.name)
}
}
Constant::Template { cooked, .. } => {
let parts: Vec<String> = cooked
.iter()
.map(|q| q.clone().unwrap_or_else(|| "undefined".to_string()))
.collect();
format!("template object [{}]", parts.join(", "))
}
}
}
}
fn format_number(value: f64) -> String {
if value.is_nan() {
return "NaN".to_string();
}
if value.is_infinite() {
return if value > 0.0 {
"inf".to_string()
} else {
"-inf".to_string()
};
}
if value == value.trunc() && value.abs() < 1e21 {
return format!("{}", value as i64);
}
format!("{value}")
}
fn escape_js_string(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Operand {
None,
Label(u32),
Loc(u32),
Arg(u32),
VarRef(u32),
Const(u32),
Atom(String),
U8(u8),
I8(i8),
U16(u16),
I16(i16),
I32(i32),
U32(u32),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Instruction {
pub op: Opcode,
pub operands: Vec<Operand>,
}
impl Instruction {
pub fn new(op: Opcode) -> Instruction {
Instruction {
op,
operands: Vec::new(),
}
}
pub fn with(op: Opcode, operand: Operand) -> Instruction {
Instruction {
op,
operands: vec![operand],
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Storage {
Arg(u32),
Loc(u32),
VarRef(u32),
Global,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LineCol {
pub pc: u32,
pub line: u32,
pub column: u32,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Function {
pub name: String,
pub kind: FunctionKind,
pub strict: bool,
pub is_arrow: bool,
pub has_parameter_expressions: bool,
pub body_start: (u32, u32),
pub args: Vec<VarDef>,
pub defined_args: u32,
pub vars: Vec<VarDef>,
pub closure_vars: Vec<ClosureVar>,
pub cpool: Vec<Constant>,
pub atoms: Vec<Atom>,
pub code: Vec<u8>,
pub stack_size: u32,
pub positions: Vec<LineCol>,
pub var_ref_count: u32,
pub source: Option<String>,
pub line: u32,
pub column: u32,
pub filename: Option<String>,
pub eval_sites: Vec<EvalSite>,
pub module: Option<Box<ModuleMeta>>,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ModuleMeta {
pub requests: Vec<ModuleRequest>,
pub imports: Vec<ImportEntry>,
pub exports: Vec<ExportEntry>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ModuleRequest {
pub specifier: String,
pub attributes: Vec<(String, String)>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ImportEntry {
pub module: u32,
pub name: String,
pub var_idx: u32,
pub is_star: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ExportEntry {
Local {
export_name: String,
var_idx: u32,
},
Indirect {
export_name: String,
module: u32,
import_name: String,
},
Star {
module: u32,
},
StarAs {
export_name: String,
module: u32,
},
}
#[derive(Debug, Clone, PartialEq)]
pub struct EvalSite {
pub line: u32,
pub column: u32,
pub bindings: Vec<EvalVisible>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct EvalVisible {
pub name: String,
pub is_arg: bool,
pub index: u32,
pub owner: u32,
}
impl Function {
pub fn set_filename(&mut self, name: &str) {
self.filename = Some(name.to_string());
for constant in &mut self.cpool {
if let Constant::Function(inner) = constant {
inner.set_filename(name);
}
}
}
pub fn position_at(&self, pc: u32) -> Option<(u32, u32)> {
let index = match self.positions.binary_search_by_key(&pc, |entry| entry.pc) {
Ok(index) => index,
Err(0) => return None,
Err(index) => index - 1,
};
self.positions
.get(index)
.map(|entry| (entry.line, entry.column))
}
pub fn instructions(&self) -> Vec<(usize, Instruction)> {
let mut out = Vec::new();
let mut pos = 0usize;
while pos < self.code.len() {
let Some(op) = Opcode::from_u8(self.code[pos]) else {
break;
};
let info = op.info();
let mut operands = Vec::new();
let payload = &self.code[pos + 1..(pos + info.size as usize).min(self.code.len())];
crate::disasm::decode_operands(info.format, payload, &mut operands);
out.push((pos, Instruction { op, operands }));
pos += info.size as usize;
}
out
}
pub fn jump_targets(&self) -> Vec<usize> {
let mut targets = Vec::new();
for (pc, instruction) in self.instructions() {
if instruction.op.info().format.is_label()
&& let Some(target) = instruction.jump_target(pc)
{
targets.push(target as usize);
}
}
targets
}
pub fn slot_count(&self) -> u32 {
self.args.len() as u32 + self.vars.len() as u32
}
}
impl fmt::Display for FunctionKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let text = match self {
FunctionKind::Normal => "function",
FunctionKind::Generator => "generator",
FunctionKind::Async => "async function",
FunctionKind::AsyncGenerator => "async generator",
};
f.write_str(text)
}
}