use std::cell::RefCell;
use std::collections::HashMap;
use indexmap::IndexMap;
use crate::abi::ir::type_registry::FileImportEntry;
pub fn collect_file_imports(program: &oxc::ast::ast::Program<'_>) -> Vec<FileImportEntry> {
use oxc::ast::ast::*;
let mut imports = Vec::new();
for stmt in &program.body {
if let Statement::ImportDeclaration(import) = stmt {
let module_specifier = import.source.value.to_string();
let is_type_only = import.import_kind.is_type();
if let Some(specifiers) = &import.specifiers {
for specifier in specifiers {
match specifier {
ImportDeclarationSpecifier::ImportSpecifier(s) => {
let local = s.local.name.to_string();
let original = if s.imported.name() != s.local.name {
Some(s.imported.name().to_string())
} else {
None
};
imports.push(FileImportEntry {
local_name: local,
module_specifier: module_specifier.clone(),
original_name: original,
is_type_only: is_type_only || s.import_kind.is_type(),
});
}
ImportDeclarationSpecifier::ImportDefaultSpecifier(s) => {
imports.push(FileImportEntry {
local_name: s.local.name.to_string(),
module_specifier: module_specifier.clone(),
original_name: Some("default".to_string()),
is_type_only,
});
}
ImportDeclarationSpecifier::ImportNamespaceSpecifier(s) => {
imports.push(FileImportEntry {
local_name: s.local.name.to_string(),
module_specifier: module_specifier.clone(),
original_name: Some("*".to_string()),
is_type_only,
});
}
}
}
}
}
}
imports
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SourceImport {
pub source_module: String,
pub original_name: Option<String>,
pub is_type_only: bool,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SourceImportEntry {
pub local_name: String,
pub source_module: String,
pub original_name: Option<String>,
pub is_type_only: bool,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GeneratedImport {
pub local_name: String,
pub source_module: String,
pub original_name: Option<String>,
pub is_type_only: bool,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ImportRegistry {
source_imports: HashMap<String, SourceImport>,
generated: IndexMap<String, GeneratedImport>,
#[serde(default)]
borrowed: HashMap<String, SourceImport>,
}
impl Default for ImportRegistry {
fn default() -> Self {
Self::new()
}
}
impl ImportRegistry {
pub fn new() -> Self {
Self {
source_imports: HashMap::new(),
generated: IndexMap::new(),
borrowed: HashMap::new(),
}
}
pub fn from_program(program: &oxc::ast::ast::Program<'_>, source: &str) -> Self {
use oxc::ast::ast::*;
let mut source_imports = HashMap::new();
source_imports.extend(
macro_imports_in_comments(&program.comments, source)
.into_iter()
.map(|(name, module_src)| {
(
name,
SourceImport {
source_module: module_src,
original_name: None,
is_type_only: false,
},
)
}),
);
for stmt in &program.body {
if let Statement::ImportDeclaration(import) = stmt {
let source_module = import.source.value.to_string();
if let Some(specifiers) = &import.specifiers {
for specifier in specifiers {
match specifier {
ImportDeclarationSpecifier::ImportSpecifier(s) => {
let local_name = s.local.name.to_string();
let original_name = if s.imported.name() != s.local.name {
Some(s.imported.name().to_string())
} else {
None
};
source_imports.insert(
local_name,
SourceImport {
source_module: source_module.clone(),
original_name,
is_type_only: import.import_kind.is_type()
|| s.import_kind.is_type(),
},
);
}
ImportDeclarationSpecifier::ImportDefaultSpecifier(s) => {
source_imports.insert(
s.local.name.to_string(),
SourceImport {
source_module: source_module.clone(),
original_name: Some("default".to_string()),
is_type_only: import.import_kind.is_type(),
},
);
}
ImportDeclarationSpecifier::ImportNamespaceSpecifier(s) => {
source_imports.insert(
s.local.name.to_string(),
SourceImport {
source_module: source_module.clone(),
original_name: Some("*".to_string()),
is_type_only: import.import_kind.is_type(),
},
);
}
}
}
}
}
}
Self {
source_imports,
generated: IndexMap::new(),
borrowed: HashMap::new(),
}
}
pub fn is_available(&self, name: &str) -> bool {
self.source_imports.contains_key(name) || self.generated.contains_key(name)
}
pub fn is_type_only(&self, name: &str) -> bool {
self.source_imports
.get(name)
.map(|si| si.is_type_only)
.unwrap_or(false)
}
pub fn get_source(&self, name: &str) -> Option<&str> {
self.source_imports
.get(name)
.or_else(|| self.borrowed.get(name))
.map(|si| si.source_module.as_str())
}
pub fn resolve_alias(&self, name: &str) -> Option<&str> {
self.source_imports
.get(name)
.or_else(|| self.borrowed.get(name))
.and_then(|si| si.original_name.as_deref())
}
pub fn borrow_import(
&mut self,
local_name: &str,
original_name: Option<&str>,
module: &str,
is_type_only: bool,
) {
self.request_import(local_name, original_name, module, is_type_only);
self.borrowed.insert(
local_name.to_string(),
SourceImport {
source_module: module.to_string(),
original_name: original_name.map(str::to_string),
is_type_only,
},
);
}
pub fn source_map(&self) -> &HashMap<String, SourceImport> {
&self.source_imports
}
pub fn source_modules(&self) -> HashMap<String, String> {
self.source_imports
.iter()
.map(|(name, si)| (name.clone(), si.source_module.clone()))
.collect()
}
pub fn aliases(&self) -> HashMap<String, String> {
self.source_imports
.iter()
.filter_map(|(name, si)| {
si.original_name
.as_ref()
.map(|orig| (name.clone(), orig.clone()))
})
.collect()
}
pub fn source_import_entries(&self) -> Vec<SourceImportEntry> {
self.source_imports
.iter()
.map(|(name, si)| SourceImportEntry {
local_name: name.clone(),
source_module: si.source_module.clone(),
original_name: si.original_name.clone(),
is_type_only: si.is_type_only,
})
.collect()
}
pub fn file_import_entries(&self) -> Vec<crate::abi::ir::type_registry::FileImportEntry> {
use crate::abi::ir::type_registry::FileImportEntry;
self.source_imports
.iter()
.map(|(name, si)| FileImportEntry {
local_name: name.clone(),
module_specifier: si.source_module.clone(),
original_name: si.original_name.clone(),
is_type_only: si.is_type_only,
})
.collect()
}
pub fn install_source_imports(&mut self, entries: Vec<SourceImportEntry>) {
for entry in entries {
self.source_imports.insert(
entry.local_name,
SourceImport {
source_module: entry.source_module,
original_name: entry.original_name,
is_type_only: entry.is_type_only,
},
);
}
}
pub fn request_import(
&mut self,
local_name: &str,
original_name: Option<&str>,
module: &str,
is_type_only: bool,
) {
if local_name.contains('.') {
return;
}
if self.source_imports.contains_key(local_name) {
return;
}
if let Some(existing) = self.generated.get_mut(local_name) {
existing.is_type_only &= is_type_only;
return;
}
self.generated.insert(
local_name.to_string(),
GeneratedImport {
local_name: local_name.to_string(),
source_module: module.to_string(),
original_name: original_name.map(|s| s.to_string()),
is_type_only,
},
);
}
pub fn request_namespace_import(&mut self, namespace: &str, module: &str, alias: &str) {
if let Some(si) = self.source_imports.get(namespace)
&& !si.is_type_only
{
return;
}
if self.generated.contains_key(alias) {
return;
}
self.generated.insert(
alias.to_string(),
GeneratedImport {
local_name: alias.to_string(),
source_module: module.to_string(),
original_name: Some(namespace.to_string()),
is_type_only: false,
},
);
}
pub fn request_type_import(&mut self, name: &str, module: &str) {
self.request_import(name, None, module, true);
}
pub fn generated_imports(&self) -> impl Iterator<Item = &GeneratedImport> {
self.generated.values()
}
pub fn take_generated_imports(&mut self) -> Vec<GeneratedImport> {
std::mem::take(&mut self.generated).into_values().collect()
}
pub fn merge_imports(&mut self, imports: Vec<GeneratedImport>) {
for import in imports {
if self.source_imports.contains_key(&import.local_name) {
continue;
}
match self.generated.entry(import.local_name.clone()) {
indexmap::map::Entry::Occupied(mut entry) => {
entry.get_mut().is_type_only &= import.is_type_only;
}
indexmap::map::Entry::Vacant(entry) => {
entry.insert(import);
}
}
}
}
pub fn emit_generated_imports(&self) -> String {
let mut declarations: IndexMap<(&str, bool), Vec<String>> = IndexMap::new();
for import in self.generated.values() {
let specifier = match &import.original_name {
Some(original) => format!("{original} as {}", import.local_name),
None => import.local_name.clone(),
};
declarations
.entry((import.source_module.as_str(), import.is_type_only))
.or_default()
.push(specifier);
}
let mut lines = String::new();
for ((module, is_type_only), specifiers) in declarations {
let keyword = if is_type_only {
"import type"
} else {
"import"
};
lines.push_str(&format!(
"{keyword} {{ {} }} from \"{module}\";\n",
specifiers.join(", ")
));
}
lines
}
}
thread_local! {
static IMPORT_REGISTRY: RefCell<ImportRegistry> = RefCell::new(ImportRegistry::new());
}
pub fn with_registry<R>(f: impl FnOnce(&ImportRegistry) -> R) -> R {
IMPORT_REGISTRY.with(|r| f(&r.borrow()))
}
pub fn with_registry_mut<R>(f: impl FnOnce(&mut ImportRegistry) -> R) -> R {
IMPORT_REGISTRY.with(|r| f(&mut r.borrow_mut()))
}
pub fn install_registry(registry: ImportRegistry) {
IMPORT_REGISTRY.with(|r| {
*r.borrow_mut() = registry;
});
}
pub fn take_registry() -> ImportRegistry {
IMPORT_REGISTRY.with(|r| std::mem::take(&mut *r.borrow_mut()))
}
pub fn clear_registry() {
IMPORT_REGISTRY.with(|r| {
*r.borrow_mut() = ImportRegistry::new();
});
}
pub fn macro_imports_in_comments(
comments: &[oxc::ast::Comment],
source: &str,
) -> HashMap<String, String> {
let mut out = HashMap::new();
for comment in comments.iter().filter(|comment| comment.is_block()) {
let Some(text) = source.get(comment.span.start as usize..comment.span.end as usize) else {
continue;
};
if let Some(body) = text
.strip_prefix("/**")
.and_then(|rest| rest.strip_suffix("*/"))
{
insert_macro_import_directive(&mut out, body);
}
}
out
}
fn insert_macro_import_directive(out: &mut HashMap<String, String>, body: &str) {
if !crate::jsdoc::is_macro_import_comment(body) {
return;
}
let normalized = normalize_macro_import_body(body);
let Some(open_brace) = normalized.find('{') else {
return;
};
let Some(close_brace) = normalized[open_brace..]
.find('}')
.map(|offset| open_brace + offset)
else {
return;
};
let Some(from_offset) = normalized[close_brace..].to_ascii_lowercase().find("from") else {
return;
};
let Some(module) =
extract_quoted_string(&normalized[close_brace + from_offset + "from".len()..])
else {
return;
};
for name in normalized[open_brace + 1..close_brace].split(',') {
let name = name.trim();
if !name.is_empty() {
out.insert(name.to_string(), module.clone());
}
}
}
fn normalize_macro_import_body(body: &str) -> String {
let mut normalized = String::new();
for line in body.lines() {
let mut trimmed = line.trim();
if let Some(stripped) = trimmed.strip_prefix('*') {
trimmed = stripped.trim();
}
if trimmed.is_empty() {
continue;
}
if !normalized.is_empty() {
normalized.push(' ');
}
normalized.push_str(trimmed);
}
normalized
}
fn extract_quoted_string(input: &str) -> Option<String> {
for (idx, ch) in input.char_indices() {
if ch == '"' || ch == '\'' {
let start = idx + 1;
let rest = &input[start..];
if let Some(end) = rest.find(ch) {
return Some(rest[..end].trim().to_string());
}
break;
}
}
None
}
#[cfg(test)]
mod tests {
use super::macro_imports_in_comments;
use oxc::allocator::Allocator;
use oxc::parser::Parser;
use oxc::span::SourceType;
use std::collections::HashMap;
fn macro_imports(source: &str) -> HashMap<String, String> {
let allocator = Allocator::default();
let parsed = Parser::new(&allocator, source, SourceType::ts()).parse();
macro_imports_in_comments(&parsed.program.comments, source)
}
#[test]
fn imports_from_one_module_share_a_declaration() {
let mut registry = super::ImportRegistry::new();
registry.request_import("__foreign__aEncode", None, "#macroforge/config", false);
registry.request_import("__mf_Ctx", Some("Ctx"), "pkg", false);
registry.request_import("__foreign__aDefault", None, "#macroforge/config", false);
registry.request_import("__mf_Options", Some("Options"), "pkg", true);
registry.request_import("__mf_Error", Some("Error"), "pkg", false);
assert_eq!(
registry.emit_generated_imports(),
"import { __foreign__aEncode, __foreign__aDefault } from \"#macroforge/config\";\n\
import { Ctx as __mf_Ctx, Error as __mf_Error } from \"pkg\";\n\
import type { Options as __mf_Options } from \"pkg\";\n"
);
}
#[test]
fn no_generated_imports_emit_nothing() {
assert_eq!(super::ImportRegistry::new().emit_generated_imports(), "");
}
#[test]
fn a_value_request_upgrades_a_type_only_import() {
for type_first in [true, false] {
let mut registry = super::ImportRegistry::new();
let requests = if type_first {
[true, false]
} else {
[false, true]
};
for is_type_only in requests {
registry.request_import("__mf_Ctx", Some("Ctx"), "pkg", is_type_only);
}
assert_eq!(
registry.emit_generated_imports().trim(),
"import { Ctx as __mf_Ctx } from \"pkg\";",
"type-only requested first: {type_first}"
);
}
}
#[test]
fn reads_an_import_macro_comment() {
let imports = macro_imports(
"/** import macro { Gigaform, $vec } from \"@testground/macro\"; */\nexport {};",
);
assert_eq!(
imports.get("Gigaform").map(String::as_str),
Some("@testground/macro")
);
assert_eq!(
imports.get("$vec").map(String::as_str),
Some("@testground/macro")
);
}
#[test]
fn the_directive_text_inside_a_string_is_not_an_import() {
let source = "const hint = '`/** import macro {Name} from \"your-package\"; */`';";
assert!(macro_imports(source).is_empty());
}
#[test]
fn an_example_inside_a_doc_comment_is_not_an_import() {
let source = "/**\n * Imported via `import macro {Name} from \"package\"`.\n */\nexport function hover() {}";
assert!(macro_imports(source).is_empty());
}
}