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::{
const_param_names, generic_field_has_accessors, generics_to_type_params, has_impl_trait,
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 file = syn::File {
shebang: None,
attrs,
items,
};
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 tree = ModelTree::collect(&file.items, Mode::Inline);
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 {
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 consts = const_param_names(&f.sig.generics);
let impl_trait = has_impl_trait(&f.sig);
if !consts.is_empty() || impl_trait {
let name = f.sig.ident.to_string();
let msg = if impl_trait {
format!("#[julia] function `{name}` uses `impl Trait` in its signature; `impl Trait` is not supported by RustCall")
} else {
format!(
"#[julia] function `{name}` has const generic parameter(s) {}; const generics are not supported by RustCall",
consts.join(", ")
)
};
out.push(syn::parse_quote! { compile_error!(#msg); });
f.vis = Visibility::Public(Default::default());
push_fn(
manifest,
function_entry(&f, attribute, false, module_path, enclosing_cfg),
);
out.push(Item::Fn(f));
} else if has_type_params(&f.sig.generics) {
if let Some(error) = crate::codegen::unsafe_function_error(&f) {
out.extend(items_of(error)?);
}
f.vis = Visibility::Public(Default::default());
push_fn(
manifest,
function_entry(&f, attribute, false, module_path, enclosing_cfg),
);
out.push(Item::Fn(f));
} else {
push_fn(
manifest,
function_entry(&f, attribute, true, module_path, enclosing_cfg),
);
out.extend(items_of(transform_function(
f,
module_path,
PanicHook::FileOwned,
))?);
}
}
_ => {
push_fn(
manifest,
function_entry(f, Attribute::None, false, 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()));
if model.is_generic() {
let entry = generic_struct_entry(model, &s, module_path, enclosing_cfg);
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 entry = concrete_struct_entry(model, &meta, module_path, enclosing_cfg);
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 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;
model
.methods
.iter()
.filter(|m| !crate::codegen::inline_method_is_generic(m))
.map(|m| {
let shape = crate::extract::method_return_shape(struct_name, &m.func, symbols);
let returns_self = matches!(
&m.func.sig.output,
syn::ReturnType::Type(_, ty) if crate::types::is_self_type(ty, struct_name)
);
Method {
name: m.name(),
symbol: if symbols {
crate::codegen::method_symbol_of(stem, &m.name())
} 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.name()),
},
is_static: m.is_static,
is_mutable: m.is_mutable,
is_constructor: m.name() == "new" || returns_self,
is_classmethod: false,
vis: crate::attrs::visibility_string(&m.func.vis),
skip_reason: crate::codegen::method_skip_reason(m),
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: crate::codegen::returns_boxed_struct(struct_name, &m.func),
args: fn_args(&m.func.sig),
return_type: return_type_to_string(&m.func.sig.output),
return_abi: crate::codegen::return_abi(&m.func.sig).to_string(),
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,
)),
}
})
.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,
}
})
.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(),
}
}