use syn::spanned::Spanned;
use syn::{FnArg, 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 is_static: bool,
pub is_mutable: bool,
pub attribute: Attribute,
pub enclosing_cfg: Vec<syn::Attribute>,
pub site: Option<ImplSite>,
pub host: Option<ImplHost>,
}
impl MethodModel {
pub fn from_fn(func: &ImplItemFn, attribute: Attribute) -> Self {
let receiver = func.sig.inputs.iter().find_map(|a| match a {
FnArg::Receiver(r) => Some(r),
_ => None,
});
MethodModel {
func: func.clone(),
is_static: receiver.is_none(),
is_mutable: receiver.map(|r| r.mutability.is_some()).unwrap_or(false),
attribute,
enclosing_cfg: Vec::new(),
site: None,
host: None,
}
}
pub fn name(&self) -> String {
self.func.sig.ident.to_string()
}
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.impls.push(imp.clone());
for mut m in wrapped_methods(imp, mode, enclosing_cfg) {
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.name() == m.name()) {
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 {
entries: Vec<LocatedModel>,
}
#[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>,
}
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 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);
for block in &impls {
if let Ok(index) = crate::paths::locate(&tree.entries, &block.header, &imports) {
tree.entries[index].model.attach_impl(
&block.item,
mode,
&block.enclosing_cfg,
Some(&block.header.module_path),
);
}
}
tree
}
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>,
) {
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,
}