use std::collections::{HashMap, HashSet};
use std::fmt::{self, Write};
use std::path::Path;
use oxc_allocator::Allocator;
use oxc_ast::ast::*;
#[must_use]
pub fn sanitize_module_name(raw: &str) -> String {
let mut result = String::new();
for ch in raw.chars() {
if ch.is_ascii_alphanumeric() || ch == '_' {
result.push(ch);
} else {
let _ = write!(result, "_u{:04x}", ch as u32);
}
}
if result.is_empty() {
result.push_str("_unnamed");
}
if !result.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') {
result.insert(0, '_');
}
if result == "lib" {
result.push_str("_mod");
}
result
}
fn sanitize_name(filename: &str) -> String {
let stem = filename.strip_suffix(".js").unwrap_or(filename);
sanitize_module_name(stem)
}
pub struct AnalysisResult {
pub entry_name: String,
pub members: Vec<String>,
pub name_map: HashMap<String, String>,
pub imported_names: HashMap<String, Vec<(String, String)>>,
pub exported_names: HashMap<String, HashSet<String>>,
pub all_fn_names: HashMap<String, HashSet<String>>,
pub file_sources: HashMap<String, String>,
pub parsed_programs: HashMap<String, Program<'static>>,
}
impl fmt::Debug for AnalysisResult {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AnalysisResult")
.field("entry_name", &self.entry_name)
.field("members", &self.members)
.field("name_map", &self.name_map)
.field("imported_names", &self.imported_names)
.field("exported_names", &self.exported_names)
.field("all_fn_names", &self.all_fn_names)
.field(
"file_sources",
&format_args!("{} files", self.file_sources.len()),
)
.field(
"parsed_programs",
&format_args!("{} programs", self.parsed_programs.len()),
)
.finish()
}
}
pub fn analyze_project(in_dir: &Path, js_files: &[String]) -> Result<AnalysisResult, String> {
assert!(!js_files.is_empty(), "js_files must not be empty");
let primary_root = &js_files[0];
let mut visited: HashSet<String> = HashSet::new();
let mut stack: Vec<String> = js_files.to_vec();
stack.reverse();
let mut imports: HashMap<String, Vec<String>> = HashMap::new();
let mut imported_names: HashMap<String, Vec<(String, String)>> = HashMap::new();
let mut exported_names: HashMap<String, HashSet<String>> = HashMap::new();
let mut all_fn_names: HashMap<String, HashSet<String>> = HashMap::new();
let mut file_sources: HashMap<String, String> = HashMap::new();
let mut parsed_programs: HashMap<String, Program<'static>> = HashMap::new();
let mut sanitized: HashMap<String, String> = HashMap::new();
while let Some(cur) = stack.pop() {
if !visited.insert(cur.clone()) {
continue;
}
let src = std::fs::read_to_string(in_dir.join(&cur))
.map_err(|e| format!("Cannot read '{}': {}", cur, e))?;
let allocator: &'static Allocator = {
use std::sync::atomic::{AtomicPtr, Ordering};
static ALLOC_PTR: AtomicPtr<Allocator> = AtomicPtr::new(std::ptr::null_mut());
let ptr = ALLOC_PTR.load(Ordering::Acquire);
if !ptr.is_null() {
unsafe { &*ptr }
} else {
let leaked: &'static mut Allocator = Box::leak(Box::new(Allocator::default()));
ALLOC_PTR.store(leaked as *mut Allocator, Ordering::Release);
leaked
}
};
let src_static: &'static str = Box::leak(src.clone().into_boxed_str());
let program: Program<'static> = crate::parser::parse_with_name(allocator, src_static, &cur);
let info = analyze_module_ast(&program);
for dep in &info.imported_files {
if !visited.contains(dep.as_str()) {
stack.push(dep.clone());
}
}
sanitized.insert(cur.clone(), sanitize_name(&cur));
imports.insert(cur.clone(), info.imported_files);
imported_names.insert(cur.clone(), info.imported_names);
exported_names.insert(cur.clone(), info.exported_names);
all_fn_names.insert(cur.clone(), info.all_toplevel_fn_names);
file_sources.insert(cur.clone(), src);
parsed_programs.insert(cur, program);
}
let members = transitive_deps_multi(js_files, &imports);
let entry_name = sanitized
.get(primary_root)
.cloned()
.unwrap_or_else(|| sanitize_name(primary_root));
Ok(AnalysisResult {
entry_name,
members,
name_map: sanitized,
imported_names,
exported_names,
all_fn_names,
file_sources,
parsed_programs,
})
}
fn transitive_deps_multi(roots: &[String], imports: &HashMap<String, Vec<String>>) -> Vec<String> {
let mut visited: HashSet<String> = HashSet::new();
let mut stack: Vec<String> = roots.to_vec();
let mut result: Vec<String> = Vec::new();
while let Some(cur) = stack.pop() {
if !visited.insert(cur.clone()) {
continue;
}
result.push(cur.clone());
if let Some(deps) = imports.get(&cur) {
for dep in deps {
if !visited.contains(dep.as_str()) {
stack.push(dep.clone());
}
}
}
}
result.reverse();
result
}
fn path_to_filename(path: &str) -> Option<String> {
let fname = Path::new(path).file_name()?.to_string_lossy().to_string();
if fname.ends_with(".js") {
Some(fname)
} else {
Some(format!("{}.js", fname))
}
}
struct ModuleInfo {
imported_files: Vec<String>,
imported_names: Vec<(String, String)>,
exported_names: HashSet<String>,
all_toplevel_fn_names: HashSet<String>,
}
fn analyze_module_ast(program: &Program) -> ModuleInfo {
let mut imported_files = Vec::new();
let mut imported_names = Vec::new();
let mut exported_names = HashSet::new();
let mut all_toplevel_fn_names = HashSet::new();
for stmt in &program.body {
match stmt {
Statement::ImportDeclaration(import) => {
let source_str = import.source.value.as_str();
if let Some(sf) = path_to_filename(source_str) {
imported_files.push(sf.clone());
if let Some(specifiers) = &import.specifiers {
for spec in specifiers {
let name = match spec {
ImportDeclarationSpecifier::ImportSpecifier(s) => {
s.local.name.as_str().to_string()
}
ImportDeclarationSpecifier::ImportDefaultSpecifier(s) => {
s.local.name.as_str().to_string()
}
ImportDeclarationSpecifier::ImportNamespaceSpecifier(s) => {
s.local.name.as_str().to_string()
}
};
imported_names.push((name, sf.clone()));
}
}
}
}
Statement::ExportNamedDeclaration(e) => {
if let Some(decl) = &e.declaration {
match decl {
Declaration::FunctionDeclaration(fd) => {
if let Some(id) = &fd.id {
let name = id.name.as_str().to_string();
exported_names.insert(name.clone());
all_toplevel_fn_names.insert(name);
}
}
Declaration::VariableDeclaration(vd) => {
for d in &vd.declarations {
if let BindingPattern::BindingIdentifier(id) = &d.id {
exported_names.insert(id.name.as_str().to_string());
}
}
}
Declaration::ClassDeclaration(cd) => {
if let Some(id) = &cd.id {
exported_names.insert(id.name.as_str().to_string());
}
}
_ => {}
}
}
for spec in &e.specifiers {
if let ModuleExportName::IdentifierName(id) = &spec.exported {
exported_names.insert(id.name.as_str().to_string());
}
}
}
Statement::ExportDefaultDeclaration(e) => {
if let Some(name) = match &e.declaration {
ExportDefaultDeclarationKind::FunctionDeclaration(fd) => {
fd.id.as_ref().map(|id| id.name.as_str().to_string())
}
ExportDefaultDeclarationKind::ClassDeclaration(cd) => {
cd.id.as_ref().map(|id| id.name.as_str().to_string())
}
_ => None,
} {
exported_names.insert(name.clone());
all_toplevel_fn_names.insert(name);
}
}
Statement::FunctionDeclaration(fd) => {
if let Some(id) = &fd.id {
all_toplevel_fn_names.insert(id.name.as_str().to_string());
}
}
Statement::ExpressionStatement(es) => {
if let Some(names) = extract_module_exports(es) {
for name in names {
exported_names.insert(name);
}
}
}
_ => {}
}
}
imported_files.sort();
imported_files.dedup();
imported_names.sort();
imported_names.dedup();
ModuleInfo {
imported_files,
imported_names,
exported_names,
all_toplevel_fn_names,
}
}
fn extract_module_exports(es: &ExpressionStatement) -> Option<Vec<String>> {
use oxc_ast::ast::AssignmentTarget;
let Expression::AssignmentExpression(assign) = &es.expression else {
return None;
};
let AssignmentTarget::StaticMemberExpression(lhs) = &assign.left else {
return None;
};
let Expression::Identifier(obj) = &lhs.object else {
return None;
};
if obj.name.as_str() != "module" {
return None;
}
if lhs.property.name.as_str() != "exports" {
return None;
}
match &assign.right {
Expression::ObjectExpression(obj) => {
let names: Vec<String> = obj
.properties
.iter()
.filter_map(|p| match p {
ObjectPropertyKind::ObjectProperty(op) => match &op.key {
PropertyKey::StaticIdentifier(id) => Some(id.name.as_str().to_string()),
_ => None,
},
_ => None,
})
.collect();
if names.is_empty() { None } else { Some(names) }
}
_ => None,
}
}