use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use crate::ast::*;
const IMP: &str = "%imp";
const META: &str = "%meta";
const REG: &str = "%reg";
pub const IMPORT_FN: &str = "%esm.import";
pub const CJS_FREE_PREFIX: &str = "%esm.cjs.";
const CJS_NAMES: &[&str] = &[
"require",
"module",
"exports",
"__filename",
"__dirname",
"arguments",
];
#[derive(Debug, Clone)]
pub struct ImportEntry {
pub request: usize,
pub import_name: Option<String>,
pub local: String,
pub clause: Span,
}
#[derive(Debug, Clone)]
pub struct IndirectExport {
pub export_name: String,
pub request: usize,
pub import_name: Option<String>,
}
#[derive(Debug, Clone, Default)]
pub struct ModuleInfo {
pub requests: Vec<(String, Vec<(String, String)>)>,
pub imports: Vec<ImportEntry>,
pub local_exports: Vec<(String, String)>,
pub indirect_exports: Vec<IndirectExport>,
pub star_exports: Vec<usize>,
pub has_tla: bool,
}
fn syntax(msg: impl std::fmt::Display) -> String {
format!("SyntaxError: {msg}")
}
fn lexical_names(stmts: &[Stmt], out: &mut Vec<String>) {
for s in stmts {
match &s.kind {
StmtKind::Decl { kind, decls } if *kind != DeclKind::Var => {
for d in decls {
crate::compiler::pattern_names(&d.target, out);
}
}
StmtKind::ClassDecl(c) => out.extend(c.name.clone()),
StmtKind::FuncDecl { name, .. } => out.push(name.clone()),
_ => {}
}
}
}
fn body_names(stmts: &[Stmt], out: &mut Vec<String>) {
for s in stmts {
crate::compiler::collect_var_names(s, out);
}
lexical_names(stmts, out);
}
fn add_request(info: &mut ModuleInfo, spec: &str, attrs: &[(String, String)]) -> usize {
if let Some(i) = info
.requests
.iter()
.position(|(s, a)| s == spec && a.as_slice() == attrs)
{
return i;
}
info.requests.push((spec.to_string(), attrs.to_vec()));
info.requests.len() - 1
}
pub fn analyze(stmts: &[Stmt]) -> Result<ModuleInfo, String> {
let mut info = ModuleInfo::default();
let mut declared: Vec<String> = Vec::new();
for s in stmts {
match &s.kind {
StmtKind::Export(ExportDecl::Decl(d))
| StmtKind::Export(ExportDecl::DefaultDecl(d)) => {
crate::compiler::collect_var_names(d, &mut declared);
lexical_names(std::slice::from_ref(&**d), &mut declared);
}
StmtKind::Export(_) | StmtKind::Import(_) => {}
_ => {
crate::compiler::collect_var_names(s, &mut declared);
lexical_names(std::slice::from_ref(s), &mut declared);
}
}
}
for s in stmts {
if let StmtKind::Import(d) = &s.kind {
let req = add_request(&mut info, &d.specifier, &d.attributes);
for spec in &d.specs {
let (import_name, local) = match spec {
ImportSpec::Default(l) => (Some("default".to_string()), l.clone()),
ImportSpec::Namespace(l) => (None, l.clone()),
ImportSpec::Named { imported, local } => {
(Some(imported.clone()), local.clone())
}
};
if declared.contains(&local) || info.imports.iter().any(|e| e.local == local) {
return Err(syntax(format!(
"Identifier '{local}' has already been declared"
)));
}
info.imports.push(ImportEntry {
request: req,
import_name,
local,
clause: d.clause,
});
}
}
}
let mut default_seen = false;
let default_decl = |seen: &mut bool| -> Result<(), String> {
if std::mem::replace(seen, true) {
return Err(syntax("Identifier '.default' has already been declared"));
}
Ok(())
};
let mut exported: Vec<String> = Vec::new();
let mut note_export = |name: &str| -> Result<(), String> {
if exported.iter().any(|e| e == name) {
return Err(syntax(format!("Duplicate export of '{name}'")));
}
exported.push(name.to_string());
Ok(())
};
for s in stmts {
let StmtKind::Export(e) = &s.kind else {
continue;
};
match e {
ExportDecl::Decl(d) => {
let mut names = Vec::new();
crate::compiler::collect_var_names(d, &mut names);
lexical_names(std::slice::from_ref(&**d), &mut names);
for n in names {
note_export(&n)?;
info.local_exports.push((n.clone(), n));
}
}
ExportDecl::DefaultDecl(d) => {
default_decl(&mut default_seen)?;
note_export("default")?;
let mut names = Vec::new();
lexical_names(std::slice::from_ref(&**d), &mut names);
let local = names.pop().unwrap_or_else(|| "default".to_string());
info.local_exports.push(("default".into(), local));
}
ExportDecl::DefaultExpr(_) => {
default_decl(&mut default_seen)?;
note_export("default")?;
info.local_exports
.push(("default".into(), "default".into()));
}
ExportDecl::Named {
specs, from: None, ..
} => {
for sp in specs {
note_export(&sp.exported)?;
match info.imports.iter().find(|i| i.local == sp.local) {
Some(ImportEntry {
request,
import_name: Some(name),
..
}) => info.indirect_exports.push(IndirectExport {
export_name: sp.exported.clone(),
request: *request,
import_name: Some(name.clone()),
}),
Some(_) => info
.local_exports
.push((sp.exported.clone(), sp.local.clone())),
None if declared.contains(&sp.local) => info
.local_exports
.push((sp.exported.clone(), sp.local.clone())),
None => {
return Err(syntax(format!(
"Export '{}' is not defined in module",
sp.local
)))
}
}
}
}
ExportDecl::Named {
specs,
from: Some(from),
attributes,
} => {
let req = add_request(&mut info, from, attributes);
for sp in specs {
note_export(&sp.exported)?;
info.indirect_exports.push(IndirectExport {
export_name: sp.exported.clone(),
request: req,
import_name: Some(sp.local.clone()),
});
}
}
ExportDecl::Star {
alias,
from,
attributes,
} => {
let req = add_request(&mut info, from, attributes);
match alias {
Some(a) => {
note_export(a)?;
info.indirect_exports.push(IndirectExport {
export_name: a.clone(),
request: req,
import_name: None,
});
}
None => info.star_exports.push(req),
}
}
}
}
info.has_tla = stmts.iter().any(stmt_has_tla);
Ok(info)
}
fn stmt_has_tla(s: &Stmt) -> bool {
let mut found = false;
let mut probe = AwaitProbe { found: &mut found };
probe.stmt(s);
found
}
struct AwaitProbe<'a> {
found: &'a mut bool,
}
impl AwaitProbe<'_> {
fn stmt(&mut self, s: &Stmt) {
if *self.found {
return;
}
match &s.kind {
StmtKind::ForOf { is_await: true, .. } => *self.found = true,
StmtKind::FuncDecl { .. } => {}
_ => walk_stmt_children(s, &mut |n| match n {
Node::S(st) => self.stmt(st),
Node::E(e) => self.expr(e),
}),
}
}
fn expr(&mut self, e: &Expr) {
if *self.found {
return;
}
match e {
Expr::Await(..) => *self.found = true,
Expr::Function { .. } => {}
Expr::Class(c) => self.class_outer(c),
_ => walk_expr_children(e, &mut |x| self.expr(x)),
}
}
fn class_outer(&mut self, c: &ClassNode) {
if let Some(p) = &c.parent {
self.expr(p);
}
for m in &c.members {
if m.computed {
self.expr(&m.key);
}
}
}
}
enum Node<'a> {
S(&'a Stmt),
E(&'a Expr),
}
fn walk_stmt_children<'a>(s: &'a Stmt, f: &mut dyn FnMut(Node<'a>)) {
match &s.kind {
StmtKind::Expr(e) | StmtKind::Throw(e) => f(Node::E(e)),
StmtKind::Return(e) => e.iter().for_each(|e| f(Node::E(e))),
StmtKind::Decl { decls, .. } => {
for d in decls {
f(Node::E(&d.target));
if let Some(i) = &d.init {
f(Node::E(i));
}
}
}
StmtKind::Block(b) => b.iter().for_each(|s| f(Node::S(s))),
StmtKind::FuncDecl { .. }
| StmtKind::Break(_)
| StmtKind::Continue(_)
| StmtKind::Empty => {}
StmtKind::ClassDecl(c) => {
if let Some(p) = &c.parent {
f(Node::E(p));
}
for m in &c.members {
if m.computed {
f(Node::E(&m.key));
}
}
}
StmtKind::If { test, cons, alt } => {
f(Node::E(test));
f(Node::S(cons));
if let Some(a) = alt {
f(Node::S(a));
}
}
StmtKind::While { test, body } | StmtKind::DoWhile { body, test } => {
f(Node::E(test));
f(Node::S(body));
}
StmtKind::With { object, body } => {
f(Node::E(object));
f(Node::S(body));
}
StmtKind::For {
init,
test,
update,
body,
} => {
if let Some(i) = init {
f(Node::S(i));
}
test.iter().for_each(|e| f(Node::E(e)));
update.iter().for_each(|e| f(Node::E(e)));
f(Node::S(body));
}
StmtKind::ForOf {
target, iter, body, ..
} => {
f(Node::E(target));
f(Node::E(iter));
f(Node::S(body));
}
StmtKind::ForIn {
target,
object,
body,
..
} => {
f(Node::E(target));
f(Node::E(object));
f(Node::S(body));
}
StmtKind::Switch { disc, cases } => {
f(Node::E(disc));
for c in cases {
c.test.iter().for_each(|e| f(Node::E(e)));
c.body.iter().for_each(|s| f(Node::S(s)));
}
}
StmtKind::Labeled { body, .. } => f(Node::S(body)),
StmtKind::Try {
block,
handler,
finalizer,
} => {
block.iter().for_each(|s| f(Node::S(s)));
if let Some((p, b)) = handler {
p.iter().for_each(|e| f(Node::E(e)));
b.iter().for_each(|s| f(Node::S(s)));
}
if let Some(fin) = finalizer {
fin.iter().for_each(|s| f(Node::S(s)));
}
}
StmtKind::Import(_) => {}
StmtKind::Export(e) => match e {
ExportDecl::Decl(d) | ExportDecl::DefaultDecl(d) => f(Node::S(d)),
ExportDecl::DefaultExpr(x) => f(Node::E(x)),
_ => {}
},
}
}
fn walk_expr_children(e: &Expr, ex: &mut dyn FnMut(&Expr)) {
match e {
Expr::Template { exprs, .. } => exprs.iter().for_each(&mut *ex),
Expr::TaggedTemplate { tag, exprs, .. } => {
ex(tag);
exprs.iter().for_each(&mut *ex);
}
Expr::Yield { arg, .. } => arg.iter().for_each(|x| ex(x)),
Expr::Await(x, _) | Expr::Spread(x) | Expr::Unary(_, x) => ex(x),
Expr::Array(items) | Expr::Sequence(items) => items.iter().for_each(&mut *ex),
Expr::Object(props) => {
for p in props {
match p {
Prop::KeyValue {
key,
value,
computed,
} => {
if *computed {
ex(key);
}
ex(value);
}
Prop::Spread(x) => ex(x),
Prop::Accessor { key, computed, .. } => {
if *computed {
ex(key);
}
}
}
}
}
Expr::Logical(_, l, r) | Expr::Binary(_, l, r) => {
ex(l);
ex(r);
}
Expr::Conditional { test, cons, alt } => {
ex(test);
ex(cons);
ex(alt);
}
Expr::Assign { target, value, .. } => {
ex(target);
ex(value);
}
Expr::Update { target, .. } => ex(target),
Expr::Call { func, args, .. } => {
ex(func);
args.iter().for_each(&mut *ex);
}
Expr::New { callee, args, .. } => {
ex(callee);
args.iter().for_each(&mut *ex);
}
Expr::Member { object, .. } => ex(object),
Expr::Index { object, index, .. } => {
ex(object);
ex(index);
}
Expr::Class(_) | Expr::Function { .. } => {}
Expr::Null
| Expr::Undefined
| Expr::True
| Expr::False
| Expr::Number(_)
| Expr::BigInt(_)
| Expr::Regex(..)
| Expr::Str(_)
| Expr::Ident(_)
| Expr::This
| Expr::Super
| Expr::NewTarget
| Expr::Hole => {}
}
}
fn const_assignment_throw() -> Expr {
let throw = Stmt::from(StmtKind::Throw(Expr::New {
callee: Box::new(Expr::Ident("TypeError".into())),
args: vec![Expr::Str("Assignment to constant variable.".into())],
pos: 0,
}));
Expr::Call {
func: Box::new(arrow(FnBody::Block(vec![throw]))),
args: Vec::new(),
optional: false,
pos: 0,
}
}
fn const_assignment_target() -> Expr {
let Expr::Call { func, .. } = const_assignment_throw() else {
unreachable!("const_assignment_throw builds a call")
};
let Expr::Function { body, .. } = *func else {
unreachable!("the callee is an arrow")
};
let setter = Expr::Function {
params: vec![Param {
pattern: Expr::Ident("_".into()),
default: None,
rest: false,
}],
body,
is_arrow: false,
name: None,
is_generator: false,
is_async: false,
is_method: true,
span: (0, 0),
};
Expr::Member {
object: Box::new(Expr::Object(vec![Prop::Accessor {
key: Expr::Str("v".into()),
computed: false,
is_getter: false,
func: setter,
}])),
property: "v".into(),
optional: false,
pos: 0,
}
}
fn arrow(body: FnBody) -> Expr {
Expr::Function {
params: Vec::new(),
body,
is_arrow: true,
name: None,
is_generator: false,
is_async: false,
is_method: false,
span: (0, 0),
}
}
struct Rewriter<'a> {
imports: HashMap<String, usize>,
cjs_free: Vec<&'static str>,
scopes: Vec<HashSet<String>>,
referrer: &'a str,
}
impl Rewriter<'_> {
fn shadowed(&self, n: &str) -> bool {
self.scopes.iter().any(|s| s.contains(n))
}
fn import_index(&self, n: &str) -> Option<usize> {
self.imports.get(n).copied().filter(|_| !self.shadowed(n))
}
fn import_read(k: usize) -> Expr {
Expr::Call {
func: Box::new(Expr::Index {
object: Box::new(Expr::Ident(IMP.into())),
index: Box::new(Expr::Number(k as f64)),
optional: false,
pos: 0,
}),
args: Vec::new(),
optional: false,
pos: 0,
}
}
fn with_scope<T>(&mut self, names: Vec<String>, f: impl FnOnce(&mut Self) -> T) -> T {
self.scopes.push(names.into_iter().collect());
let out = f(self);
self.scopes.pop();
out
}
fn stmts(&mut self, stmts: &mut [Stmt]) {
for s in stmts {
self.stmt(s);
}
}
fn block(&mut self, stmts: &mut [Stmt]) {
let mut names = Vec::new();
lexical_names(stmts, &mut names);
self.with_scope(names, |r| r.stmts(stmts));
}
fn stmt(&mut self, s: &mut Stmt) {
match &mut s.kind {
StmtKind::Expr(e) | StmtKind::Throw(e) => self.expr(e),
StmtKind::Return(e) => {
if let Some(e) = e {
self.expr(e);
}
}
StmtKind::Decl { decls, .. } => {
for d in decls {
self.binding_pattern(&mut d.target);
if let Some(i) = &mut d.init {
self.expr(i);
}
}
}
StmtKind::Block(b) => self.block(b),
StmtKind::FuncDecl { params, body, .. } => self.function(params, body, None, false),
StmtKind::ClassDecl(c) => self.class(c),
StmtKind::If { test, cons, alt } => {
self.expr(test);
self.stmt(cons);
if let Some(a) = alt {
self.stmt(a);
}
}
StmtKind::While { test, body } | StmtKind::DoWhile { body, test } => {
self.expr(test);
self.stmt(body);
}
StmtKind::With { object, body } => {
self.expr(object);
self.stmt(body);
}
StmtKind::For {
init,
test,
update,
body,
} => {
let mut names = Vec::new();
if let Some(i) = init {
lexical_names(std::slice::from_ref(&**i), &mut names);
}
self.with_scope(names, |r| {
if let Some(i) = init {
r.stmt(i);
}
if let Some(t) = test {
r.expr(t);
}
if let Some(u) = update {
r.expr(u);
}
r.stmt(body);
});
}
StmtKind::ForOf {
decl_kind,
target,
iter,
body,
..
}
| StmtKind::ForIn {
decl_kind,
target,
object: iter,
body,
..
} => {
let mut names = Vec::new();
if matches!(decl_kind, Some(DeclKind::Let) | Some(DeclKind::Const)) {
crate::compiler::pattern_names(target, &mut names);
}
let declares = decl_kind.is_some();
self.with_scope(names, |r| {
r.expr(iter);
if declares {
r.binding_pattern(target);
} else {
r.assignment_pattern(target);
}
r.stmt(body);
});
}
StmtKind::Switch { disc, cases } => {
self.expr(disc);
let mut names = Vec::new();
for c in cases.iter() {
lexical_names(&c.body, &mut names);
}
self.with_scope(names, |r| {
for c in cases {
if let Some(t) = &mut c.test {
r.expr(t);
}
r.stmts(&mut c.body);
}
});
}
StmtKind::Labeled { body, .. } => self.stmt(body),
StmtKind::Try {
block,
handler,
finalizer,
} => {
self.block(block);
if let Some((param, body)) = handler {
let mut names = Vec::new();
if let Some(p) = param {
crate::compiler::pattern_names(p, &mut names);
}
lexical_names(body, &mut names);
self.with_scope(names, |r| {
if let Some(p) = param {
r.binding_pattern(p);
}
r.stmts(body);
});
}
if let Some(f) = finalizer {
self.block(f);
}
}
StmtKind::Break(_) | StmtKind::Continue(_) | StmtKind::Empty => {}
StmtKind::Import(_) | StmtKind::Export(_) => {}
}
}
fn function(
&mut self,
params: &mut [Param],
body: &mut [Stmt],
own: Option<&str>,
arrow: bool,
) {
let mut names: Vec<String> = own.map(str::to_string).into_iter().collect();
if !arrow {
names.push("arguments".into());
}
for p in params.iter() {
crate::compiler::pattern_names(&p.pattern, &mut names);
}
body_names(body, &mut names);
self.with_scope(names, |r| {
for p in params.iter_mut() {
r.binding_pattern(&mut p.pattern);
if let Some(d) = &mut p.default {
r.expr(d);
}
}
r.stmts(body);
});
}
fn class(&mut self, c: &mut ClassNode) {
let names: Vec<String> = c.name.clone().into_iter().collect();
self.with_scope(names, |r| {
if let Some(p) = &mut c.parent {
r.expr(p);
}
for m in &mut c.members {
if m.computed {
r.expr(&mut m.key);
}
match m.kind {
MemberKind::Field => {
if let Some(i) = &mut m.field_init {
r.with_scope(vec!["arguments".into()], |r| r.expr(i));
}
}
_ => r.function(&mut m.params, &mut m.body, None, false),
}
}
});
}
fn binding_pattern(&mut self, target: &mut Expr) {
match target {
Expr::Ident(_) => {}
Expr::Array(items) => items.iter_mut().for_each(|i| self.binding_pattern(i)),
Expr::Object(props) => {
for p in props {
match p {
Prop::KeyValue {
key,
value,
computed,
} => {
if *computed {
self.expr(key);
}
self.binding_pattern(value);
}
Prop::Spread(e) => self.binding_pattern(e),
Prop::Accessor { .. } => {}
}
}
}
Expr::Assign { target, value, .. } => {
self.binding_pattern(target);
self.expr(value);
}
Expr::Spread(inner) => self.binding_pattern(inner),
other => self.expr(other),
}
}
fn assignment_pattern(&mut self, target: &mut Expr) {
match target {
Expr::Ident(n) if self.import_index(n).is_some() => *target = const_assignment_target(),
Expr::Ident(_) => self.expr(target),
Expr::Array(items) => items.iter_mut().for_each(|i| self.assignment_pattern(i)),
Expr::Object(props) => {
for p in props {
match p {
Prop::KeyValue {
key,
value,
computed,
} => {
if *computed {
self.expr(key);
}
self.assignment_pattern(value);
}
Prop::Spread(e) => self.assignment_pattern(e),
Prop::Accessor { .. } => {}
}
}
}
Expr::Assign { target, value, .. } => {
self.assignment_pattern(target);
self.expr(value);
}
Expr::Spread(inner) => self.assignment_pattern(inner),
other => self.expr(other),
}
}
fn expr(&mut self, e: &mut Expr) {
match e {
Expr::Ident(n) => {
if let Some(k) = self.import_index(n) {
*e = Self::import_read(k);
} else if self.cjs_free.contains(&n.as_str()) && !self.shadowed(n) {
*n = format!("{CJS_FREE_PREFIX}{n}");
}
}
Expr::Member {
object, property, ..
} if matches!(&**object, Expr::Ident(i) if i == "import") && property == "meta" => {
*e = Expr::Ident(META.into());
}
Expr::Call { func, args, .. } if matches!(&**func, Expr::Ident(i) if i == "import") => {
for a in args.iter_mut() {
self.expr(a);
}
let mut full = Vec::with_capacity(3);
let mut it = std::mem::take(args).into_iter();
full.push(it.next().unwrap_or(Expr::Undefined));
full.push(Expr::Str(self.referrer.to_string()));
full.extend(it.next());
*e = Expr::Call {
func: Box::new(Expr::Ident(IMPORT_FN.into())),
args: full,
optional: false,
pos: 0,
};
}
Expr::Assign { target, op, value } => {
let hits = matches!(&**target, Expr::Ident(n) if self.import_index(n).is_some());
if !hits {
if matches!(&**target, Expr::Array(_) | Expr::Object(_)) {
self.assignment_pattern(target);
} else {
self.expr(target);
}
self.expr(value);
return;
}
self.expr(value);
let value = std::mem::replace(&mut **value, Expr::Undefined);
let throw = const_assignment_throw();
*e = match (op.as_ref(), &**target) {
(Some(AssignOp::Logical(lop)), Expr::Ident(n)) => {
let read = Self::import_read(self.import_index(n).unwrap_or(0));
Expr::Logical(
*lop,
Box::new(read),
Box::new(Expr::Sequence(vec![value, throw])),
)
}
(Some(AssignOp::Binary(bop)), Expr::Ident(n)) => {
let read = Self::import_read(self.import_index(n).unwrap_or(0));
Expr::Sequence(vec![
Expr::Binary(*bop, Box::new(read), Box::new(value)),
throw,
])
}
_ => Expr::Sequence(vec![value, throw]),
};
}
Expr::Update { target, .. } => {
if let Expr::Ident(n) = &**target {
if let Some(k) = self.import_index(n) {
let read = Expr::Unary(UnOp::Pos, Box::new(Self::import_read(k)));
*e = Expr::Sequence(vec![read, const_assignment_throw()]);
return;
}
}
self.expr(target);
}
Expr::Function {
params,
body,
is_arrow,
name,
..
} => {
let arrow = *is_arrow;
let own = name.clone();
match body {
FnBody::Block(b) => self.function(params, b, own.as_deref(), arrow),
FnBody::Expr(x) => {
let mut stmts = Vec::new();
self.function(params, &mut stmts, own.as_deref(), arrow);
let mut names: Vec<String> = Vec::new();
for p in params.iter() {
crate::compiler::pattern_names(&p.pattern, &mut names);
}
if !arrow {
names.push("arguments".into());
}
self.with_scope(names, |r| r.expr(x));
}
}
}
Expr::Class(c) => self.class(c),
Expr::Object(props) => {
for p in props {
match p {
Prop::KeyValue {
key,
value,
computed,
} => {
if *computed {
self.expr(key);
}
self.expr(value);
}
Prop::Spread(x) => self.expr(x),
Prop::Accessor {
key,
computed,
func,
..
} => {
if *computed {
self.expr(key);
}
self.expr(func);
}
}
}
}
Expr::Template { exprs, .. } => exprs.iter_mut().for_each(|x| self.expr(x)),
Expr::TaggedTemplate { tag, exprs, .. } => {
self.expr(tag);
exprs.iter_mut().for_each(|x| self.expr(x));
}
Expr::Yield { arg, .. } => {
if let Some(a) = arg {
self.expr(a);
}
}
Expr::Await(x, _) | Expr::Spread(x) | Expr::Unary(_, x) => self.expr(x),
Expr::Array(items) | Expr::Sequence(items) => {
items.iter_mut().for_each(|x| self.expr(x))
}
Expr::Logical(_, l, r) | Expr::Binary(_, l, r) => {
self.expr(l);
self.expr(r);
}
Expr::Conditional { test, cons, alt } => {
self.expr(test);
self.expr(cons);
self.expr(alt);
}
Expr::Call { func, args, .. } => {
self.expr(func);
args.iter_mut().for_each(|x| self.expr(x));
}
Expr::New { callee, args, .. } => {
self.expr(callee);
args.iter_mut().for_each(|x| self.expr(x));
}
Expr::Member { object, .. } => self.expr(object),
Expr::Index { object, index, .. } => {
self.expr(object);
self.expr(index);
}
Expr::Null
| Expr::Undefined
| Expr::True
| Expr::False
| Expr::Number(_)
| Expr::BigInt(_)
| Expr::Regex(..)
| Expr::Str(_)
| Expr::This
| Expr::Super
| Expr::NewTarget
| Expr::Hole => {}
}
}
}
pub fn lower(stmts: Vec<Stmt>, info: &ModuleInfo, referrer: &str, generator: bool) -> Expr {
let mut body: Vec<Stmt> = Vec::with_capacity(stmts.len() + 2);
for s in stmts {
let line = s.line;
match s.kind {
StmtKind::Import(_) => {}
StmtKind::Export(ExportDecl::Decl(d))
| StmtKind::Export(ExportDecl::DefaultDecl(d)) => body.push(*d),
StmtKind::Export(ExportDecl::DefaultExpr(e)) => body.push(Stmt::new(
StmtKind::Decl {
kind: DeclKind::Const,
decls: vec![Declarator {
target: Expr::Ident("default".into()),
init: Some(e),
bound: Vec::new(),
}],
},
line,
)),
StmtKind::Export(_) => {}
other => body.push(Stmt::new(other, line)),
}
}
let mut declared = Vec::new();
body_names(&body, &mut declared);
let mut rw = Rewriter {
imports: info
.imports
.iter()
.enumerate()
.map(|(k, e)| (e.local.clone(), k))
.collect(),
cjs_free: CJS_NAMES
.iter()
.copied()
.filter(|n| !declared.iter().any(|d| d == n))
.collect(),
scopes: Vec::new(),
referrer,
};
rw.stmts(&mut body);
let getters: Vec<Expr> = info
.local_exports
.iter()
.map(|(_, local)| {
let mut read = Expr::Ident(local.clone());
rw.expr(&mut read);
arrow(FnBody::Expr(Box::new(read)))
})
.collect();
let mut prologue = vec![Stmt::from(StmtKind::Expr(Expr::Call {
func: Box::new(Expr::Ident(REG.into())),
args: vec![Expr::Array(getters)],
optional: false,
pos: 0,
}))];
if generator {
prologue.push(Stmt::from(StmtKind::Expr(Expr::Yield {
arg: None,
delegate: false,
})));
}
prologue.extend(body);
let param = |n: &str| Param {
pattern: Expr::Ident(n.into()),
default: None,
rest: false,
};
Expr::Function {
params: vec![param(IMP), param(META), param(REG)],
body: FnBody::Block(prologue),
is_arrow: false,
name: None,
is_generator: generator,
is_async: info.has_tla,
is_method: false,
span: (0, 0),
}
}
const MODULE_ONLY_ERRORS: &[&str] = &[
"SyntaxError: Cannot use import statement outside a module",
"SyntaxError: Unexpected token 'export'",
"SyntaxError: Cannot use 'import.meta' outside a module",
"SyntaxError: await is only valid in async functions and the top level bodies of modules",
];
pub fn detect_module(src: &str, script_err: &str) -> bool {
let explained = MODULE_ONLY_ERRORS.iter().any(|m| script_err.starts_with(m))
|| script_err.starts_with("SyntaxError") && src.contains("await");
explained && crate::parser::parse_module(src).is_ok()
}
pub fn has_module_syntax(src: &str) -> bool {
match crate::parser::parse(src) {
Ok(_) => false,
Err(e) => detect_module(src, &e),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
Module,
CommonJs,
Json,
Builtin,
}
impl Format {
fn name(self) -> &'static str {
match self {
Format::Module => "module",
Format::CommonJs => "commonjs",
Format::Json => "json",
Format::Builtin => "builtin",
}
}
}
thread_local! {
static PACKAGE_JSON: std::cell::RefCell<HashMap<PathBuf, Option<serde_json::Value>>> =
std::cell::RefCell::new(HashMap::new());
}
fn read_package_json(path: &Path) -> Option<serde_json::Value> {
if let Some(hit) = PACKAGE_JSON.with(|c| c.borrow().get(path).cloned()) {
return hit;
}
let parsed = std::fs::read_to_string(path)
.ok()
.and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok());
PACKAGE_JSON.with(|c| c.borrow_mut().insert(path.to_path_buf(), parsed.clone()));
parsed
}
fn package_scope(dir: &Path) -> Option<serde_json::Value> {
package_scope_file(dir).and_then(|pj| read_package_json(&pj))
}
fn package_scope_file(dir: &Path) -> Option<PathBuf> {
let mut cur = Some(dir);
while let Some(d) = cur {
let pj = d.join("package.json");
if pj.is_file() {
return Some(pj);
}
if d.file_name().is_some_and(|n| n == "node_modules") {
return None;
}
cur = d.parent();
}
None
}
pub fn file_format_declared(path: &Path) -> Option<Format> {
match path.extension().and_then(|e| e.to_str()) {
Some("mjs") => return Some(Format::Module),
Some("cjs") => return Some(Format::CommonJs),
Some("json") => return Some(Format::Json),
_ => {}
}
let scope_type = path
.parent()
.and_then(package_scope)
.and_then(|p| p.get("type").and_then(|t| t.as_str()).map(str::to_string));
match scope_type.as_deref() {
Some("module") => Some(Format::Module),
Some("commonjs") => Some(Format::CommonJs),
_ => None,
}
}
pub fn file_format(path: &Path) -> Format {
file_format_declared(path).unwrap_or_else(|| match std::fs::read_to_string(path) {
Ok(src) if has_module_syntax(&src) => Format::Module,
_ => Format::CommonJs,
})
}
fn not_found(what: &str, parent: Option<&str>) -> String {
let msg = match parent {
Some(p) => format!("Cannot find {what} imported from {p}"),
None => format!("Cannot find {what}"),
};
crate::host::plain_coded_error("Error", "ERR_MODULE_NOT_FOUND", &msg)
}
pub fn file_url(path: &str) -> String {
url::Url::from_file_path(path)
.map(|u| u.to_string())
.unwrap_or_else(|_| format!("file://{path}"))
}
pub struct Resolved {
pub url: String,
pub file: String,
pub format: Format,
}
fn builtin(spec: &str) -> Option<Resolved> {
crate::stdlib::resolve(spec).map(|_| Resolved {
url: format!("node:{}", spec.strip_prefix("node:").unwrap_or(spec)),
file: String::new(),
format: Format::Builtin,
})
}
pub fn resolve(spec: &str, parent: Option<&str>) -> Result<Resolved, String> {
if let Some(name) = spec.strip_prefix("node:") {
return builtin(spec).ok_or_else(|| {
crate::host::plain_coded_error(
"Error",
"ERR_UNKNOWN_BUILTIN_MODULE",
&format!("No such built-in module: node:{name}"),
)
});
}
let base_dir = match parent {
Some(p) => Path::new(p)
.parent()
.map(Path::to_path_buf)
.unwrap_or_default(),
None => std::env::current_dir().unwrap_or_default(),
};
let base_url = url::Url::from_directory_path(&base_dir)
.map_err(|_| crate::host::type_error(&format!("Invalid URL: {}", base_dir.display())))?;
let relative = spec.starts_with("./") || spec.starts_with("../") || spec.starts_with('/');
let url = if relative {
base_url
.join(spec)
.map_err(|_| crate::host::type_error(&format!("Invalid URL: {spec}")))?
} else if let Ok(u) = url::Url::parse(spec) {
if u.scheme() != "file" {
return Err(crate::host::plain_coded_error(
"Error",
"ERR_UNSUPPORTED_ESM_URL_SCHEME",
&format!(
"Only URLs with a scheme in: file and node are supported by the default ESM loader. Received protocol '{}:'",
u.scheme()
),
));
}
u
} else {
if let Some(b) = builtin(spec) {
return Ok(b);
}
let file = if spec.starts_with('#') {
imports_resolve(spec, &base_dir, parent)?
} else {
package_resolve(spec, &base_dir, parent)?
};
url::Url::from_file_path(&file)
.map_err(|_| crate::host::type_error(&format!("Invalid URL: {}", file.display())))?
};
finalize(url, parent)
}
fn finalize(url: url::Url, parent: Option<&str>) -> Result<Resolved, String> {
let path = url
.to_file_path()
.map_err(|_| crate::host::type_error(&format!("Invalid URL: {url}")))?;
if path.is_dir() {
return Err(crate::host::plain_coded_error(
"Error",
"ERR_UNSUPPORTED_DIR_IMPORT",
&format!(
"Directory import '{}' is not supported resolving ES modules imported from {}",
path.display(),
parent.unwrap_or("")
),
));
}
if !path.is_file() {
return Err(not_found(&format!("module '{}'", path.display()), parent));
}
let real = std::fs::canonicalize(&path).unwrap_or(path);
let mut url = url::Url::from_file_path(&real).unwrap_or(url.clone());
url.set_query(url.query().map(str::to_string).as_deref());
let file = real.to_string_lossy().into_owned();
Ok(Resolved {
url: url.to_string(),
format: file_format(&real),
file,
})
}
const IMPORT_CONDITIONS: &[&str] = &["node", "import", "module-sync", "default"];
fn package_resolve(spec: &str, from: &Path, parent: Option<&str>) -> Result<PathBuf, String> {
let (name, rest) = match spec.strip_prefix('@') {
Some(s) => match s.split_once('/') {
Some((scope, tail)) => {
let (pkg, sub) = tail.split_once('/').unwrap_or((tail, ""));
(format!("@{scope}/{pkg}"), sub.to_string())
}
None => (spec.to_string(), String::new()),
},
None => {
let (pkg, sub) = spec.split_once('/').unwrap_or((spec, ""));
(pkg.to_string(), sub.to_string())
}
};
let subpath = if rest.is_empty() {
".".to_string()
} else {
format!("./{rest}")
};
if let Some(pj) = package_scope_file(from) {
if let Some(json) = read_package_json(&pj) {
let exports = json.get("exports").filter(|e| !e.is_null());
if let (Some(exports), Some(own)) = (exports, json.get("name").and_then(|n| n.as_str()))
{
if own == name {
let pkg = pj.parent().unwrap_or(Path::new("/"));
return exports_resolve(pkg, &subpath, exports, &pj, parent);
}
}
}
}
let mut dir = Some(from);
while let Some(d) = dir {
let pkg_dir = d.join("node_modules").join(&name);
if pkg_dir.is_dir() {
let pj_path = pkg_dir.join("package.json");
let pj = read_package_json(&pj_path);
if let Some(exports) = pj
.as_ref()
.and_then(|p| p.get("exports"))
.filter(|e| !e.is_null())
{
return exports_resolve(&pkg_dir, &subpath, exports, &pj_path, parent);
}
if subpath == "." {
return legacy_main(&pkg_dir, pj.as_ref())
.ok_or_else(|| not_found(&format!("package '{}'", pkg_dir.display()), parent));
}
return Ok(pkg_dir.join(&rest));
}
dir = d.parent();
}
Err(not_found(&format!("package '{name}'"), parent))
}
fn legacy_main(pkg: &Path, pj: Option<&serde_json::Value>) -> Option<PathBuf> {
let mut cands: Vec<PathBuf> = Vec::new();
if let Some(main) = pj.and_then(|p| p.get("main")).and_then(|m| m.as_str()) {
let m = pkg.join(main);
cands.push(m.clone());
for ext in ["js", "json", "node"] {
cands.push(PathBuf::from(format!("{}.{ext}", m.display())));
}
for idx in ["index.js", "index.json", "index.node"] {
cands.push(m.join(idx));
}
}
for idx in ["index.js", "index.json", "index.node"] {
cands.push(pkg.join(idx));
}
cands.into_iter().find(|c| c.is_file())
}
fn not_exported(pkg_json: &Path, subpath: &str, parent: Option<&str>) -> String {
let from = parent
.map(|p| format!(" imported from {p}"))
.unwrap_or_default();
let msg = if subpath == "." {
format!(
"No \"exports\" main defined in {}{from}",
pkg_json.display()
)
} else {
format!(
"Package subpath '{subpath}' is not defined by \"exports\" in {}{from}",
pkg_json.display()
)
};
crate::host::plain_coded_error("Error", "ERR_PACKAGE_PATH_NOT_EXPORTED", &msg)
}
fn exports_resolve(
pkg: &Path,
subpath: &str,
exports: &serde_json::Value,
pj: &Path,
parent: Option<&str>,
) -> Result<PathBuf, String> {
let is_subpath_map = exports
.as_object()
.is_some_and(|o| o.keys().next().is_some_and(|k| k.starts_with('.')));
let found = match exports.as_object() {
Some(map) if is_subpath_map => match_subpath_map(map, subpath),
_ => (subpath == ".").then(|| (exports, String::new())),
};
let found = found
.and_then(|(t, pattern)| target_string(t, &pattern))
.and_then(|s| s.strip_prefix("./").map(|rel| pkg.join(rel)));
found.ok_or_else(|| not_exported(pj, subpath, parent))
}
fn match_subpath_map<'a>(
map: &'a serde_json::Map<String, serde_json::Value>,
key: &str,
) -> Option<(&'a serde_json::Value, String)> {
if let Some(t) = map.get(key).filter(|_| !key.contains('*')) {
return Some((t, String::new()));
}
let mut best: Option<(&str, String)> = None;
for k in map.keys() {
let Some((pre, post)) = k.split_once('*') else {
continue;
};
if key.starts_with(pre)
&& key.len() >= pre.len() + post.len()
&& key.ends_with(post)
&& best.as_ref().map_or(true, |(b, _)| k.len() > b.len())
{
best = Some((
k.as_str(),
key[pre.len()..key.len() - post.len()].to_string(),
));
}
}
best.map(|(k, mid)| (&map[k], mid))
}
fn target_string(target: &serde_json::Value, pattern: &str) -> Option<String> {
match target {
serde_json::Value::String(s) => Some(s.replace('*', pattern)),
serde_json::Value::Object(o) => o
.iter()
.filter(|(k, _)| IMPORT_CONDITIONS.contains(&k.as_str()))
.find_map(|(_, v)| target_string(v, pattern)),
serde_json::Value::Array(a) => a.iter().find_map(|v| target_string(v, pattern)),
_ => None,
}
}
fn imports_resolve(spec: &str, from: &Path, parent: Option<&str>) -> Result<PathBuf, String> {
let undefined = || {
let from_text = parent
.map(|p| format!(" imported from {p}"))
.unwrap_or_default();
crate::host::plain_coded_error(
"TypeError",
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
&format!("Package import specifier \"{spec}\" is not defined{from_text}"),
)
};
let pj = package_scope_file(from).ok_or_else(undefined)?;
let pkg = pj.parent().unwrap_or(Path::new("/"));
let json = read_package_json(&pj).ok_or_else(undefined)?;
let map = json
.get("imports")
.and_then(|i| i.as_object())
.ok_or_else(undefined)?;
let (target, pattern) = match_subpath_map(map, spec).ok_or_else(undefined)?;
let target = target_string(target, &pattern).ok_or_else(undefined)?;
match target.strip_prefix("./") {
Some(rel) => Ok(pkg.join(rel)),
None => package_resolve(&target, pkg, parent),
}
}
pub fn cjs_export_names(file: &Path, seen: &mut HashSet<PathBuf>) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
if !seen.insert(file.to_path_buf()) {
return out;
}
let Ok(src) = std::fs::read_to_string(file) else {
return out;
};
let Ok(stmts) = crate::parser::parse(&src) else {
return out;
};
let mut reexports: Vec<String> = Vec::new();
let mut scan = CjsScan {
names: &mut out,
reexports: &mut reexports,
};
for s in &stmts {
scan.stmt(s);
}
let dir = file.parent().unwrap_or(Path::new("/"));
for spec in reexports {
if let Some(target) = crate::module::resolve(&spec, dir) {
for n in cjs_export_names(&target, seen) {
if !out.contains(&n) {
out.push(n);
}
}
}
}
out.retain(|n| n != "default");
out
}
struct CjsScan<'a> {
names: &'a mut Vec<String>,
reexports: &'a mut Vec<String>,
}
fn is_exports_obj(e: &Expr) -> bool {
match e {
Expr::Ident(n) => n == "exports",
Expr::Member {
object, property, ..
} => property == "exports" && matches!(&**object, Expr::Ident(m) if m == "module"),
_ => false,
}
}
impl CjsScan<'_> {
fn add(&mut self, n: &str) {
if !self.names.iter().any(|x| x == n) {
self.names.push(n.to_string());
}
}
fn stmt(&mut self, s: &Stmt) {
walk_stmt_children(s, &mut |n| match n {
Node::S(st) => self.stmt(st),
Node::E(e) => self.expr(e),
});
if let StmtKind::FuncDecl { body, .. } = &s.kind {
body.iter().for_each(|st| self.stmt(st));
}
}
fn expr(&mut self, e: &Expr) {
match e {
Expr::Assign { target, value, .. } => {
match &**target {
Expr::Member {
object, property, ..
} if is_exports_obj(object) => self.add(property),
Expr::Index { object, index, .. } if is_exports_obj(object) => {
if let Expr::Str(k) = &**index {
self.add(k);
}
}
t if is_exports_obj(t) && matches!(t, Expr::Member { .. }) => match &**value {
Expr::Object(props) => {
for p in props {
match p {
Prop::KeyValue {
key: Expr::Str(k),
computed: false,
value,
} => match value {
Expr::Ident(_) => self.add(k),
Expr::Call { func, .. } if matches!(&**func, Expr::Ident(r) if r == "require") =>
{
self.add(k);
break;
}
_ => break,
},
Prop::Spread(_) => {}
_ => break,
}
}
}
Expr::Call { func, args, .. } if matches!(&**func, Expr::Ident(r) if r == "require") => {
if let Some(Expr::Str(s)) = args.first() {
self.reexports.push(s.clone());
}
}
_ => {}
},
_ => {}
}
walk_expr_children(e, &mut |x| self.expr(x));
}
Expr::Call { func, args, .. } => {
if let Expr::Member {
object, property, ..
} = &**func
{
if property == "defineProperty"
&& matches!(&**object, Expr::Ident(o) if o == "Object")
&& args.first().is_some_and(is_exports_obj)
{
if let Some(Expr::Str(k)) = args.get(1) {
self.add(k);
}
}
}
walk_expr_children(e, &mut |x| self.expr(x));
}
Expr::Function { body, .. } => match body {
FnBody::Block(b) => b.iter().for_each(|st| self.stmt(st)),
FnBody::Expr(x) => self.expr(x),
},
_ => walk_expr_children(e, &mut |x| self.expr(x)),
}
}
}
use crate::host::{self, with_host, JsObj};
use fusevm::Value;
struct Parsed {
lowered: Option<Expr>,
source: String,
url: String,
}
thread_local! {
static PARSED: std::cell::RefCell<Vec<Parsed>> = const { std::cell::RefCell::new(Vec::new()) };
static VIRTUAL: std::cell::RefCell<HashMap<String, String>> =
std::cell::RefCell::new(HashMap::new());
static LOADER: std::cell::RefCell<Option<Value>> = const { std::cell::RefCell::new(None) };
}
pub fn reset() {
PARSED.with(|p| p.borrow_mut().clear());
VIRTUAL.with(|v| v.borrow_mut().clear());
LOADER.with(|l| *l.borrow_mut() = None);
PACKAGE_JSON.with(|c| c.borrow_mut().clear());
}
fn s(v: &Value) -> String {
with_host(|h| h.str_of(v))
}
fn js_str(text: &str) -> Value {
with_host(|h| h.new_str(text.to_string()))
}
fn js_array(items: Vec<Value>) -> Value {
with_host(|h| h.new_array(items))
}
fn js_name(n: &Option<String>) -> Value {
match n {
Some(n) => js_str(n),
None => with_host(|h| h.null()),
}
}
fn clause_text(source: &str, (start, end): Span) -> String {
let raw = source.get(start as usize..end as usize).unwrap_or("");
let words: Vec<&str> = raw.split_whitespace().collect();
words.join(" ").replace(" as ", ": ")
}
fn info_value(id: usize, info: &ModuleInfo, source: &str) -> Value {
let requests = info
.requests
.iter()
.map(|(spec, attrs)| {
let mut props = indexmap::IndexMap::new();
for (k, v) in attrs {
props.insert(k.clone(), js_str(v));
}
let attrs = with_host(|h| h.new_object(props));
js_array(vec![js_str(spec), attrs])
})
.collect();
let imports = info
.imports
.iter()
.map(|e| {
js_array(vec![
Value::Float(e.request as f64),
js_name(&e.import_name),
js_str(&e.local),
js_str(&clause_text(source, e.clause)),
])
})
.collect();
let locals = info
.local_exports
.iter()
.map(|(e, l)| js_array(vec![js_str(e), js_str(l)]))
.collect();
let indirect = info
.indirect_exports
.iter()
.map(|e| {
js_array(vec![
js_str(&e.export_name),
Value::Float(e.request as f64),
js_name(&e.import_name),
])
})
.collect();
let stars = info
.star_exports
.iter()
.map(|r| Value::Float(*r as f64))
.collect();
let mut props = indexmap::IndexMap::new();
props.insert("id".to_string(), Value::Float(id as f64));
props.insert("requests".to_string(), js_array(requests));
props.insert("imports".to_string(), js_array(imports));
props.insert("localExports".to_string(), js_array(locals));
props.insert("indirectExports".to_string(), js_array(indirect));
props.insert("starExports".to_string(), js_array(stars));
props.insert("hasTLA".to_string(), Value::Bool(info.has_tla));
with_host(|h| h.new_object(props))
}
fn parse_file(path: &str) -> Result<Value, String> {
let source = match VIRTUAL.with(|v| v.borrow_mut().remove(path)) {
Some(text) => text,
None => {
std::fs::read_to_string(path).map_err(|e| format!("Error: cannot read {path}: {e}"))?
}
};
let stmts = crate::parser::parse_module(&source).inspect_err(|e| {
let at = crate::parser::take_error_pos();
host::note_syntax_error(&source, host::ScriptOrigin::named(file_url(path)), e, at);
})?;
let info = analyze(&stmts)?;
let lowered = lower(stmts, &info, path, false);
if let Expr::Function {
body: FnBody::Block(b),
..
} = &lowered
{
crate::compiler::check_early_errors(b).inspect_err(|e| {
let at = crate::parser::take_error_pos();
host::note_syntax_error(&source, host::ScriptOrigin::named(file_url(path)), e, at);
})?;
}
let id = PARSED.with(|p| p.borrow().len());
let record = info_value(id, &info, &source);
PARSED.with(|p| {
p.borrow_mut().push(Parsed {
lowered: Some(lowered),
source,
url: file_url(path),
})
});
Ok(record)
}
fn compile(id: usize, generator: bool) -> Result<Value, String> {
let (lowered, source, url) = PARSED.with(|p| {
let mut p = p.borrow_mut();
let entry = &mut p[id];
(
entry.lowered.take(),
std::mem::take(&mut entry.source),
entry.url.clone(),
)
});
let mut lowered = lowered.ok_or_else(|| host::type_error("module instantiated twice"))?;
if generator {
if let Expr::Function {
body: FnBody::Block(b),
is_generator,
..
} = &mut lowered
{
*is_generator = true;
b.insert(
1,
Stmt::from(StmtKind::Expr(Expr::Yield {
arg: None,
delegate: false,
})),
);
}
}
let stmts = vec![Stmt::from(StmtKind::Expr(lowered))];
let prog = crate::with_source(
crate::compiler::compile_completion_strict(&stmts, false, true, false),
&source,
)?;
host::run_chunk_in_global_scope(crate::load_merged_from(
prog,
Some(host::ScriptOrigin::named(url)),
))
}
fn mark_namespace(ns: &Value) {
with_host(|h| {
if let Some(JsObj::Proxy { target, .. }) = h.get(ns).cloned() {
if let Some(JsObj::Object(p)) = h.get_mut(&target) {
p.insert(NAMESPACE_MARK.to_string(), Value::Bool(true));
}
}
});
}
const NAMESPACE_MARK: &str = "@@esmNamespace";
pub fn is_namespace(v: &Value) -> bool {
with_host(|h| match h.get(v) {
Some(JsObj::Proxy { target, .. }) => {
matches!(h.get(target), Some(JsObj::Object(p)) if p.contains_key(NAMESPACE_MARK))
}
_ => false,
})
}
pub fn native(name: &str, args: &[Value]) -> Result<Value, String> {
let arg = |i: usize| args.get(i).cloned().unwrap_or(Value::Undef);
match name {
"resolve" => {
let parent = match arg(1) {
Value::Undef => None,
v => Some(s(&v)),
};
let r = resolve(&s(&arg(0)), parent.as_deref())?;
Ok(js_array(vec![
js_str(&r.url),
js_str(&r.file),
js_str(r.format.name()),
]))
}
"parse" => parse_file(&s(&arg(0))),
"compile" => {
let id = with_host(|h| h.to_number(&arg(0))) as usize;
let generator = with_host(|h| h.truthy(&arg(1)));
compile(id, generator)
}
"cjsNames" => {
let names = cjs_export_names(Path::new(&s(&arg(0))), &mut HashSet::new());
Ok(js_array(names.iter().map(|n| js_str(n)).collect()))
}
"requireCjs" => crate::module::require_file(Path::new(&s(&arg(0))), ""),
"builtin" => {
let url = s(&arg(0));
let spec = url.strip_prefix("node:").unwrap_or(&url);
crate::module::require(spec, &crate::module::entry_dir(), "")
}
"json" => {
let path = s(&arg(0));
let text = std::fs::read_to_string(&path)
.map_err(|e| format!("Error: cannot read {path}: {e}"))?;
crate::builtins::call_builtin_function("JSON.parse", vec![js_str(&text)])
}
"markNamespace" => {
mark_namespace(&arg(0));
Ok(Value::Undef)
}
"import" => loader_call("dynamicImport", args.to_vec()),
"main" => loader_call("runMain", args.to_vec()),
_ => Err(host::type_error(&format!("@@esm.{name} is not a function"))),
}
}
fn loader() -> Result<Value, String> {
if let Some(l) = LOADER.with(|l| l.borrow().clone()) {
return Ok(l);
}
let factory = crate::eval_in_global_scope_from(
include_str!("esm_loader.js"),
Some(host::ScriptOrigin::internal(
"node:internal/modules/esm/loader",
)),
)?;
let mut natives = indexmap::IndexMap::new();
for n in [
"resolve",
"parse",
"compile",
"cjsNames",
"requireCjs",
"builtin",
"json",
"markNamespace",
] {
let f = with_host(|h| h.alloc(JsObj::Builtin(format!("@@esm.{n}"))));
natives.insert(n.to_string(), f);
}
let natives = with_host(|h| h.new_object(natives));
let api = host::invoke(&factory, vec![natives], None)?;
LOADER.with(|l| *l.borrow_mut() = Some(api.clone()));
Ok(api)
}
fn loader_call(method: &str, args: Vec<Value>) -> Result<Value, String> {
let api = loader()?;
let f = crate::builtins::get_property(&api, method)?;
host::invoke(&f, args, None)
}
pub fn require_module(path: &Path, parent: &str) -> Result<Value, String> {
loader_call(
"requireModule",
vec![js_str(&path.to_string_lossy()), js_str(parent)],
)
}
pub fn main_program(entry: &str, source: Option<String>, is_main: bool) -> Vec<Stmt> {
if let Some(text) = source {
VIRTUAL.with(|v| v.borrow_mut().insert(entry.to_string(), text));
}
with_host(|h| h.module_frame_done = true);
let call = Expr::Call {
func: Box::new(Expr::Ident(MAIN_FN.into())),
args: vec![
Expr::Str(entry.to_string()),
Expr::Str(file_url(entry)),
if is_main { Expr::True } else { Expr::False },
],
optional: false,
pos: 0,
};
vec![Stmt::from(StmtKind::Expr(call))]
}
pub const MAIN_FN: &str = "%esm.main";
pub enum Refused {
Set,
Delete,
Define,
}
pub fn namespace_refusal(recv: &Value, op: Refused, key: &str) -> Option<String> {
if !is_namespace(recv) {
return None;
}
Some(host::type_error(&match op {
Refused::Set => format!("Cannot assign to property '{key}' of [object Module]"),
Refused::Delete => format!("Cannot delete property '{key}' of [object Module]"),
Refused::Define => format!("Cannot redefine property: {key}"),
}))
}
pub fn settle_unfinished_entry() -> Result<(), String> {
if LOADER.with(|l| l.borrow().is_none()) {
return Ok(());
}
let pending = loader_call("mainUnsettled", Vec::new())?;
if matches!(pending, Value::Undef) {
return Ok(());
}
let stalled = with_host(|h| h.iter_vec(&pending)).unwrap_or_default();
let mut out = String::new();
for entry in stalled {
let pair = with_host(|h| h.iter_vec(&entry)).unwrap_or_default();
let url = with_host(|h| h.str_of(pair.first().unwrap_or(&Value::Undef)));
let pos = pair.get(1).map_or(0, host::suspended_await_pos);
out.push_str("Warning: Detected unsettled top-level await at ");
match with_host(|h| host::source_arrow(h, pos)) {
Some(arrow) => {
out.push_str(&arrow);
out.push_str("\n\n\n");
}
None => {
out.push_str(&url);
out.push('\n');
}
}
}
with_host(|h| {
h.write_out(&out, true);
h.exit_code.get_or_insert(13);
});
Ok(())
}