use std::collections::HashMap;
use crate::abi::type_registry::{ResolvedTypeRef, TypeRegistry};
use crate::abi::{ClassIR, EnumIR, FunctionIR, InterfaceIR, SpanIR, TypeAliasIR};
use crate::import_registry::ImportRegistry;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum MacroKind {
Derive,
Attribute,
Call,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TargetIR {
Class(ClassIR),
Enum(EnumIR),
Interface(InterfaceIR),
TypeAlias(TypeAliasIR),
Function(FunctionIR),
Other,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MacroContextIR {
pub abi_version: u32,
pub macro_kind: MacroKind,
pub macro_name: String,
pub module_path: String,
pub decorator_span: SpanIR,
#[serde(default)]
pub macro_name_span: Option<SpanIR>,
pub target_span: SpanIR,
pub file_name: String,
pub target: TargetIR,
pub target_source: String,
#[serde(default)]
pub import_registry: ImportRegistry,
#[serde(default)]
pub config: Option<crate::config::MacroforgeConfig>,
#[serde(default)]
pub type_registry: TypeRegistry,
#[serde(default)]
pub resolved_fields: Option<HashMap<String, ResolvedTypeRef>>,
}
impl MacroContextIR {
pub fn new_derive_class(
macro_name: String,
module_path: String,
decorator_span: SpanIR,
target_span: SpanIR,
file_name: String,
class: ClassIR,
target_source: String,
) -> Self {
Self {
abi_version: 1,
macro_kind: MacroKind::Derive,
macro_name,
module_path,
decorator_span,
macro_name_span: None,
target_span,
file_name,
target: TargetIR::Class(class),
target_source,
import_registry: ImportRegistry::new(),
config: None,
type_registry: TypeRegistry::default(),
resolved_fields: None,
}
}
pub fn with_macro_name_span(mut self, span: SpanIR) -> Self {
self.macro_name_span = Some(span);
self
}
pub fn error_span(&self) -> SpanIR {
self.macro_name_span.unwrap_or(self.decorator_span)
}
pub fn as_class(&self) -> Option<&ClassIR> {
match &self.target {
TargetIR::Class(class) => Some(class),
_ => None,
}
}
pub fn as_enum(&self) -> Option<&EnumIR> {
match &self.target {
TargetIR::Enum(enum_ir) => Some(enum_ir),
_ => None,
}
}
pub fn as_interface(&self) -> Option<&InterfaceIR> {
match &self.target {
TargetIR::Interface(interface_ir) => Some(interface_ir),
_ => None,
}
}
pub fn as_type_alias(&self) -> Option<&TypeAliasIR> {
match &self.target {
TargetIR::TypeAlias(type_alias_ir) => Some(type_alias_ir),
_ => None,
}
}
pub fn as_function(&self) -> Option<&FunctionIR> {
match &self.target {
TargetIR::Function(function_ir) => Some(function_ir),
_ => None,
}
}
pub fn new_derive_interface(
macro_name: String,
module_path: String,
decorator_span: SpanIR,
target_span: SpanIR,
file_name: String,
interface: InterfaceIR,
target_source: String,
) -> Self {
Self {
abi_version: 1,
macro_kind: MacroKind::Derive,
macro_name,
module_path,
decorator_span,
macro_name_span: None,
target_span,
file_name,
target: TargetIR::Interface(interface),
target_source,
import_registry: ImportRegistry::new(),
config: None,
type_registry: TypeRegistry::default(),
resolved_fields: None,
}
}
pub fn new_derive_type_alias(
macro_name: String,
module_path: String,
decorator_span: SpanIR,
target_span: SpanIR,
file_name: String,
type_alias: TypeAliasIR,
target_source: String,
) -> Self {
Self {
abi_version: 1,
macro_kind: MacroKind::Derive,
macro_name,
module_path,
decorator_span,
macro_name_span: None,
target_span,
file_name,
target: TargetIR::TypeAlias(type_alias),
target_source,
import_registry: ImportRegistry::new(),
config: None,
type_registry: TypeRegistry::default(),
resolved_fields: None,
}
}
pub fn new_derive_enum(
macro_name: String,
module_path: String,
decorator_span: SpanIR,
target_span: SpanIR,
file_name: String,
enum_ir: EnumIR,
target_source: String,
) -> Self {
Self {
abi_version: 1,
macro_kind: MacroKind::Derive,
macro_name,
module_path,
decorator_span,
macro_name_span: None,
target_span,
file_name,
target: TargetIR::Enum(enum_ir),
target_source,
import_registry: ImportRegistry::new(),
config: None,
type_registry: TypeRegistry::default(),
resolved_fields: None,
}
}
pub fn new_attribute_function(
macro_name: String,
module_path: String,
decorator_span: SpanIR,
target_span: SpanIR,
file_name: String,
function_ir: FunctionIR,
target_source: String,
) -> Self {
Self {
abi_version: 1,
macro_kind: MacroKind::Attribute,
macro_name,
module_path,
decorator_span,
macro_name_span: None,
target_span,
file_name,
target: TargetIR::Function(function_ir),
target_source,
import_registry: ImportRegistry::new(),
config: None,
type_registry: TypeRegistry::default(),
resolved_fields: None,
}
}
pub fn new_attribute_class(
macro_name: String,
module_path: String,
decorator_span: SpanIR,
target_span: SpanIR,
file_name: String,
class: ClassIR,
target_source: String,
) -> Self {
Self {
abi_version: 1,
macro_kind: MacroKind::Attribute,
macro_name,
module_path,
decorator_span,
macro_name_span: None,
target_span,
file_name,
target: TargetIR::Class(class),
target_source,
import_registry: ImportRegistry::new(),
config: None,
type_registry: TypeRegistry::default(),
resolved_fields: None,
}
}
pub fn new_attribute_interface(
macro_name: String,
module_path: String,
decorator_span: SpanIR,
target_span: SpanIR,
file_name: String,
interface: InterfaceIR,
target_source: String,
) -> Self {
Self {
abi_version: 1,
macro_kind: MacroKind::Attribute,
macro_name,
module_path,
decorator_span,
macro_name_span: None,
target_span,
file_name,
target: TargetIR::Interface(interface),
target_source,
import_registry: ImportRegistry::new(),
config: None,
type_registry: TypeRegistry::default(),
resolved_fields: None,
}
}
pub fn new_attribute_enum(
macro_name: String,
module_path: String,
decorator_span: SpanIR,
target_span: SpanIR,
file_name: String,
enum_ir: EnumIR,
target_source: String,
) -> Self {
Self {
abi_version: 1,
macro_kind: MacroKind::Attribute,
macro_name,
module_path,
decorator_span,
macro_name_span: None,
target_span,
file_name,
target: TargetIR::Enum(enum_ir),
target_source,
import_registry: ImportRegistry::new(),
config: None,
type_registry: TypeRegistry::default(),
resolved_fields: None,
}
}
pub fn new_attribute_type_alias(
macro_name: String,
module_path: String,
decorator_span: SpanIR,
target_span: SpanIR,
file_name: String,
type_alias: TypeAliasIR,
target_source: String,
) -> Self {
Self {
abi_version: 1,
macro_kind: MacroKind::Attribute,
macro_name,
module_path,
decorator_span,
macro_name_span: None,
target_span,
file_name,
target: TargetIR::TypeAlias(type_alias),
target_source,
import_registry: ImportRegistry::new(),
config: None,
type_registry: TypeRegistry::default(),
resolved_fields: None,
}
}
pub fn import_specifier_for(&self, type_name: &str) -> Option<String> {
if let Some(existing) = self.import_registry.get_source(type_name)
&& !existing.is_empty()
{
return Some(existing.to_string());
}
let entry = self.type_registry.types.get(type_name)?;
if entry.file_path == self.file_name {
return None;
}
relative_module_specifier(&self.file_name, &entry.file_path)
}
}
fn relative_module_specifier(current_file: &str, target_file: &str) -> Option<String> {
use std::path::Path;
let from = Path::new(current_file).parent()?;
let to = Path::new(target_file);
let rel = pathdiff::diff_paths(to, from)?;
let mut s = rel.to_string_lossy().replace('\\', "/");
if let Some(stripped) = s.strip_suffix(".svelte.ts") {
s = format!("{stripped}.svelte");
} else if let Some(stripped) = s.strip_suffix(".tsx") {
s = stripped.to_string();
} else if let Some(stripped) = s.strip_suffix(".ts") {
s = stripped.to_string();
}
if !s.starts_with('.') && !s.starts_with('/') {
s = format!("./{s}");
}
Some(s)
}
#[cfg(test)]
mod import_specifier_tests {
use super::*;
use crate::SpanIR;
use crate::abi::ir::interface::InterfaceIR;
use crate::abi::ir::type_registry::{TypeDefinitionIR, TypeRegistry, TypeRegistryEntry};
fn empty_interface(name: &str) -> InterfaceIR {
InterfaceIR {
name: name.to_string(),
span: SpanIR::new(0, 0),
body_span: SpanIR::new(0, 0),
type_params: vec![],
heritage: vec![],
fields: vec![],
methods: vec![],
decorators: vec![],
}
}
fn make_ctx(file_name: &str) -> MacroContextIR {
MacroContextIR {
abi_version: 1,
macro_kind: MacroKind::Derive,
macro_name: "Test".to_string(),
module_path: "@test".to_string(),
decorator_span: SpanIR::new(0, 0),
macro_name_span: None,
target_span: SpanIR::new(0, 0),
file_name: file_name.to_string(),
target: TargetIR::Interface(empty_interface("Probe")),
target_source: String::new(),
import_registry: ImportRegistry::new(),
config: None,
type_registry: TypeRegistry::default(),
resolved_fields: None,
}
}
fn registry_with(name: &str, file_path: &str) -> TypeRegistry {
let mut reg = TypeRegistry::new();
reg.types.insert(
name.to_string(),
TypeRegistryEntry {
name: name.to_string(),
file_path: file_path.to_string(),
is_exported: true,
definition: TypeDefinitionIR::Interface(empty_interface(name)),
file_imports: vec![],
},
);
reg
}
#[test]
fn existing_import_takes_priority() {
let mut ctx = make_ctx("/foo/order.svelte.ts");
ctx.import_registry.install_source_imports(vec![
crate::import_registry::SourceImportEntry {
local_name: "Customer".to_string(),
source_module: "./customer.svelte".to_string(),
original_name: None,
is_type_only: true,
},
]);
ctx.type_registry = registry_with("Customer", "/totally/different/path.svelte.ts");
assert_eq!(
ctx.import_specifier_for("Customer"),
Some("./customer.svelte".to_string())
);
}
#[test]
fn co_located_returns_none() {
let mut ctx = make_ctx("/foo/bar.svelte.ts");
ctx.type_registry = registry_with("Bar", "/foo/bar.svelte.ts");
assert_eq!(ctx.import_specifier_for("Bar"), None);
}
#[test]
fn sibling_file() {
let mut ctx = make_ctx("/foo/order.svelte.ts");
ctx.type_registry = registry_with("Customer", "/foo/customer.svelte.ts");
assert_eq!(
ctx.import_specifier_for("Customer"),
Some("./customer.svelte".to_string())
);
}
#[test]
fn nested_subdir() {
let mut ctx = make_ctx("/foo/order.svelte.ts");
ctx.type_registry = registry_with("Customer", "/foo/sub/customer.svelte.ts");
assert_eq!(
ctx.import_specifier_for("Customer"),
Some("./sub/customer.svelte".to_string())
);
}
#[test]
fn parent_dir() {
let mut ctx = make_ctx("/foo/sub/order.svelte.ts");
ctx.type_registry = registry_with("Customer", "/foo/customer.svelte.ts");
assert_eq!(
ctx.import_specifier_for("Customer"),
Some("../customer.svelte".to_string())
);
}
#[test]
fn unknown_type() {
let ctx = make_ctx("/foo/order.svelte.ts");
assert_eq!(ctx.import_specifier_for("Customer"), None);
}
#[test]
fn plain_ts_file() {
let mut ctx = make_ctx("/foo/order.svelte.ts");
ctx.type_registry = registry_with("Util", "/foo/util.ts");
assert_eq!(ctx.import_specifier_for("Util"), Some("./util".to_string()));
}
#[test]
fn tsx_file() {
let mut ctx = make_ctx("/foo/order.svelte.ts");
ctx.type_registry = registry_with("Component", "/foo/component.tsx");
assert_eq!(
ctx.import_specifier_for("Component"),
Some("./component".to_string())
);
}
}