use crate::ast::{Expr, Module, Script, Stmt};
use crate::value::Value;
mod annex_b;
mod binding;
mod chunk;
mod class;
mod delegate;
mod expression;
mod for_await;
mod function;
mod pattern;
mod statement;
pub use self::chunk::{
Chunk, Deletable, ExportEntry, ExportSource, ImportEntry, Instruction, NamePrefix, Scope,
ShortCircuit, SpreadCall, Template,
};
use self::chunk::Unpatched;
use crate::heap::{Heap, Mutability};
use crate::span::Span;
use crate::static_semantics::var_declared_names;
use std::rc::Rc;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompileError {
pub kind: ErrorKind,
pub span: Span,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ErrorKind {
Unsupported(&'static str),
TooManyConstants,
TooLong,
TooDeep,
BadPattern(&'static str),
}
impl CompileError {
pub fn message(&self) -> String {
match self.kind {
ErrorKind::Unsupported(what) => format!("{what} is not implemented yet"),
ErrorKind::BadPattern(why) => why.to_string(),
ErrorKind::TooManyConstants => "too many constants in one unit of code".to_string(),
ErrorKind::TooLong => "too many instructions in one unit of code".to_string(),
ErrorKind::TooDeep => "an expression nested too deeply to compile".to_string(),
}
}
}
pub fn compile_expression(expression: &Expr, heap: &mut Heap) -> Result<Chunk, CompileError> {
let mut compiler = Compiler::new(heap);
compiler.expression(expression)?;
compiler.chunk.emit(Instruction::SetCompletion);
Ok(compiler.finish())
}
pub fn compile_script(script: &Script, heap: &mut Heap) -> Result<Chunk, CompileError> {
compile_script_bindings(script, heap, Deletable::No)
}
pub fn compile_eval(script: &Script, heap: &mut Heap) -> Result<Chunk, CompileError> {
compile_script_bindings(script, heap, Deletable::Yes)
}
fn compile_script_bindings(
script: &Script,
heap: &mut Heap,
deletable: Deletable,
) -> Result<Chunk, CompileError> {
let mut compiler = Compiler::new(heap);
compiler.chunk.strict = script.is_strict;
compiler.deletable = deletable;
compiler.instantiate_globals(&script.body)?;
if !script.is_strict {
compiler.declare_block_functions(&script.body, &std::collections::HashSet::new())?;
}
compiler.declare_lexical_names(&script.body)?;
compiler.hoist_functions(&script.body)?;
compiler.statements(&script.body)?;
Ok(compiler.finish())
}
pub fn compile_module(module: &Module, heap: &mut Heap) -> Result<Chunk, CompileError> {
let (chunk, saw_await) = compile_module_body(module, heap, false)?;
match saw_await {
true => compile_module_body(module, heap, true).map(|(chunk, _)| chunk),
false => Ok(chunk),
}
}
fn compile_module_body(
module: &Module,
heap: &mut Heap,
asynchronous: bool,
) -> Result<(Chunk, bool), CompileError> {
let mut compiler = Compiler::new(heap);
compiler.chunk.strict = true;
compiler.chunk.is_async = asynchronous;
compiler.global_vars = false;
for item in &module.body {
let crate::ast::ModuleItem::Import(declaration) = item else {
continue;
};
declare_imports(&mut compiler, declaration);
}
let statements = module_statements(module)?;
for name in var_declared_names(&statements) {
compiler.declare(name.name);
}
compiler.declare_lexical_names(&statements)?;
let rejecting = asynchronous.then(|| compiler.chunk.emit_jump(Instruction::PushHandler));
let default_slot = match module.body.iter().find_map(default_expression) {
Some(DefaultKind::Lexical) => {
let slot = compiler.declare_lexical(DEFAULT_EXPORT, Mutability::Mutable);
compiler.chunk.emit(Instruction::Uninitialise(slot));
Some(slot)
}
Some(DefaultKind::Hoisted) | None => None,
};
compiler.hoist_functions(&statements)?;
let default_slot = match module.body.iter().find_map(hoisted_default) {
Some(statement) => {
let slot = compiler.declare_lexical(DEFAULT_EXPORT, Mutability::Mutable);
compiler.default_declaration(statement)?;
compiler.chunk.emit(Instruction::Initialise(slot));
compiler.chunk.emit(Instruction::Pop);
Some(slot)
}
None => default_slot,
};
for item in &module.body {
match item {
crate::ast::ModuleItem::Statement(statement) => compiler.statement(statement)?,
crate::ast::ModuleItem::Import(_) => {}
crate::ast::ModuleItem::Export(declaration) => match &declaration.kind {
crate::ast::ExportKind::Declaration(statement) => compiler.statement(statement)?,
crate::ast::ExportKind::Default(crate::ast::ExportDefault::Declaration(
statement,
)) => match declared_name(statement) {
Some(_) => compiler.statement(statement)?,
None => {
if !matches!(statement.kind, crate::ast::StmtKind::Function(_)) {
let slot = default_slot
.unwrap_or_else(|| unreachable_default_slot(&mut compiler));
compiler.default_declaration(statement)?;
compiler.chunk.emit(Instruction::Initialise(slot));
compiler.chunk.emit(Instruction::Pop);
}
}
},
crate::ast::ExportKind::Default(crate::ast::ExportDefault::Expression(value)) => {
let slot =
default_slot.unwrap_or_else(|| unreachable_default_slot(&mut compiler));
compiler.named_evaluation("default", value)?;
compiler.chunk.emit(Instruction::Initialise(slot));
compiler.chunk.emit(Instruction::Pop);
}
crate::ast::ExportKind::Named(_) => {}
crate::ast::ExportKind::All { .. } | crate::ast::ExportKind::NamedFrom { .. } => {}
},
}
}
for item in &module.body {
let crate::ast::ModuleItem::Export(declaration) = item else {
continue;
};
record_exports(&mut compiler, declaration)?;
}
if let Some(rejecting) = rejecting {
compiler.constant(Value::Undefined)?;
compiler.chunk.emit(Instruction::Return);
compiler.chunk.patch(rejecting)?;
compiler.chunk.emit(Instruction::AsyncReject);
}
let saw_await = compiler.saw_top_level_await;
Ok((compiler.finish(), saw_await))
}
fn declare_imports(compiler: &mut Compiler<'_>, declaration: &crate::ast::ImportDeclaration) {
use crate::ast::ImportClause;
let specifier: Box<str> = String::from_utf16_lossy(&declaration.specifier).into();
let Some(clause) = &declaration.clause else {
compiler.chunk.imports.push(chunk::ImportEntry {
specifier,
import_name: None,
slot: None,
});
return;
};
let mut names: Vec<(&str, Option<Box<str>>)> = Vec::new();
match clause {
ImportClause::Default(name) => names.push((&name.name, Some("default".into()))),
ImportClause::Namespace(name) => names.push((&name.name, None)),
ImportClause::Named(specifiers) => {
for entry in specifiers {
names.push((&entry.local.name, Some(export_name(&entry.imported))));
}
}
ImportClause::DefaultAndNamespace(default, namespace) => {
names.push((&default.name, Some("default".into())));
names.push((&namespace.name, None));
}
ImportClause::DefaultAndNamed(default, specifiers) => {
names.push((&default.name, Some("default".into())));
for entry in specifiers {
names.push((&entry.local.name, Some(export_name(&entry.imported))));
}
}
}
for (local, imported) in names {
let slot = compiler.declare_lexical(local, Mutability::Const);
compiler.chunk.imports.push(chunk::ImportEntry {
specifier: specifier.clone(),
import_name: imported,
slot: Some(slot),
});
}
}
fn record_exports(
compiler: &mut Compiler<'_>,
declaration: &crate::ast::ExportDeclaration,
) -> Result<(), CompileError> {
use crate::ast::ExportKind;
let specifiers: Vec<(Box<str>, Box<str>)> = match &declaration.kind {
ExportKind::Named(specifiers) => specifiers
.iter()
.map(|entry| (export_name(&entry.local), export_name(&entry.exported)))
.collect(),
ExportKind::Declaration(statement) => {
let one = std::slice::from_ref(statement);
let mut names: Vec<Box<str>> = var_declared_names(one)
.into_iter()
.chain(crate::static_semantics::lexically_declared_names(one))
.map(|name| Box::<str>::from(name.name))
.collect();
if let crate::ast::StmtKind::Function(function) = &statement.kind
&& let Some(name) = &function.name
{
names.push(Box::<str>::from(&*name.name));
}
names.sort();
names.dedup();
names.into_iter().map(|name| (name.clone(), name)).collect()
}
ExportKind::Default(what) => {
let local: Box<str> = match what {
crate::ast::ExportDefault::Expression(_) => DEFAULT_EXPORT.into(),
crate::ast::ExportDefault::Declaration(statement) => {
match declared_name(statement) {
Some(name) => name,
None => DEFAULT_EXPORT.into(),
}
}
};
vec![(local, "default".into())]
}
ExportKind::NamedFrom {
specifiers,
specifier,
..
} => {
let from: Box<str> = String::from_utf16_lossy(specifier).into();
compiler.chunk.imports.push(chunk::ImportEntry {
specifier: from.clone(),
import_name: None,
slot: None,
});
for entry in specifiers {
compiler.chunk.exports.push(chunk::ExportEntry {
export_name: export_name(&entry.exported),
from: chunk::ExportSource::Indirect {
specifier: from.clone(),
import_name: Some(export_name(&entry.local)),
},
});
}
return Ok(());
}
ExportKind::All {
exported,
specifier,
..
} => {
let from: Box<str> = String::from_utf16_lossy(specifier).into();
match exported {
Some(name) => compiler.chunk.exports.push(chunk::ExportEntry {
export_name: export_name(name),
from: chunk::ExportSource::Indirect {
specifier: from,
import_name: None,
},
}),
None => compiler.chunk.star_exports.push(from),
}
return Ok(());
}
};
for (local, exported) in specifiers {
let Some(slot) = compiler.resolve(&local) else {
return Err(unsupported(
"an `export` of a name this module does not declare",
declaration.span,
));
};
let from = match compiler
.chunk
.imports
.iter()
.find(|entry| entry.slot == Some(slot))
{
Some(entry) if entry.import_name.is_some() => chunk::ExportSource::Indirect {
specifier: entry.specifier.clone(),
import_name: entry.import_name.clone(),
},
Some(_) | None => chunk::ExportSource::Local(slot),
};
compiler.chunk.exports.push(chunk::ExportEntry {
export_name: exported,
from,
});
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DefaultKind {
Lexical,
Hoisted,
}
fn default_expression(item: &crate::ast::ModuleItem) -> Option<DefaultKind> {
let crate::ast::ModuleItem::Export(declaration) = item else {
return None;
};
match &declaration.kind {
crate::ast::ExportKind::Default(crate::ast::ExportDefault::Expression(_)) => {
Some(DefaultKind::Lexical)
}
crate::ast::ExportKind::Default(crate::ast::ExportDefault::Declaration(statement)) => {
match (&statement.kind, declared_name(statement)) {
(_, Some(_)) => None,
(crate::ast::StmtKind::Function(_), None) => Some(DefaultKind::Hoisted),
(_, None) => Some(DefaultKind::Lexical),
}
}
_ => None,
}
}
fn hoisted_default(item: &crate::ast::ModuleItem) -> Option<&Stmt> {
let crate::ast::ModuleItem::Export(declaration) = item else {
return None;
};
let crate::ast::ExportKind::Default(crate::ast::ExportDefault::Declaration(statement)) =
&declaration.kind
else {
return None;
};
match default_expression(item)? {
DefaultKind::Hoisted => Some(statement),
DefaultKind::Lexical => None,
}
}
fn unreachable_default_slot(compiler: &mut Compiler<'_>) -> u32 {
compiler.declare_lexical(DEFAULT_EXPORT, Mutability::Mutable)
}
const DEFAULT_EXPORT: &str = "*default*";
impl Compiler<'_> {
fn default_declaration(&mut self, statement: &Stmt) -> Result<(), CompileError> {
match &statement.kind {
crate::ast::StmtKind::Function(function) => self.make_function(
function,
self::function::Naming::of("default"),
statement.span,
),
crate::ast::StmtKind::Class(class) => {
self.class(class, self::function::Naming::of("default"), statement.span)
}
_ => Err(unsupported(
"an `export default` of something that is not a declaration",
statement.span,
)),
}
}
}
fn declared_name(statement: &Stmt) -> Option<Box<str>> {
match &statement.kind {
crate::ast::StmtKind::Function(function) => {
function.name.as_ref().map(|name| Box::from(&*name.name))
}
crate::ast::StmtKind::Class(class) => {
class.name.as_ref().map(|name| Box::from(&*name.name))
}
_ => None,
}
}
fn export_name(name: &crate::ast::ModuleExportName) -> Box<str> {
match name {
crate::ast::ModuleExportName::Identifier(text) => text.clone(),
crate::ast::ModuleExportName::String(units) => String::from_utf16_lossy(units).into(),
}
}
fn module_statements(module: &Module) -> Result<Vec<Stmt>, CompileError> {
let mut statements = Vec::new();
for item in &module.body {
match item {
crate::ast::ModuleItem::Statement(statement) => statements.push(statement.clone()),
crate::ast::ModuleItem::Import(_) => {}
crate::ast::ModuleItem::Export(declaration) => match &declaration.kind {
crate::ast::ExportKind::Declaration(statement) => {
statements.push(statement.clone())
}
crate::ast::ExportKind::Default(crate::ast::ExportDefault::Declaration(
statement,
)) => {
if declared_name(statement).is_some() {
statements.push(statement.clone());
}
}
crate::ast::ExportKind::Named(_)
| crate::ast::ExportKind::Default(crate::ast::ExportDefault::Expression(_)) => {}
crate::ast::ExportKind::All { .. } | crate::ast::ExportKind::NamedFrom { .. } => {}
},
}
}
Ok(statements)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EvalVars {
Global,
Own,
Caller,
}
pub fn compile_direct_eval(
script: &Script,
heap: &mut Heap,
chain: Vec<Vec<crate::heap::Binding>>,
vars: EvalVars,
dynamic: bool,
) -> Result<Chunk, CompileError> {
let mut compiler = Compiler::new(heap);
compiler.with_depth = u32::from(dynamic);
compiler.chunk.strict = script.is_strict;
compiler.outer = chain
.into_iter()
.map(|level| level.into_iter().map(Local::from).collect())
.collect();
compiler.seeded_scopes = compiler.outer.len();
compiler.global_vars = vars == EvalVars::Global;
compiler.deletable = Deletable::Yes;
match vars {
EvalVars::Global => compiler.instantiate_globals(&script.body)?,
EvalVars::Own => {
for name in var_declared_names(&script.body) {
compiler.declare(name.name);
}
}
EvalVars::Caller => {
if let Some(name) = var_declared_names(&script.body).into_iter().next() {
return Err(unsupported(
"a sloppy `var` inside a direct eval in a function",
name.span,
));
}
if let Some(statement) = script
.body
.iter()
.find(|statement| matches!(statement.kind, crate::ast::StmtKind::Function(_)))
{
return Err(unsupported(
"a sloppy function declaration inside a direct eval in a function",
statement.span,
));
}
}
}
if !script.is_strict {
compiler.declare_block_functions(&script.body, &std::collections::HashSet::new())?;
}
compiler.declare_lexical_names(&script.body)?;
compiler.hoist_functions(&script.body)?;
compiler.statements(&script.body)?;
Ok(compiler.finish())
}
#[derive(Debug, Clone)]
struct Local {
name: Box<str>,
live: bool,
mutability: Mutability,
}
impl Local {
fn answers_to(&self, name: &str) -> bool {
self.live && &*self.name == name
}
}
impl From<crate::heap::Binding> for Local {
fn from(binding: crate::heap::Binding) -> Self {
Self {
name: binding.name,
live: true,
mutability: binding.mutability,
}
}
}
struct Compiler<'a> {
chunk: Chunk,
heap: &'a mut Heap,
locals: Vec<Local>,
breaks: Vec<Vec<Unpatched>>,
arguments_slot: Option<u32>,
uses_arguments: bool,
saw_direct_eval: bool,
inside_eval: bool,
scope_marks: Vec<usize>,
continues: Vec<Option<Vec<Unpatched>>>,
depth: u32,
outer: Vec<Vec<Local>>,
this_binding: Option<ThisSlot>,
derived_fields: Option<u32>,
is_script: bool,
global_vars: bool,
deletable: Deletable,
with_depth: u32,
seeded_scopes: usize,
high_water: usize,
saw_top_level_await: bool,
hoisted: Vec<Span>,
block_functions: Vec<(Span, BlockFunctionTarget)>,
labels: Vec<(Box<str>, usize)>,
chains: Vec<Vec<Unpatched>>,
unwinds: Vec<Unwind>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BlockFunctionTarget {
Global(u32),
Slot(u32),
}
#[derive(Clone)]
struct Unwind {
outer: usize,
what: Crossing,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Closing {
Sync,
Awaited,
}
#[derive(Clone)]
enum Crossing {
Handlers(u32),
Scope,
Finally(Rc<[Stmt]>),
Iterator(u32, Closing),
Operand,
}
impl<'a> Compiler<'a> {
fn new(heap: &'a mut Heap) -> Self {
Self {
chunk: Chunk::default(),
heap,
locals: Vec::new(),
breaks: Vec::new(),
arguments_slot: None,
uses_arguments: false,
saw_direct_eval: false,
inside_eval: false,
scope_marks: Vec::new(),
continues: Vec::new(),
saw_top_level_await: false,
hoisted: Vec::new(),
block_functions: Vec::new(),
labels: Vec::new(),
unwinds: Vec::new(),
chains: Vec::new(),
high_water: 0,
depth: 0,
outer: Vec::new(),
this_binding: None,
derived_fields: None,
is_script: true,
global_vars: true,
deletable: Deletable::No,
seeded_scopes: 0,
with_depth: 0,
}
}
pub(super) fn load_this(&mut self) {
match self.this_binding {
Some(at) => self.chunk.emit(Instruction::LoadThisBinding {
depth: at.depth,
index: at.index,
}),
None => self.chunk.emit(Instruction::LoadThis),
}
}
fn finish(self) -> Chunk {
let mut chunk = self.chunk;
chunk.locals = self.high_water;
chunk.bindings = bindings_of(&self.locals);
chunk
}
fn instantiate_globals(&mut self, body: &[Stmt]) -> Result<(), CompileError> {
for name in var_declared_names(body) {
let index = self.name(name.name)?;
self.chunk.emit(Instruction::CheckGlobalVar(index));
}
for statement in body {
let crate::ast::StmtKind::Function(function) = &statement.kind else {
continue;
};
let Some(name) = &function.name else {
continue;
};
let index = self.name(&name.name)?;
self.chunk.emit(Instruction::CheckGlobalFunction(index));
}
for name in var_declared_names(body) {
let index = self.name(name.name)?;
let deletable = self.deletable;
self.chunk.emit(Instruction::DeclareGlobal {
name: index,
deletable,
});
}
Ok(())
}
pub(super) fn declare_block_functions_of(
&mut self,
body: &[Stmt],
parameters: &crate::ast::FormalParameters,
) -> Result<(), CompileError> {
if self.chunk.strict {
return Ok(());
}
let names: std::collections::HashSet<&str> = parameters
.items
.iter()
.map(|item| &item.target)
.chain(parameters.rest.as_deref())
.flat_map(crate::static_semantics::bound_names)
.map(|declared| declared.name)
.collect();
self.declare_block_functions(body, &names)
}
fn declare_block_functions(
&mut self,
body: &[Stmt],
parameters: &std::collections::HashSet<&str>,
) -> Result<(), CompileError> {
for function in annex_b::block_functions(body, parameters) {
let target = match self.global_vars {
true => {
let index = self.name(function.name)?;
let deletable = self.deletable;
self.chunk.emit(Instruction::DeclareGlobal {
name: index,
deletable,
});
BlockFunctionTarget::Global(index)
}
false => BlockFunctionTarget::Slot(self.declare(function.name)),
};
self.block_functions.push((function.span, target));
}
Ok(())
}
fn declare(&mut self, name: &str) -> u32 {
if let Some(slot) = self.resolve(name) {
return slot;
}
self.declare_shadowing(name)
}
fn resolve(&self, name: &str) -> Option<u32> {
let at = self
.locals
.iter()
.rposition(|local| local.answers_to(name))?;
u32::try_from(at).ok()
}
fn resolve_in_scope(&self, name: &str) -> Option<u32> {
let mark = self.scope_marks.last().copied().unwrap_or(0);
let at = self
.locals
.iter()
.rposition(|local| local.answers_to(name))
.filter(|at| *at >= mark)?;
u32::try_from(at).ok()
}
fn enter_scope(&mut self) -> usize {
let mark = self.locals.len();
self.scope_marks.push(mark);
mark
}
fn enter_environment(&mut self) -> Environment {
let outer = self.breaks.len();
self.open_environment(outer)
}
fn enter_iteration_environment(&mut self) -> Environment {
let outer = self.breaks.len() + 1;
self.open_environment(outer)
}
fn open_environment(&mut self, outer: usize) -> Environment {
let held = std::mem::take(&mut self.locals);
self.outer.push(held);
if let Some(slot) = &mut self.this_binding {
slot.depth += 1;
}
self.scope_marks.push(0);
self.unwinds.push(Unwind {
outer,
what: Crossing::Scope,
});
Environment {
scope: self.chunk.emit_jump(Instruction::PushScope),
copies: Vec::new(),
}
}
fn enter_with_environment(&mut self) -> Environment {
let outer = self.breaks.len();
let held = std::mem::take(&mut self.locals);
self.outer.push(held);
self.scope_marks.push(0);
self.unwinds.push(Unwind {
outer,
what: Crossing::Scope,
});
self.with_depth += 1;
Environment {
scope: self.chunk.emit_jump(Instruction::PushWithScope),
copies: Vec::new(),
}
}
fn leave_with_environment(&mut self, environment: Environment) -> Result<(), CompileError> {
self.with_depth = self.with_depth.saturating_sub(1);
self.close_environment(environment, true)
}
fn copy_environment(&mut self, environment: &mut Environment) {
environment
.copies
.push(self.chunk.emit_jump(Instruction::CopyScope));
}
fn leave_environment(&mut self, environment: Environment) -> Result<(), CompileError> {
self.close_environment(environment, true)
}
fn leave_environment_already_popped(
&mut self,
environment: Environment,
) -> Result<(), CompileError> {
self.close_environment(environment, false)
}
fn close_environment(
&mut self,
environment: Environment,
pop: bool,
) -> Result<(), CompileError> {
let slots = u32::try_from(self.locals.len()).map_err(|_| CompileError {
kind: ErrorKind::TooLong,
span: Span::new(0, 0),
})?;
let names = bindings_of(&self.locals);
let index = self.chunk.add_scope(chunk::Scope { slots, names })?;
self.chunk.patch_scope(environment.scope, index);
for copy in environment.copies {
self.chunk.patch_scope(copy, index);
}
if pop {
self.chunk.emit(Instruction::PopScope);
}
self.unwinds.pop();
self.scope_marks.pop();
if let Some(slot) = &mut self.this_binding {
slot.depth = slot.depth.saturating_sub(1);
}
let Some(held) = self.outer.pop() else {
return Err(CompileError {
kind: ErrorKind::TooDeep,
span: Span::new(0, 0),
});
};
self.locals = held;
Ok(())
}
fn local(&self, name: &str) -> Option<&Local> {
self.locals
.iter()
.rev()
.find(|local| local.answers_to(name))
}
fn declare_lexical(&mut self, name: &str, mutability: Mutability) -> u32 {
let slot = self.declare_shadowing(name);
if let Some(local) = self.locals.last_mut() {
local.mutability = mutability;
}
slot
}
fn leave_scope(&mut self, mark: usize) {
self.scope_marks.pop();
for local in self.locals.iter_mut().skip(mark) {
local.live = false;
}
}
fn binding(&self, name: &str) -> Option<Where> {
if let Some(index) = self.resolve(name) {
let mutability = self
.local(name)
.map_or(Mutability::Mutable, |local| local.mutability);
return Some(Where {
depth: 0,
index,
mutability,
});
}
for (back, scope) in self.outer.iter().rev().enumerate() {
let Some(at) = scope.iter().rposition(|local| local.answers_to(name)) else {
continue;
};
let depth = u32::try_from(back + 1).ok()?; let index = u32::try_from(at).ok()?; let mutability = scope
.get(at)
.map_or(Mutability::Mutable, |local| local.mutability);
return Some(Where {
depth,
index,
mutability,
});
}
None
}
fn load(&mut self, binding: Where) {
self.chunk
.emit(Instruction::LoadVariable(binding.depth, binding.index));
}
fn store(&mut self, binding: Where) {
self.chunk
.emit(Instruction::StoreVariable(binding.depth, binding.index));
}
pub(super) fn at_global_scope(&self) -> bool {
self.global_vars && self.outer.len() == self.seeded_scopes
}
pub(super) fn name(&mut self, name: &str) -> Result<u32, CompileError> {
let units: Vec<u16> = name.encode_utf16().collect();
let interned = self.heap.intern(&units);
self.chunk.add_constant(Value::String(interned))
}
fn note_arguments(&mut self, name: &str, binding: Option<Where>) {
if name != "arguments" {
return;
}
match binding {
Some(found) if found.depth == self.own_depth() => {
self.uses_arguments = Some(found.index) == self.arguments_slot;
}
Some(_) => self.chunk.outer_arguments = true,
None => {}
}
}
fn own_depth(&self) -> u32 {
u32::try_from(self.outer.len().saturating_sub(self.seeded_scopes)).unwrap_or(u32::MAX)
}
pub(super) fn names_are_dynamic(&self) -> bool {
self.with_depth > 0 || self.inside_eval
}
pub(super) fn inside_with(&self) -> bool {
self.with_depth > 0
}
pub(super) fn load_name(&mut self, name: &str) -> Result<(), CompileError> {
let binding = self.binding(name);
self.note_arguments(name, binding);
if self.names_are_dynamic() {
let index = self.name(name)?;
self.chunk.emit(Instruction::LoadName(index));
return Ok(());
}
match binding {
Some(binding) => {
self.load(binding);
Ok(())
}
None => {
let index = self.name(name)?;
self.chunk.emit(Instruction::LoadGlobal(index));
Ok(())
}
}
}
pub(super) fn load_private_name(&mut self, name: &str) -> Result<(), CompileError> {
let slot = crate::compile::class::private_name_slot(name);
let Some(binding) = self.binding(&slot) else {
return Err(unsupported(
"a private name outside a class body",
Span::new(0, 0),
));
};
self.load(binding);
Ok(())
}
fn private_slot(&mut self, slot: &str, write: bool) -> Result<(), CompileError> {
let Some(binding) = self.binding(slot) else {
return Err(unsupported(
"a private method outside a class body",
Span::new(0, 0),
));
};
match write {
true => self.store(binding),
false => self.load(binding),
}
Ok(())
}
pub(super) fn load_private_slot(&mut self, slot: &str) -> Result<(), CompileError> {
self.private_slot(slot, false)
}
pub(super) fn store_private_slot(&mut self, slot: &str) -> Result<(), CompileError> {
self.private_slot(slot, true)
}
pub(super) fn store_name(&mut self, name: &str) -> Result<(), CompileError> {
let binding = self.binding(name);
self.note_arguments(name, binding);
if self.names_are_dynamic() {
let index = self.name(name)?;
self.chunk.emit(Instruction::StoreName(index));
return Ok(());
}
match binding {
Some(binding) if !binding.mutability.writes() => {
if binding.mutability.refusal_throws(self.chunk.strict) {
self.chunk.emit(Instruction::ThrowImmutableAssignment);
}
Ok(())
}
Some(binding) => {
self.store(binding);
Ok(())
}
None => {
let index = self.name(name)?;
self.chunk.emit(Instruction::StoreGlobal(index));
Ok(())
}
}
}
}
impl Compiler<'_> {
pub(super) fn declare_shadowing(&mut self, name: &str) -> u32 {
let slot = u32::try_from(self.locals.len()).unwrap_or(u32::MAX);
self.locals.push(Local {
name: name.into(),
live: true,
mutability: Mutability::Mutable,
});
self.high_water = self.high_water.max(self.locals.len());
slot
}
fn declare_hidden(&mut self, what: &str) -> u32 {
let name = format!("%{what}{}", self.locals.len());
self.declare_shadowing(&name)
}
fn here(&self) -> Result<u32, CompileError> {
u32::try_from(self.chunk.code.len()).map_err(|_| CompileError {
kind: ErrorKind::TooLong,
span: Span::new(0, 0),
})
}
}
const MAX_EXPRESSION_DEPTH: u32 = 64;
const THIS_BINDING: &str = "%this";
struct Environment {
scope: chunk::Unpatched,
copies: Vec<chunk::Unpatched>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Where {
depth: u32,
index: u32,
mutability: Mutability,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ThisSlot {
depth: u32,
index: u32,
}
fn bindings_of(locals: &[Local]) -> Rc<[crate::heap::Binding]> {
locals
.iter()
.map(|local| crate::heap::Binding {
name: local.name.clone(),
mutability: local.mutability,
})
.collect()
}
pub(super) fn lexical_mutability(immutable: bool) -> Mutability {
match immutable {
true => Mutability::Const,
false => Mutability::Mutable,
}
}
fn unsupported(what: &'static str, span: Span) -> CompileError {
CompileError {
kind: ErrorKind::Unsupported(what),
span,
}
}
#[cfg(test)]
mod tests;