use syn::{Item, Visibility};
use crate::attrs::{rustcall_attribute, strip_julia_struct_derive, strip_rustcall_attrs};
use crate::cfg::{predicate_string, CfgSet};
use crate::codegen::{
inline_generic_method_refusals, inline_generic_wrappers, inline_struct_wrappers,
panic_hook_items, transform_function, PanicHook,
};
use crate::extract::{fn_args, function_entry};
use crate::manifest::{Attribute, Field, Manifest, Method, Mode, Struct};
use crate::model::{ModelTree, StructModel};
use crate::types::{
generic_field_has_accessors, generics_to_type_params, has_type_params, return_type_to_string,
type_to_string,
};
pub struct Expanded {
pub source: String,
pub manifest: Manifest,
}
fn items_of(tokens: proc_macro2::TokenStream) -> Result<Vec<Item>, syn::Error> {
let file: syn::File = syn::parse2(tokens)?;
Ok(file.items)
}
fn unparse_items(items: Vec<Item>) -> String {
unparse_file(Vec::new(), items)
}
fn unparse_file(attrs: Vec<syn::Attribute>, items: Vec<Item>) -> String {
let mut file = syn::File {
shebang: None,
attrs,
items,
};
crate::owned_returns::strip_file(&mut file);
prettyplease::unparse(&file)
}
pub fn expand(source: &str) -> Result<Expanded, syn::Error> {
expand_with_cfg(source, None)
}
pub fn expand_with_cfg(source: &str, cfg: Option<&CfgSet>) -> Result<Expanded, syn::Error> {
let mut file = syn::parse_file(source)?;
if let Some(set) = cfg {
crate::cfg::prune_file_or_error(set, &mut file)?;
}
let mut manifest = Manifest::new(Mode::Inline);
let mut tree = ModelTree::collect(&file.items, Mode::Inline);
tree.record_file_attrs(&file.attrs);
let mut out = expand_items(&file.items, &mut manifest, &[], &[], &tree)?;
for (claim, first, second) in manifest.duplicate_claims() {
let symbol = &claim.name;
let msg = if claim.exported {
format!(
"RustCall would export the symbol `{symbol}` twice in this block: for {first} \
and for {second}. The scheme derives every symbol from the item's name and \
module path (`rustcall_<fn>`, `rustcall_<Struct>_<method>`, `<Struct>_free`, \
`<Struct>_get_<field>`, `<owner>_free_rust_string`, ... — #300), so two items \
whose names differ only where the scheme joins them meet here. Rename one of \
them."
)
} else {
format!(
"RustCall would define the item `{symbol}` twice in this block: for {first} \
and for {second}. It is not exported and not one you wrote — it is {}. Two of \
them in one module are a duplicate definition rustc would report inside \
generated code. Rename one of the items (#338).",
crate::claims::internal_origin(&claim)
)
};
out.insert(0, syn::parse_quote! { compile_error!(#msg); });
}
out.extend(items_of(panic_hook_items())?);
Ok(Expanded {
source: unparse_file(file.attrs.clone(), out),
manifest,
})
}
fn expand_items(
items: &[Item],
manifest: &mut Manifest,
module_path: &[String],
enclosing_cfg: &[syn::Attribute],
tree: &ModelTree,
) -> Result<Vec<Item>, syn::Error> {
let mut out: Vec<Item> = Vec::new();
let push_fn = |manifest: &mut Manifest, entry: crate::manifest::Function| {
manifest.functions.push(entry);
};
for item in items {
if let Some(refusal) = crate::refusal::julia_item_refusal(item) {
return Err(syn::Error::new(
refusal.span,
format!("{} ({})", refusal.message, refusal.detail),
));
}
match item {
Item::Fn(f) => {
let attribute = rustcall_attribute(&f.attrs);
match attribute {
Attribute::Julia => {
let mut f = f.clone();
strip_rustcall_attrs(&mut f.attrs);
let mut entry =
function_entry(&f, attribute, Mode::Inline, module_path, enclosing_cfg);
if !has_type_params(&f.sig.generics) {
crate::extract::mark_checked_handle_args(
&mut entry.args,
&f.sig,
|ty| tree.checked_borrowed_handle(ty, module_path),
);
}
crate::owned_returns::mark(
&f.attrs,
&f.sig,
&mut entry.return_handle,
&mut entry.skip_reason,
|ty| tree.checked_borrowed_handle(ty, module_path).ok().flatten(),
);
if !entry.skip_reason.is_empty() {
entry.exported = false;
}
push_fn(manifest, entry);
let refusal =
crate::refusal::function_refusal(&f, module_path, Mode::Inline);
if refusal.is_none() && !has_type_params(&f.sig.generics) {
out.extend(items_of(transform_function(
f,
module_path,
PanicHook::FileOwned,
))?);
} else {
if let Some(refusal) = refusal {
out.extend(items_of(
refusal.compile_error(&crate::cfg::cfg_attrs(&f.attrs)),
)?);
}
f.vis = Visibility::Public(Default::default());
out.push(Item::Fn(f));
}
}
_ => {
push_fn(
manifest,
function_entry(
f,
Attribute::None,
Mode::Inline,
module_path,
enclosing_cfg,
),
);
out.push(item.clone());
}
}
}
Item::Struct(s) => {
let Some(model) = tree.find(module_path, &s.ident.to_string()) else {
out.push(item.clone());
continue;
};
let mut s = s.clone();
strip_rustcall_attrs(&mut s.attrs);
strip_julia_struct_derive(&mut s.attrs);
s.vis = Visibility::Public(Default::default());
out.push(Item::Struct(s.clone()));
out.extend(items_of(crate::codegen::owned_marker_impl(
&s,
PanicHook::FileOwned,
))?);
if model.is_generic() {
let mut entry = generic_struct_entry(model, &s, module_path, enclosing_cfg);
mark_method_handles(&mut entry, model, module_path, tree);
for w in &entry.generic_wrappers {
let f: syn::File = syn::parse_str(&w.source)?;
out.extend(f.items);
}
out.extend(items_of(inline_generic_method_refusals(model))?);
manifest.structs.push(entry);
} else {
let (tokens, meta) = inline_struct_wrappers(model, module_path);
out.extend(items_of(tokens)?);
let mut entry = concrete_struct_entry(model, &meta, module_path, enclosing_cfg);
mark_method_handles(&mut entry, model, module_path, tree);
manifest.structs.push(entry);
}
}
Item::Impl(imp) => {
let mut imp = imp.clone();
strip_rustcall_attrs(&mut imp.attrs);
for ii in &mut imp.items {
if let syn::ImplItem::Fn(func) = ii {
strip_rustcall_attrs(&mut func.attrs);
}
}
out.push(Item::Impl(imp));
}
Item::Mod(m) => match &m.content {
Some((brace, inner)) => {
let mut m = m.clone();
strip_rustcall_attrs(&mut m.attrs);
let mut path = module_path.to_vec();
path.push(m.ident.to_string());
let cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &m.attrs);
m.content = Some((*brace, expand_items(inner, manifest, &path, &cfg, tree)?));
out.push(Item::Mod(m));
}
None => out.push(item.clone()),
},
other => out.push(other.clone()),
}
}
for foreign in tree.foreign_methods(module_path) {
out.extend(items_of(crate::codegen::inline_foreign_method_wrapper(
foreign.self_ty,
foreign.struct_name,
foreign.struct_module_path,
foreign.method,
))?);
}
for name in symbol_collisions(items, &out) {
let msg = format!(
"RustCall generates an item named `{name}` in this module, but the block already \
defines one. `#[julia]` keeps the annotated item and emits its `extern \"C\"` entry \
point next to it (`rustcall_<fn>`, `rustcall_<Struct>_<method>`, `<Struct>_free`, \
`<Struct>_get_<field>`, `CResult_<fn>`, `<fn>_RustCallOwnedString`, ... — with the \
module path folded into `<fn>` / `<Struct>` inside a module, #300), so rename \
the conflicting item (#279)."
);
out.insert(0, syn::parse_quote! { compile_error!(#msg); });
}
Ok(out)
}
fn mark_method_handles(
entry: &mut crate::manifest::Struct,
model: &StructModel,
module_path: &[String],
tree: &ModelTree,
) {
for method in entry.methods.iter_mut() {
let Some(m) = model
.methods
.iter()
.find(|m| m.name() == method.name && m.trait_path() == method.trait_path)
else {
continue;
};
let site = m
.site
.as_ref()
.map(|site| site.module_path.clone())
.unwrap_or_else(|| module_path.to_vec());
let checked = |ty: &syn::Type| {
if m.host
.as_ref()
.is_some_and(|h| crate::extract::type_parameter_path(ty, &h.generics))
{
Ok(None)
} else if let Some(reason) = tree.borrow_context_error(&site) {
Err(reason)
} else if crate::extract::is_self_type(ty) {
match tree.borrow_context_error(module_path) {
Some(reason) => Err(reason),
None => Ok(Some(entry_ffi_name(module_path, model))),
}
} else if m
.host
.as_ref()
.is_some_and(|h| crate::receiver::same_spelling(ty, &h.self_ty))
{
match tree.borrow_context_error(module_path) {
Some(reason) => Err(reason),
None => Ok(Some(entry_ffi_name(module_path, model))),
}
} else {
tree.checked_borrowed_handle(ty, &site)
}
};
crate::owned_returns::mark(
&m.func.attrs,
&m.func.sig,
&mut method.return_handle,
&mut method.skip_reason,
|ty| checked(ty).ok().flatten(),
);
crate::extract::mark_checked_handle_args(&mut method.args, &m.func.sig, checked);
}
}
fn entry_ffi_name(module_path: &[String], model: &StructModel) -> String {
crate::codegen::symbol_stem(module_path, &model.name())
}
fn item_key(item: &Item) -> Option<(u8, String)> {
const TYPE_NS: u8 = 0;
const VALUE_NS: u8 = 1;
match item {
Item::Fn(f) => Some((VALUE_NS, f.sig.ident.to_string())),
Item::Const(c) => Some((VALUE_NS, c.ident.to_string())),
Item::Static(s) => Some((VALUE_NS, s.ident.to_string())),
Item::Struct(s) => Some((TYPE_NS, s.ident.to_string())),
Item::Enum(e) => Some((TYPE_NS, e.ident.to_string())),
Item::Union(u) => Some((TYPE_NS, u.ident.to_string())),
Item::Trait(t) => Some((TYPE_NS, t.ident.to_string())),
Item::Type(t) => Some((TYPE_NS, t.ident.to_string())),
Item::Mod(m) => Some((TYPE_NS, m.ident.to_string())),
_ => None,
}
}
fn key_counts(items: &[Item]) -> std::collections::HashMap<(u8, String), usize> {
let mut counts = std::collections::HashMap::new();
for item in items {
if let Some(key) = item_key(item) {
*counts.entry(key).or_insert(0) += 1;
}
}
counts
}
fn symbol_collisions(original: &[Item], expanded: &[Item]) -> Vec<String> {
let before = key_counts(original);
let after = key_counts(expanded);
let mut clashes: Vec<String> = after
.iter()
.filter(|(key, count)| **count > before.get(*key).copied().unwrap_or(0))
.filter(|(key, _)| before.contains_key(*key))
.map(|((_, name), _)| name.clone())
.collect();
clashes.sort();
clashes
}
fn methods_of(
model: &StructModel,
symbols: bool,
stem: &str,
module_path: &[String],
) -> Vec<Method> {
let struct_name = &model.item.ident;
let bare: syn::Type = syn::parse_quote!(#struct_name);
model
.methods
.iter()
.map(|m| {
let site = if !symbols {
crate::refusal::MethodSite::InlineGeneric { struct_name }
} else {
crate::refusal::MethodSite::Inline {
self_ty: match &m.site {
Some(site) if !m.is_local_to(module_path) => &site.self_ty,
_ => &bare,
},
struct_name,
}
};
let refusal = crate::refusal::method_refusal(site, m);
let shape = crate::extract::method_return_shape(struct_name, m, symbols);
Method {
name: m.name(),
trait_path: m.trait_path(),
julia_name: String::new(),
symbol: if symbols {
crate::codegen::method_symbol_of(stem, &m.method_stem())
} else {
String::new()
},
string_owner: match (symbols, m.is_local_to(module_path)) {
(false, _) => String::new(),
(true, true) => stem.to_string(),
(true, false) => crate::codegen::method_string_owner(stem, &m.method_stem()),
},
is_static: m.is_static(),
is_mutable: m.is_mutable(),
is_constructor: m.is_constructor(struct_name)
&& (symbols || m.fallible_constructor(struct_name).is_none()),
is_classmethod: false,
vis: crate::attrs::visibility_string(&m.func.vis),
skip_reason: refusal.map(|r| r.skip_reason()).unwrap_or_default(),
python_name: String::new(),
accessor: String::new(),
attribute: m.attribute,
return_kind: shape.kind,
ok_type: shape.ok_type,
err_type: shape.err_type,
inner_type: shape.inner_type,
ok_abi: shape.ok_abi,
err_abi: shape.err_abi,
inner_abi: shape.inner_abi,
returns_boxed_struct: m.returns_boxed_struct(struct_name),
args: fn_args(&m.func.sig),
return_type: return_type_to_string(&m.func.sig.output),
return_abi: if crate::owned_returns::annotation(&m.func.attrs)
.ok()
.flatten()
.is_some()
&& !matches!(shape.kind, crate::manifest::ReturnKind::Result)
{
"boxed".into()
} else {
crate::codegen::return_abi(&m.func.sig).to_string()
},
return_handle: String::new(),
generic_wrapper: String::new(),
generic_wrapper_name: String::new(),
cfg: crate::cfg::predicate_string(&crate::cfg::effective_cfg_attrs(
&m.enclosing_cfg,
&m.func.attrs,
)),
py_return: None,
}
})
.collect()
}
fn fields_of(model: &StructModel, accessors: &[(String, String, String)]) -> Vec<Field> {
model
.named_fields()
.iter()
.map(|(name, ty)| {
let acc = accessors.iter().find(|(f, _, _)| *name == *f);
Field {
name: name.to_string(),
rust_type: type_to_string(ty),
abi: crate::codegen::field_abi(ty).to_string(),
vec_element: String::new(),
free_symbol: String::new(),
ffi_compatible: acc.is_some(),
getter: acc.map(|a| a.1.clone()).unwrap_or_default(),
setter: acc.map(|a| a.2.clone()).unwrap_or_default(),
python_name: String::new(),
vis: String::new(),
cfg: String::new(),
pyo3_get: false,
pyo3_set: false,
precollision: None,
py_shape: None,
}
})
.collect()
}
fn concrete_struct_entry(
model: &StructModel,
meta: &crate::codegen::InlineStructMeta,
module_path: &[String],
enclosing_cfg: &[syn::Attribute],
) -> Struct {
let stem = crate::codegen::symbol_stem(module_path, &model.name());
let effective_cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &model.item.attrs);
Struct {
callable_path: Vec::new(),
cfg: predicate_string(&effective_cfg),
cfg_features: crate::cfg::predicate_features(&effective_cfg),
name: model.name(),
attribute: model.attribute,
vis: crate::attrs::visibility_string(&model.item.vis),
skip_reason: String::new(),
python_name: String::new(),
python_path: Vec::new(),
pyo3_extends: String::new(),
pyo3_options: Vec::new(),
python_owned_handle: false,
type_params: Vec::new(),
fields: fields_of(model, &meta.accessors),
methods: methods_of(model, true, &stem, module_path),
ffi_name: stem,
derives: model.derives.clone(),
has_clone: meta.has_clone,
has_owned_string_helper: meta.has_owned_string_helper,
has_borrowed_string_helper: meta.has_borrowed_string_helper,
context_source: String::new(),
generic_wrappers: Vec::new(),
line: model.line,
module_path: module_path.to_vec(),
}
}
fn generic_struct_entry(
model: &StructModel,
stripped_struct: &syn::ItemStruct,
module_path: &[String],
enclosing_cfg: &[syn::Attribute],
) -> Struct {
let effective_cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &model.item.attrs);
let stem = crate::codegen::symbol_stem(module_path, &model.name());
let wrappers = inline_generic_wrappers(model, module_path);
let wrapper_names: Vec<&str> = wrappers.iter().map(|w| w.name.as_str()).collect();
let type_params = model.type_param_names();
let accessors: Vec<(String, String, String)> = model
.named_fields()
.iter()
.filter(|(_, ty)| generic_field_has_accessors(ty, &type_params))
.map(|(n, _)| {
let getter = crate::codegen::field_getter_symbol(&stem, &n.to_string());
let setter = crate::codegen::field_setter_symbol(&stem, &n.to_string());
let has_setter = wrapper_names.contains(&setter.as_str());
(
n.to_string(),
getter,
if has_setter { setter } else { String::new() },
)
})
.collect();
let mut context_items: Vec<Item> = vec![Item::Struct(stripped_struct.clone())];
for imp in &model.impls {
let mut imp = imp.clone();
strip_rustcall_attrs(&mut imp.attrs);
for ii in &mut imp.items {
if let syn::ImplItem::Fn(func) = ii {
strip_rustcall_attrs(&mut func.attrs);
}
}
context_items.push(Item::Impl(imp));
}
let mut methods = methods_of(model, false, &stem, module_path);
for m in &mut methods {
let wrapper_name = crate::codegen::generic_method_wrapper_name(&stem, &m.name);
if let Some(w) = wrappers.iter().find(|w| w.name == wrapper_name) {
m.generic_wrapper = w.source.clone();
m.generic_wrapper_name = wrapper_name;
}
}
Struct {
callable_path: Vec::new(),
cfg: predicate_string(&effective_cfg),
cfg_features: crate::cfg::predicate_features(&effective_cfg),
name: model.name(),
ffi_name: stem,
attribute: model.attribute,
vis: crate::attrs::visibility_string(&model.item.vis),
skip_reason: String::new(),
python_name: String::new(),
python_path: Vec::new(),
pyo3_extends: String::new(),
pyo3_options: Vec::new(),
python_owned_handle: false,
type_params: generics_to_type_params(&model.item.generics),
fields: fields_of(model, &accessors),
methods,
derives: model.derives.clone(),
has_clone: false,
has_owned_string_helper: false,
has_borrowed_string_helper: false,
context_source: unparse_items(context_items),
generic_wrappers: wrappers,
line: model.line,
module_path: module_path.to_vec(),
}
}