use syn::spanned::Spanned;
use syn::{ImplItem, ImplItemFn, Item, ItemImpl, ItemStruct, Type, Visibility};
use crate::attrs::{derive_list, is_julia_attr, rustcall_attribute};
use crate::manifest::{Attribute, Mode};
#[derive(Debug, Clone)]
pub struct ImplSite {
pub module_path: Vec<String>,
pub self_ty: Type,
}
#[derive(Debug, Clone)]
pub struct ImplHost {
pub generics: syn::Generics,
pub self_ty: Type,
pub trait_: Option<syn::Path>,
}
impl ImplHost {
pub fn of(imp: &ItemImpl) -> Self {
ImplHost {
generics: imp.generics.clone(),
self_ty: (*imp.self_ty).clone(),
trait_: imp.trait_.as_ref().map(|(_, path, _)| path.clone()),
}
}
}
#[derive(Debug, Clone)]
pub struct MethodModel {
pub func: ImplItemFn,
pub attribute: Attribute,
pub enclosing_cfg: Vec<syn::Attribute>,
pub site: Option<ImplSite>,
pub host: Option<ImplHost>,
pub returns_own_type_resolved: bool,
}
impl MethodModel {
pub fn from_fn(func: &ImplItemFn, attribute: Attribute) -> Self {
MethodModel {
func: func.clone(),
attribute,
enclosing_cfg: Vec::new(),
site: None,
host: None,
returns_own_type_resolved: false,
}
}
pub fn name(&self) -> String {
self.func.sig.ident.to_string()
}
pub fn receiver(&self) -> crate::receiver::Receiver {
crate::receiver::Receiver::of(&self.func.sig, self.host.as_ref().map(|h| &h.self_ty))
}
pub fn is_static(&self) -> bool {
self.receiver().is_static()
}
pub fn is_mutable(&self) -> bool {
self.receiver().is_mutable()
}
pub fn trait_path(&self) -> String {
self.host
.as_ref()
.and_then(|h| h.trait_.as_ref())
.map(|path| {
crate::types::type_to_string(&syn::Type::Path(syn::TypePath {
qself: None,
path: path.clone(),
}))
})
.unwrap_or_default()
}
pub fn method_stem(&self) -> String {
let trait_name = self
.host
.as_ref()
.and_then(|h| h.trait_.as_ref())
.and_then(crate::codegen::trait_name_of);
crate::codegen::method_stem(trait_name.as_deref(), &self.name())
}
pub fn returns_boxed_struct(&self, struct_name: &syn::Ident) -> bool {
self.returns_own_type_resolved
|| crate::codegen::returns_own_type(
&self.func.sig.output,
struct_name,
self.host.as_ref().map(|h| &h.self_ty),
)
}
pub fn fallible_constructor(
&self,
struct_name: &syn::Ident,
) -> Option<crate::types::ResultTypeInfo> {
if !self.receiver().is_static() || !self.trait_path().is_empty() {
return None;
}
self.boxed_self_result(struct_name)
}
pub fn boxed_self_result(
&self,
struct_name: &syn::Ident,
) -> Option<crate::types::ResultTypeInfo> {
let syn::ReturnType::Type(_, ty) = &self.func.sig.output else {
return None;
};
let result = crate::types::extract_result_type(ty)?;
if !crate::refusal::payload_is_representable(&result.err_type) {
return None;
}
let output = syn::ReturnType::Type(Default::default(), Box::new(result.ok_type.clone()));
crate::codegen::returns_own_type(
&output,
struct_name,
self.host.as_ref().map(|h| &h.self_ty),
)
.then_some(result)
}
pub fn is_constructor(&self, struct_name: &syn::Ident) -> bool {
self.trait_path().is_empty()
&& (self.returns_boxed_struct(struct_name)
|| self.fallible_constructor(struct_name).is_some())
}
pub fn is_same_method(&self, other: &MethodModel) -> bool {
self.name() == other.name() && self.trait_path() == other.trait_path()
}
pub fn is_local_to(&self, struct_module_path: &[String]) -> bool {
self.site
.as_ref()
.is_none_or(|site| site.module_path == struct_module_path)
}
}
#[derive(Debug, Clone)]
pub struct StructModel {
pub item: ItemStruct,
pub attribute: Attribute,
pub derives: Vec<String>,
pub impls: Vec<ItemImpl>,
pub methods: Vec<MethodModel>,
pub line: usize,
}
impl StructModel {
pub fn name(&self) -> String {
self.item.ident.to_string()
}
pub fn is_generic(&self) -> bool {
crate::types::has_type_params(&self.item.generics)
}
pub fn type_param_names(&self) -> Vec<String> {
self.item
.generics
.params
.iter()
.filter_map(|p| match p {
syn::GenericParam::Type(tp) => Some(tp.ident.to_string()),
_ => None,
})
.collect()
}
pub fn field_cfg_attrs(&self, name: &syn::Ident) -> Vec<syn::Attribute> {
match &self.item.fields {
syn::Fields::Named(named) => named
.named
.iter()
.find(|f| f.ident.as_ref() == Some(name))
.map(|f| crate::cfg::cfg_attrs(&f.attrs))
.unwrap_or_default(),
_ => Vec::new(),
}
}
pub fn named_fields(&self) -> Vec<(syn::Ident, Type)> {
match &self.item.fields {
syn::Fields::Named(named) => named
.named
.iter()
.filter_map(|f| f.ident.clone().map(|id| (id, f.ty.clone())))
.collect(),
_ => Vec::new(),
}
}
pub fn of(s: &ItemStruct, mode: Mode) -> Option<StructModel> {
let attribute = rustcall_attribute(&s.attrs);
let selected = matches!(
(mode, attribute),
(_, Attribute::Julia) | (Mode::Inline, Attribute::DeriveJuliaStruct)
);
if !selected {
return None;
}
Some(StructModel {
item: s.clone(),
attribute,
derives: derive_list(&s.attrs)
.into_iter()
.filter(|d| d != "JuliaStruct")
.collect(),
impls: Vec::new(),
methods: Vec::new(),
line: s.span().start().line,
})
}
pub fn attach_impl(
&mut self,
imp: &ItemImpl,
mode: Mode,
enclosing_cfg: &[syn::Attribute],
block_module: Option<&[String]>,
) {
self.attach_impl_resolving(imp, mode, enclosing_cfg, block_module, |_| false);
}
pub fn attach_impl_resolving(
&mut self,
imp: &ItemImpl,
mode: Mode,
enclosing_cfg: &[syn::Attribute],
block_module: Option<&[String]>,
names_self: impl Fn(&Type) -> bool,
) {
self.impls.push(imp.clone());
for mut m in wrapped_methods(imp, mode, enclosing_cfg) {
m.returns_own_type_resolved =
matches!(&m.func.sig.output, syn::ReturnType::Type(_, ty) if names_self(ty));
m.site = block_module.map(|path| ImplSite {
module_path: path.to_vec(),
self_ty: (*imp.self_ty).clone(),
});
if !self.methods.iter().any(|seen| seen.is_same_method(&m)) {
self.methods.push(m);
}
}
}
}
pub fn impl_has_julia(imp: &ItemImpl) -> bool {
imp.attrs.iter().any(is_julia_attr)
}
pub fn wrapped_methods(
imp: &ItemImpl,
mode: Mode,
enclosing_cfg: &[syn::Attribute],
) -> Vec<MethodModel> {
let has_julia = impl_has_julia(imp);
let block_cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &imp.attrs);
let impl_attribute = if has_julia {
Attribute::Julia
} else {
Attribute::None
};
imp.items
.iter()
.filter_map(|ii| match ii {
ImplItem::Fn(func) => Some(func),
_ => None,
})
.filter(|func| match mode {
Mode::Inline => matches!(func.vis, Visibility::Public(_)),
Mode::Crate => has_julia && func.attrs.iter().any(is_julia_attr),
})
.map(|func| {
let mut m = MethodModel::from_fn(func, impl_attribute);
m.enclosing_cfg = block_cfg.clone();
m.host = Some(ImplHost::of(imp));
m
})
.collect()
}
#[derive(Debug, Default)]
pub struct ModelTree {
borrow_scope: crate::borrow_scope::Scope,
entries: Vec<LocatedModel>,
imports: Vec<crate::paths::ScannedImport>,
}
#[derive(Debug)]
struct LocatedModel {
module_path: Vec<String>,
name: String,
model: StructModel,
}
#[derive(Debug)]
struct ScannedBlock {
item: ItemImpl,
header: crate::paths::ImplHeader,
enclosing_cfg: Vec<syn::Attribute>,
}
#[derive(Debug)]
struct Place {
module_path: Vec<String>,
name: String,
}
impl crate::paths::Located for Place {
fn name(&self) -> &str {
&self.name
}
fn module_path(&self) -> &[String] {
&self.module_path
}
}
impl crate::paths::Located for LocatedModel {
fn name(&self) -> &str {
&self.name
}
fn module_path(&self) -> &[String] {
&self.module_path
}
}
impl ModelTree {
pub fn collect(items: &[Item], mode: Mode) -> ModelTree {
let mut tree = ModelTree::default();
let runtime: syn::File =
syn::parse2(crate::codegen::panic_hook_items()).expect("valid runtime AST");
let runtime_types: Vec<Item> = runtime
.items
.into_iter()
.filter(|item| {
matches!(
item,
Item::Struct(_)
| Item::Enum(_)
| Item::Union(_)
| Item::Type(_)
| Item::Trait(_)
| Item::TraitAlias(_)
)
})
.collect();
tree.borrow_scope
.record(&runtime_types, &[], false, &[], mode);
let mut impls: Vec<ScannedBlock> = Vec::new();
let mut imports = Vec::new();
let mut path = Vec::new();
tree.walk(items, mode, &mut path, &[], &mut impls, &mut imports);
let places: Vec<Place> = tree
.entries
.iter()
.map(|e| Place {
module_path: e.module_path.clone(),
name: e.name.clone(),
})
.collect();
for block in &impls {
if let Ok(index) = crate::paths::locate(&tree.entries, &block.header, &imports) {
let names_self = |ty: &Type| {
crate::paths::names_struct(
&places,
index,
&block.item.self_ty,
ty,
&block.header.module_path,
&imports,
true,
)
};
tree.entries[index].model.attach_impl_resolving(
&block.item,
mode,
&block.enclosing_cfg,
Some(&block.header.module_path),
names_self,
);
}
}
for entry in &tree.entries {
let meta = crate::extract::crate_struct_entry(&entry.model, &entry.module_path, &[]);
tree.borrow_scope
.generated_struct(&meta, &entry.model, &entry.module_path);
}
tree.imports = imports;
tree
}
pub fn borrowed_handle(&self, ty: &Type, module_path: &[String]) -> Option<String> {
self.checked_borrowed_handle(ty, module_path).ok().flatten()
}
pub(crate) fn record_file_attrs(&mut self, attrs: &[syn::Attribute]) {
self.borrow_scope.record_context_attrs(attrs, &[]);
}
pub(crate) fn borrow_context_error(&self, scope: &[String]) -> Option<&'static str> {
self.borrow_scope.context_error(scope)
}
pub(crate) fn checked_borrowed_handle(
&self,
ty: &Type,
module_path: &[String],
) -> Result<Option<String>, &'static str> {
match self.borrow_scope.resolve(ty, module_path, true) {
crate::borrow_scope::Borrow::Owner(scope, name) => Ok(self
.entries
.iter()
.find(|e| crate::borrow_scope::same_item(&e.module_path, &e.name, &scope, &name))
.filter(|e| !e.model.is_generic())
.map(|e| crate::codegen::symbol_stem(&e.module_path, &e.name))),
crate::borrow_scope::Borrow::Plain => Ok(None),
crate::borrow_scope::Borrow::Unresolved(reason) => Err(reason),
}
}
fn walk(
&mut self,
items: &[Item],
mode: Mode,
path: &mut Vec<String>,
enclosing_cfg: &[syn::Attribute],
impls: &mut Vec<ScannedBlock>,
imports: &mut Vec<crate::paths::ScannedImport>,
) {
self.borrow_scope
.record(items, path, !enclosing_cfg.is_empty(), path, mode);
for item in items {
match item {
Item::Struct(s) => {
if let Some(model) = StructModel::of(s, mode) {
self.entries.push(LocatedModel {
module_path: path.clone(),
name: model.name(),
model,
});
}
}
Item::Impl(imp) => {
if let Some(header) = crate::paths::ImplHeader::of(imp, path) {
impls.push(ScannedBlock {
item: imp.clone(),
header,
enclosing_cfg: enclosing_cfg.to_vec(),
});
}
}
Item::Use(u) => imports.extend(crate::paths::imports_of_use(u, path)),
Item::Mod(m) => {
if let Some((_, inner)) = &m.content {
path.push(m.ident.to_string());
let cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &m.attrs);
self.walk(inner, mode, path, &cfg, impls, imports);
path.pop();
}
}
_ => {}
}
}
}
pub fn find(&self, module_path: &[String], name: &str) -> Option<&StructModel> {
self.entries
.iter()
.find(|e| e.module_path == module_path && e.name == name)
.map(|e| &e.model)
}
pub fn foreign_methods(&self, module_path: &[String]) -> Vec<ForeignMethod<'_>> {
let mut out = Vec::new();
for entry in &self.entries {
if entry.model.is_generic() {
continue;
}
for method in &entry.model.methods {
let Some(site) = &method.site else { continue };
if site.module_path != module_path || site.module_path == entry.module_path {
continue;
}
out.push(ForeignMethod {
struct_name: &entry.model.item.ident,
struct_module_path: &entry.module_path,
self_ty: &site.self_ty,
method,
});
}
}
out
}
}
#[derive(Debug)]
pub struct ForeignMethod<'a> {
pub struct_name: &'a syn::Ident,
pub struct_module_path: &'a [String],
pub self_ty: &'a Type,
pub method: &'a MethodModel,
}