use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::{
Attribute, File, FnArg, Ident, Item, ItemFn, ItemImpl, ItemMod, ItemStruct, Pat, ReturnType,
Type, Visibility,
};
use crate::cfg::cfg_attrs;
use crate::manifest::{GenericWrapper, Mode};
use crate::model::{ImplHost, MethodModel, StructModel};
use crate::receiver::Receiver;
use crate::refusal::Refusal;
use crate::types::{
extract_option_type, extract_result_type, field_has_accessors, generic_field_has_accessors,
is_self_type, is_str_ref_type, is_string_type, is_vec_type, last_ident, unparen,
};
pub const SYMBOL_PREFIX: &str = "rustcall_";
pub const MODULE_SEPARATOR: &str = "__";
pub const ESCAPED_UNDERSCORE: &str = "_0";
pub fn unraw(name: &str) -> &str {
name.strip_prefix("r#").unwrap_or(name)
}
pub fn source_ident(name: &str, span: proc_macro2::Span) -> Ident {
match name.strip_prefix("r#") {
Some(bare) => Ident::new_raw(bare, span),
None => Ident::new(name, span),
}
}
pub fn symbol_stem(module_path: &[String], name: &str) -> String {
let name = unraw(name);
if module_path.is_empty() {
return name.to_string();
}
module_path
.iter()
.map(|segment| segment.as_str())
.chain(std::iter::once(name))
.map(|segment| unraw(segment).replace('_', ESCAPED_UNDERSCORE))
.collect::<Vec<_>>()
.join(MODULE_SEPARATOR)
}
pub fn function_symbol(module_path: &[String], name: &str) -> String {
format!("{SYMBOL_PREFIX}{}", symbol_stem(module_path, name))
}
pub fn method_symbol(module_path: &[String], struct_name: &str, method: &str) -> String {
method_symbol_of(
&symbol_stem(module_path, struct_name),
&method_stem(None, method),
)
}
pub fn method_stem(trait_name: Option<&str>, method: &str) -> String {
let method = unraw(method);
match trait_name.map(unraw) {
None => method.to_string(),
Some(trait_name) => format!("{}{trait_name}_{method}", trait_name.len()),
}
}
pub fn trait_name_of(trait_path: &syn::Path) -> Option<String> {
use syn::ext::IdentExt;
trait_path
.segments
.last()
.map(|s| s.ident.unraw().to_string())
}
pub fn method_symbol_of(struct_stem: &str, method: &str) -> String {
format!("{SYMBOL_PREFIX}{}_{}", unraw(struct_stem), unraw(method))
}
pub fn struct_free_symbol(struct_stem: &str) -> String {
format!("{}_free", unraw(struct_stem))
}
pub fn method_string_owner(struct_stem: &str, method: &str) -> String {
format!("{}_{}", unraw(struct_stem), unraw(method))
}
pub fn field_getter_symbol(struct_stem: &str, field: &str) -> String {
format!("{}_get_{}", unraw(struct_stem), unraw(field))
}
pub fn field_setter_symbol(struct_stem: &str, field: &str) -> String {
format!("{}_set_{}", unraw(struct_stem), unraw(field))
}
pub fn function_returns_string(sig: &syn::Signature) -> bool {
matches!(&sig.output, ReturnType::Type(_, ty) if is_string_type(ty))
}
pub fn function_returns_str_ref(sig: &syn::Signature) -> bool {
matches!(&sig.output, ReturnType::Type(_, ty) if is_str_ref_type(ty))
}
pub fn has_string_args(sig: &syn::Signature) -> bool {
sig.inputs.iter().any(|a| match a {
FnArg::Typed(pt) => is_string_type(&pt.ty) || is_str_ref_type(&pt.ty),
FnArg::Receiver(_) => false,
})
}
pub fn returns_borrowed_str(sig: &syn::Signature) -> bool {
function_returns_str_ref(sig) && !has_string_args(sig)
}
pub fn returns_copied_str(sig: &syn::Signature) -> bool {
function_returns_str_ref(sig) && has_string_args(sig)
}
pub fn return_abi(sig: &syn::Signature) -> &'static str {
if function_returns_string(sig) || returns_copied_str(sig) {
"string"
} else if returns_borrowed_str(sig) {
"str"
} else {
""
}
}
pub fn field_abi(ty: &Type) -> &'static str {
if is_string_type(ty) {
"string"
} else {
""
}
}
fn fresh_ident(base: &str, taken: &[String]) -> Ident {
let mut name = base.to_string();
while taken.iter().any(|t| t == &name) {
name.push('_');
}
format_ident!("{}", name)
}
fn typed_arg_names(sig: &syn::Signature) -> Vec<Ident> {
sig.inputs
.iter()
.enumerate()
.filter_map(|(i, arg)| match arg {
FnArg::Typed(pat_type) => Some(match pat_type.pat.as_ref() {
Pat::Ident(pi) => pi.ident.clone(),
_ => format_ident!("arg{}", i),
}),
FnArg::Receiver(_) => None,
})
.collect()
}
fn arg_pairs(sig: &syn::Signature) -> Vec<(Ident, Type)> {
sig.inputs
.iter()
.filter_map(|a| match a {
FnArg::Typed(pt) => Some((*pt.ty).clone()),
FnArg::Receiver(_) => None,
})
.zip(typed_arg_names(sig))
.map(|(ty, name)| (name, ty))
.collect()
}
fn string_arg_conversion(
name: &Ident,
ty: &Type,
taken: &[String],
) -> (Vec<TokenStream2>, Option<TokenStream2>) {
if is_string_type(ty) {
let p = fresh_ident(&format!("{name}_ptr"), taken);
let l = fresh_ident(&format!("{name}_len"), taken);
(
vec![quote! { #p: *const u8 }, quote! { #l: usize }],
Some(quote! {
let #name = unsafe {
let slice = std::slice::from_raw_parts(#p, #l);
String::from_utf8_lossy(slice).into_owned()
};
}),
)
} else if is_str_ref_type(ty) {
let p = fresh_ident(&format!("{name}_ptr"), taken);
let l = fresh_ident(&format!("{name}_len"), taken);
let b = fresh_ident(&format!("{name}_bytes"), taken);
let c = fresh_ident(&format!("{name}_cow"), taken);
(
vec![quote! { #p: *const u8 }, quote! { #l: usize }],
Some(quote! {
let #b = unsafe { std::slice::from_raw_parts(#p, #l) };
let #c = String::from_utf8_lossy(#b);
let #name: &str = &#c;
}),
)
} else {
(vec![quote! { #name: #ty }], None)
}
}
pub(crate) struct WrapperReceiver {
pub ty: syn::Path,
pub shape: Receiver,
pub borrow: crate::environment::SelfBorrow,
}
pub(crate) enum CallTarget {
Free(syn::Path),
Method { ty: syn::Path, path: syn::TypePath },
}
fn path_tail(path: &syn::Path) -> String {
path.segments
.last()
.map(|s| s.ident.to_string())
.unwrap_or_default()
}
#[allow(clippy::large_enum_variant)]
pub(crate) enum WrapperReturn {
Unit,
Plain(Type),
Boxed(syn::Path),
OwnedString {
helper: Ident,
free: Ident,
declare: bool,
},
BorrowedStr { helper: Ident, declare: bool },
CResult {
name: Ident,
ok: WrapperPayload,
err: WrapperPayload,
},
COption { name: Ident, inner: WrapperPayload },
}
#[allow(clippy::large_enum_variant)]
pub(crate) enum WrapperPayload {
Plain(Type),
Boxed(syn::Path),
BoxedVerified(syn::Path),
OwnedString {
helper: Ident,
free: Ident,
declare: bool,
},
}
impl WrapperReturn {
fn passed_types(&self) -> Vec<TokenStream2> {
let payload = |p: &WrapperPayload| match p {
WrapperPayload::Plain(ty) => Some(quote! { #ty }),
WrapperPayload::Boxed(path) | WrapperPayload::BoxedVerified(path) => {
Some(quote! { #path })
}
WrapperPayload::OwnedString { .. } => None,
};
match self {
WrapperReturn::Plain(ty) => vec![quote! { #ty }],
WrapperReturn::Boxed(path) => vec![quote! { #path }],
WrapperReturn::CResult { ok, err, .. } => {
[ok, err].into_iter().filter_map(payload).collect()
}
WrapperReturn::COption { inner, .. } => payload(inner).into_iter().collect(),
WrapperReturn::Unit
| WrapperReturn::OwnedString { .. }
| WrapperReturn::BorrowedStr { .. } => Vec::new(),
}
}
fn types_mut(&mut self) -> Vec<&mut Type> {
fn payload(p: &mut WrapperPayload) -> Option<&mut Type> {
match p {
WrapperPayload::Plain(ty) => Some(ty),
_ => None,
}
}
match self {
WrapperReturn::Plain(ty) => vec![ty],
WrapperReturn::CResult { ok, err, .. } => {
[ok, err].into_iter().filter_map(payload).collect()
}
WrapperReturn::COption { inner, .. } => payload(inner).into_iter().collect(),
_ => Vec::new(),
}
}
}
impl WrapperPayload {
fn is_plain(&self) -> bool {
matches!(self, WrapperPayload::Plain(_))
}
fn stored_type(&self) -> Type {
match self {
WrapperPayload::Plain(ty) => ty.clone(),
WrapperPayload::Boxed(ty) | WrapperPayload::BoxedVerified(ty) => {
syn::parse_quote!(*mut #ty)
}
WrapperPayload::OwnedString { helper, .. } => syn::parse_quote!(#helper),
}
}
fn store_expr(&self, value: &Ident) -> TokenStream2 {
match self {
WrapperPayload::Plain(_) => quote! { #value },
WrapperPayload::Boxed(_) | WrapperPayload::BoxedVerified(_) => {
quote! { Box::into_raw(Box::new(#value)) }
}
WrapperPayload::OwnedString { helper, .. } => quote! {{
let mut rustcall_bytes = ToString::to_string(&#value).into_bytes();
let rustcall_buf = #helper {
ptr: rustcall_bytes.as_mut_ptr(),
len: rustcall_bytes.len(),
cap: rustcall_bytes.capacity(),
};
::std::mem::forget(rustcall_bytes);
rustcall_buf
}},
}
}
fn declaration(&self) -> Option<(&Ident, &Ident)> {
match self {
WrapperPayload::OwnedString {
helper,
free,
declare: true,
} => Some((helper, free)),
_ => None,
}
}
}
pub(crate) struct WrapperSpec {
pub symbol: Ident,
pub cfg_attrs: Vec<Attribute>,
pub receiver: Option<WrapperReceiver>,
pub args: Vec<(Ident, Type)>,
pub generics: syn::Generics,
pub host: Option<ImplHost>,
pub ret: WrapperReturn,
pub target: CallTarget,
pub panic_hook: PanicHook,
pub call_suffix: TokenStream2,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum PanicHook {
FileOwned,
Runtime,
External,
}
pub const PANIC_SYMBOL_SUFFIX: &str = "_take_panic";
pub const RUNTIME_CRATE: &str = "rustcall_julia_macros";
pub const INSTALL_PANIC_HOOK_SYMBOL: &str = "__rustcall_install_panic_hook";
pub const UNINSTALL_PANIC_HOOK_SYMBOL: &str = "__rustcall_uninstall_panic_hook";
pub fn panic_symbol(symbol: &str) -> String {
format!("{}{PANIC_SYMBOL_SUFFIX}", unraw(symbol))
}
fn panic_channel(cfg_attrs: &[Attribute], slot: &Ident, reader: &Ident) -> TokenStream2 {
quote! {
#(#cfg_attrs)*
thread_local! {
static #slot: ::std::cell::RefCell<::std::option::Option<::std::string::String>> =
::std::cell::RefCell::new(::std::option::Option::None);
}
#(#cfg_attrs)*
#[no_mangle]
pub extern "C" fn #reader(out: *mut u8, cap: usize) -> usize {
#slot.with(|rustcall_slot| {
let mut rustcall_slot = rustcall_slot.borrow_mut();
if out.is_null() && cap == usize::MAX {
return rustcall_slot.take().map_or(0, |message| message.len());
}
let rustcall_len = match rustcall_slot.as_ref() {
::std::option::Option::Some(message) => {
let bytes = message.as_bytes();
if bytes.len() <= cap && !out.is_null() {
unsafe {
::std::ptr::copy_nonoverlapping(bytes.as_ptr(), out, bytes.len());
}
Some(bytes.len())
} else {
return bytes.len();
}
}
::std::option::Option::None => ::std::option::Option::None,
};
match rustcall_len {
::std::option::Option::Some(n) => {
*rustcall_slot = ::std::option::Option::None;
n
}
::std::option::Option::None => 0,
}
})
}
}
}
pub fn panic_hook_items_present(items: &[Item]) -> bool {
items.iter().any(|item| match item {
Item::Struct(s) => s.ident == "__RustCallBoundary",
Item::Fn(f) => f.sig.ident == INSTALL_PANIC_HOOK_SYMBOL,
_ => false,
})
}
pub fn panic_hook_items() -> TokenStream2 {
let install = format_ident!("{}", INSTALL_PANIC_HOOK_SYMBOL);
let uninstall = format_ident!("{}", UNINSTALL_PANIC_HOOK_SYMBOL);
quote! {
thread_local! {
static __RUSTCALL_QUIET_DEPTH: ::std::cell::Cell<usize> =
const { ::std::cell::Cell::new(0) };
}
static __RUSTCALL_QUIET_HOOK_LIVE: ::std::sync::Mutex<bool> =
::std::sync::Mutex::new(false);
pub struct __RustCallBoundary;
impl __RustCallBoundary {
pub fn enter() -> Self {
let _ = __RUSTCALL_QUIET_DEPTH.try_with(|depth| depth.set(depth.get() + 1));
Self
}
}
impl ::std::ops::Drop for __RustCallBoundary {
fn drop(&mut self) {
let _ = __RUSTCALL_QUIET_DEPTH
.try_with(|depth| depth.set(depth.get().saturating_sub(1)));
}
}
#[no_mangle]
pub extern "C" fn #install() {
if let ::std::result::Result::Ok(mut rustcall_live) =
__RUSTCALL_QUIET_HOOK_LIVE.lock()
{
if !*rustcall_live {
let rustcall_previous = ::std::panic::take_hook();
::std::panic::set_hook(::std::boxed::Box::new(move |rustcall_info| {
if __RUSTCALL_QUIET_DEPTH.try_with(|depth| depth.get()).unwrap_or(0) == 0 {
rustcall_previous(rustcall_info);
}
}));
*rustcall_live = true;
}
}
}
#[no_mangle]
pub extern "C" fn #uninstall() {
if let ::std::result::Result::Ok(mut rustcall_live) =
__RUSTCALL_QUIET_HOOK_LIVE.lock()
{
if *rustcall_live {
let _ = ::std::panic::take_hook();
*rustcall_live = false;
}
}
}
}
}
pub fn runtime_module_source() -> String {
let file: File =
syn::parse2(panic_hook_items()).expect("the quiet-hook items are not a valid Rust file");
format!(
"// GENERATED by `rustcall_julia_core::codegen::runtime_module_source`. DO NOT EDIT.\n\
// Regenerate with `UPDATE_GOLDEN=1 cargo test` in `deps/rustcall_julia_core`,\n\
// then `cargo fmt` here;\n\
// `tests/runtime_crate.rs` fails if this file and the generator disagree.\n\
//\n\
// These are the same items `panic_hook_items()` puts at the root of a file\n\
// RustCall writes whole (#304). Here they are compiled once, into the crate\n\
// every `#[julia]` crate already depends on, so a `#[julia]` wrapper can take\n\
// the boundary guard by path and the `cdylib` still exports\n\
// `__rustcall_install_panic_hook` for Julia to call.\n\
\n{}",
prettyplease::unparse(&file)
)
}
fn guarded_body(
julia_name: &str,
slot: &Ident,
prologue: &TokenStream2,
body: TokenStream2,
sentinel: TokenStream2,
returns_unit: bool,
hook: PanicHook,
) -> TokenStream2 {
let ok_arm = if returns_unit {
quote! { ::std::result::Result::Ok(_) => {} }
} else {
quote! { ::std::result::Result::Ok(rustcall_value) => rustcall_value, }
};
let boundary = match hook {
PanicHook::FileOwned => quote! {
let _rustcall_boundary = crate::__RustCallBoundary::enter();
},
PanicHook::Runtime => {
let krate = format_ident!("{}", RUNTIME_CRATE);
quote! {
let _rustcall_boundary = ::#krate::__RustCallBoundary::enter();
}
}
PanicHook::External => TokenStream2::new(),
};
quote! {
#boundary
match ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| {
#prologue
#body
})) {
#ok_arm
::std::result::Result::Err(rustcall_payload) => {
let rustcall_message: ::std::string::String =
if let ::std::option::Option::Some(s) =
rustcall_payload.downcast_ref::<&'static str>()
{
::std::string::ToString::to_string(s)
} else if let ::std::option::Option::Some(s) =
rustcall_payload.downcast_ref::<::std::string::String>()
{
s.clone()
} else {
::std::string::ToString::to_string("Box<dyn Any>")
};
let rustcall_message = ::std::format!(
"{} panicked: {}", #julia_name, rustcall_message);
#slot.with(|rustcall_slot| {
*rustcall_slot.borrow_mut() =
::std::option::Option::Some(rustcall_message);
});
#sentinel
}
}
}
}
pub(crate) fn generate_wrapper(spec: WrapperSpec) -> TokenStream2 {
let cfgs = spec.cfg_attrs.clone();
match wrapper_tokens(spec) {
Ok(tokens) => tokens,
Err(refusal) => refusal.compile_error(&cfgs),
}
}
fn wrapper_refusal(spec: WrapperSpec) -> Option<Refusal> {
wrapper_tokens(spec).err()
}
fn wrapper_tokens(spec: WrapperSpec) -> Result<TokenStream2, Refusal> {
let WrapperSpec {
symbol,
cfg_attrs,
receiver,
mut args,
generics,
host,
mut ret,
target,
call_suffix,
panic_hook,
} = spec;
let julia_name = match &target {
CallTarget::Free(name) => path_tail(name),
CallTarget::Method { ty, path } => {
format!("{}::{}", path_tail(ty), path_tail(&path.path))
}
};
let mut environment = crate::environment::wrapper_environment(host.as_ref(), &generics);
if let Some(host) = &host {
let mut out_of_scope = crate::environment::expand_self(host, &mut environment);
for (_, ty) in args.iter_mut() {
out_of_scope = out_of_scope.or(crate::environment::expand_self_in_type(host, ty));
}
for ty in ret.types_mut() {
out_of_scope = out_of_scope.or(crate::environment::expand_self_in_type(host, ty));
}
if let Some(span) = out_of_scope {
return Err(crate::environment::out_of_scope_error(
span,
host,
&julia_name,
));
}
}
let spelled_types = {
let arg_types = args.iter().map(|(_, ty)| ty);
let returned = ret.passed_types();
let predicates = &environment.where_clause;
quote! { #environment #predicates #(#arg_types)* #(#returned)* }
};
if let Some((span, in_macro)) = crate::environment::leftover_self(spelled_types) {
return Err(crate::environment::leftover_self_error(
span,
in_macro.as_deref(),
&julia_name,
));
}
let borrow = receiver
.as_ref()
.map(|r| r.borrow.clone())
.unwrap_or(crate::environment::SelfBorrow::None);
match crate::environment::name_elided_return(
&mut environment,
&borrow,
&mut args,
ret.types_mut(),
&julia_name,
) {
crate::environment::ElidedReturn::Named => {}
crate::environment::ElidedReturn::Undecidable => return Ok(TokenStream2::new()),
crate::environment::ElidedReturn::Refused(refusal) => return Err(refusal),
}
if let Some(refusal) = crate::environment::lowered_lifetime_error(
&environment,
&args,
&ret.passed_types(),
&julia_name,
) {
return Err(refusal);
}
let taken: Vec<String> = args.iter().map(|(n, _)| n.to_string()).collect();
let ptr = fresh_ident("ptr", &taken);
let self_obj = fresh_ident("self_obj", &taken);
let mut wrapper_args: Vec<TokenStream2> = Vec::new();
let mut conversions: Vec<TokenStream2> = Vec::new();
let mut call_args: Vec<TokenStream2> = Vec::new();
if let Some(r) = &receiver {
let ty = &r.ty;
wrapper_args.push(if r.shape.is_mutable() {
quote! { #ptr: *mut #ty }
} else {
quote! { #ptr: *const #ty }
});
}
for (name, ty) in &args {
let (a, conversion) = string_arg_conversion(name, ty, &taken);
wrapper_args.extend(a);
conversions.extend(conversion);
call_args.push(quote! { #name });
}
let signature = {
let returned = ret.passed_types();
quote! { #(#wrapper_args)* #(#returned)* }
};
let environment = crate::environment::prune_unused_lifetimes(environment, signature);
let (lifetimes, _, lifetime_where) = environment.split_for_impl();
let self_binding = receiver
.as_ref()
.map(|r| r.shape.binding(&self_obj, &ptr))
.unwrap_or_default();
let call = match &target {
CallTarget::Free(name) => quote! { #name(#(#call_args),*) },
CallTarget::Method { path, .. } => {
let self_arg = receiver.as_ref().and_then(|r| r.shape.argument(&self_obj));
let args = self_arg.into_iter().chain(call_args.iter().cloned());
quote! { #path(#(#args),*) }
}
};
let call = quote! { #call #call_suffix };
let prologue = quote! { #(#conversions)* #self_binding };
let slot = format_ident!("__RUSTCALL_PANIC_{}", symbol.to_string().to_uppercase());
let reader = format_ident!("{}", panic_symbol(&symbol.to_string()));
let mut out = TokenStream2::new();
out.extend(panic_channel(&cfg_attrs, &slot, &reader));
let wrapper = match ret {
WrapperReturn::Unit => {
let guarded = guarded_body(
&julia_name,
&slot,
&prologue,
quote! { #call },
quote! {},
true,
panic_hook,
);
quote! {
#(#cfg_attrs)*
#[no_mangle]
pub extern "C" fn #symbol #lifetimes (#(#wrapper_args),*) #lifetime_where {
#guarded
}
}
}
WrapperReturn::Plain(ty) => {
let sentinel = quote! { ::std::mem::MaybeUninit::zeroed() };
let guarded = guarded_body(
&julia_name,
&slot,
&prologue,
quote! { ::std::mem::MaybeUninit::new(#call) },
sentinel,
false,
panic_hook,
);
quote! {
#(#cfg_attrs)*
#[no_mangle]
pub extern "C" fn #symbol #lifetimes (#(#wrapper_args),*) -> ::std::mem::MaybeUninit<#ty> #lifetime_where {
#guarded
}
}
}
WrapperReturn::Boxed(ty) => {
let body = quote! {
let obj = #call;
Box::into_raw(Box::new(obj))
};
let guarded = guarded_body(
&julia_name,
&slot,
&prologue,
body,
quote! { ::std::ptr::null_mut() },
false,
panic_hook,
);
quote! {
#(#cfg_attrs)*
#[no_mangle]
pub extern "C" fn #symbol #lifetimes (#(#wrapper_args),*) -> *mut #ty #lifetime_where {
#guarded
}
}
}
WrapperReturn::OwnedString {
helper,
free,
declare,
} => {
if declare {
out.extend(owned_string_helper(&cfg_attrs, &helper, &free));
}
let body = quote! {
let rustcall_value = #call;
let mut rustcall_bytes = ToString::to_string(&rustcall_value).into_bytes();
let rustcall_ret = #helper {
ptr: rustcall_bytes.as_mut_ptr(),
len: rustcall_bytes.len(),
cap: rustcall_bytes.capacity(),
};
std::mem::forget(rustcall_bytes);
rustcall_ret
};
let sentinel = quote! {
#helper { ptr: ::std::ptr::null_mut(), len: 0, cap: 0 }
};
let guarded = guarded_body(
&julia_name,
&slot,
&prologue,
body,
sentinel,
false,
panic_hook,
);
quote! {
#(#cfg_attrs)*
#[no_mangle]
pub extern "C" fn #symbol #lifetimes (#(#wrapper_args),*) -> #helper #lifetime_where {
#guarded
}
}
}
WrapperReturn::BorrowedStr { helper, declare } => {
if declare {
out.extend(borrowed_string_helper(&cfg_attrs, &helper));
}
let body = quote! {
let rustcall_value = #call;
#helper {
ptr: rustcall_value.as_ptr(),
len: rustcall_value.len(),
}
};
let sentinel = quote! {
#helper { ptr: ::std::ptr::null(), len: 0 }
};
let guarded = guarded_body(
&julia_name,
&slot,
&prologue,
body,
sentinel,
false,
panic_hook,
);
quote! {
#(#cfg_attrs)*
#[no_mangle]
pub extern "C" fn #symbol #lifetimes (#(#wrapper_args),*) -> #helper #lifetime_where {
#guarded
}
}
}
WrapperReturn::CResult { name, ok, err } => {
if matches!(ok, WrapperPayload::BoxedVerified(_)) {
let marker = format_ident!("{}", boxed_result_marker(&symbol.to_string()));
out.extend(quote! {
#(#cfg_attrs)*
#[no_mangle]
pub extern "C" fn #marker() -> u8 { 1 }
});
}
out.extend(payload_helpers(&cfg_attrs, &[&ok, &err]));
out.extend(generate_c_result_type(
&name,
&ok.stored_type(),
&err.stored_type(),
&cfg_attrs,
));
let sentinel = quote! { #name::panicked() };
let body = if ok.is_plain() && err.is_plain() {
quote! { #name::new(#call) }
} else {
let ok_binding = fresh_ident("rustcall_ok", &taken);
let err_binding = fresh_ident("rustcall_err", &taken);
let ok_store = ok.store_expr(&ok_binding);
let err_store = err.store_expr(&err_binding);
quote! {
#name::new(match #call {
::std::result::Result::Ok(#ok_binding) =>
::std::result::Result::Ok(#ok_store),
::std::result::Result::Err(#err_binding) =>
::std::result::Result::Err(#err_store),
})
}
};
let guarded = guarded_body(
&julia_name,
&slot,
&prologue,
body,
sentinel,
false,
panic_hook,
);
quote! {
#(#cfg_attrs)*
#[no_mangle]
pub extern "C" fn #symbol #lifetimes (#(#wrapper_args),*) -> #name #lifetime_where {
#guarded
}
}
}
WrapperReturn::COption { name, inner } => {
out.extend(payload_helpers(&cfg_attrs, &[&inner]));
out.extend(generate_c_option_type(
&name,
&inner.stored_type(),
&cfg_attrs,
));
let sentinel = quote! { #name::panicked() };
let body = if inner.is_plain() {
quote! { #name::new(#call) }
} else {
let binding = fresh_ident("rustcall_some", &taken);
let store = inner.store_expr(&binding);
quote! {
#name::new(match #call {
::std::option::Option::Some(#binding) =>
::std::option::Option::Some(#store),
::std::option::Option::None => ::std::option::Option::None,
})
}
};
let guarded = guarded_body(
&julia_name,
&slot,
&prologue,
body,
sentinel,
false,
panic_hook,
);
quote! {
#(#cfg_attrs)*
#[no_mangle]
pub extern "C" fn #symbol #lifetimes (#(#wrapper_args),*) -> #name #lifetime_where {
#guarded
}
}
}
};
out.extend(wrapper);
Ok(out)
}
pub(crate) fn owned_string_helper_items(helper: &Ident, free: &Ident) -> TokenStream2 {
owned_string_helper(&[], helper, free)
}
fn payload_helpers(cfg_attrs: &[Attribute], payloads: &[&WrapperPayload]) -> TokenStream2 {
let mut out = TokenStream2::new();
let mut declared: Vec<String> = Vec::new();
for p in payloads {
if let Some((helper, free)) = p.declaration() {
if declared.contains(&helper.to_string()) {
continue;
}
declared.push(helper.to_string());
out.extend(owned_string_helper(cfg_attrs, helper, free));
}
}
out
}
fn owned_string_helper(cfg_attrs: &[Attribute], helper: &Ident, free: &Ident) -> TokenStream2 {
quote! {
#(#cfg_attrs)*
#[repr(C)]
pub struct #helper {
pub ptr: *mut u8,
pub len: usize,
pub cap: usize,
}
#(#cfg_attrs)*
#[no_mangle]
pub extern "C" fn #free(ptr: *mut u8, len: usize, cap: usize) {
if !ptr.is_null() {
unsafe { drop(Vec::from_raw_parts(ptr, len, cap)); }
}
}
}
}
fn borrowed_string_helper(cfg_attrs: &[Attribute], helper: &Ident) -> TokenStream2 {
quote! {
#(#cfg_attrs)*
#[repr(C)]
pub struct #helper {
pub ptr: *const u8,
pub len: usize,
}
}
}
fn generate_c_result_type(
name: &Ident,
ok_type: &Type,
err_type: &Type,
cfg_attrs: &[Attribute],
) -> TokenStream2 {
quote! {
#(#cfg_attrs)*
#[repr(C)]
pub struct #name {
is_ok: u8,
ok_value: ::std::mem::MaybeUninit<#ok_type>,
err_value: ::std::mem::MaybeUninit<#err_type>,
}
#(#cfg_attrs)*
impl #name {
pub fn new(value: Result<#ok_type, #err_type>) -> Self {
match value {
Ok(v) => Self {
is_ok: 1,
ok_value: ::std::mem::MaybeUninit::new(v),
err_value: ::std::mem::MaybeUninit::zeroed(),
},
Err(e) => Self {
is_ok: 0,
ok_value: ::std::mem::MaybeUninit::zeroed(),
err_value: ::std::mem::MaybeUninit::new(e),
},
}
}
pub fn is_ok(&self) -> bool {
self.is_ok == 1
}
pub fn ok(&self) -> Option<&#ok_type> {
if self.is_ok == 1 { Some(unsafe { self.ok_value.assume_init_ref() }) } else { None }
}
pub fn err(&self) -> Option<&#err_type> {
if self.is_ok == 0 { Some(unsafe { self.err_value.assume_init_ref() }) } else { None }
}
pub fn panicked() -> Self {
Self {
is_ok: 0,
ok_value: ::std::mem::MaybeUninit::zeroed(),
err_value: ::std::mem::MaybeUninit::zeroed(),
}
}
}
}
}
fn generate_c_option_type(
name: &Ident,
inner_type: &Type,
cfg_attrs: &[Attribute],
) -> TokenStream2 {
quote! {
#(#cfg_attrs)*
#[repr(C)]
pub struct #name {
is_some: u8,
value: ::std::mem::MaybeUninit<#inner_type>,
}
#(#cfg_attrs)*
impl #name {
pub fn new(value: Option<#inner_type>) -> Self {
match value {
Some(v) => Self {
is_some: 1,
value: ::std::mem::MaybeUninit::new(v),
},
None => Self {
is_some: 0,
value: ::std::mem::MaybeUninit::zeroed(),
},
}
}
pub fn is_some(&self) -> bool {
self.is_some == 1
}
pub fn some(&self) -> Option<&#inner_type> {
if self.is_some == 1 { Some(unsafe { self.value.assume_init_ref() }) } else { None }
}
pub fn panicked() -> Self {
Self {
is_some: 0,
value: ::std::mem::MaybeUninit::zeroed(),
}
}
}
}
}
struct FreeFnOptions {
wrap_result: bool,
panic_hook: PanicHook,
}
impl Default for FreeFnOptions {
fn default() -> Self {
FreeFnOptions {
wrap_result: true,
panic_hook: PanicHook::External,
}
}
}
fn free_function_wrapper(
func: &ItemFn,
module_path: &[String],
options: &FreeFnOptions,
) -> TokenStream2 {
generate_wrapper(free_function_spec(func, module_path, options))
}
pub(crate) fn free_function_wrapper_refusal(
func: &ItemFn,
module_path: &[String],
) -> Option<Refusal> {
wrapper_refusal(free_function_spec(
func,
module_path,
&FreeFnOptions::default(),
))
}
fn free_function_spec(
func: &ItemFn,
module_path: &[String],
options: &FreeFnOptions,
) -> WrapperSpec {
let name = func.sig.ident.clone();
let stem = format_ident!("{}", symbol_stem(module_path, &name.to_string()));
let symbol = format_ident!("{}{}", SYMBOL_PREFIX, stem);
let cfgs = cfg_attrs(&func.attrs);
let ret = free_fn_return(func, &stem, options);
WrapperSpec {
symbol,
cfg_attrs: cfgs,
receiver: None,
generics: func.sig.generics.clone(),
host: None,
args: arg_pairs(&func.sig),
ret,
target: CallTarget::Free(name.into()),
call_suffix: TokenStream2::new(),
panic_hook: options.panic_hook,
}
}
fn payload_of(ty: &Type, helper: &Ident, free: &Ident, declare: bool) -> WrapperPayload {
if is_string_type(ty) || is_str_ref_type(ty) {
WrapperPayload::OwnedString {
helper: helper.clone(),
free: free.clone(),
declare,
}
} else {
WrapperPayload::Plain(ty.clone())
}
}
pub use crate::refusal::payload_is_representable;
pub fn method_wraps_result(ty: &Type) -> bool {
extract_result_type(ty)
.map(|r| payload_is_representable(&r.ok_type) && payload_is_representable(&r.err_type))
.unwrap_or(false)
}
pub fn method_wraps_option(ty: &Type) -> bool {
extract_option_type(ty)
.map(|o| payload_is_representable(&o.inner_type))
.unwrap_or(false)
}
pub fn payload_abi(ty: &Type) -> &'static str {
if is_string_type(ty) || is_str_ref_type(ty) {
"string"
} else {
""
}
}
fn free_fn_return(func: &ItemFn, name: &Ident, options: &FreeFnOptions) -> WrapperReturn {
let ReturnType::Type(_, ty) = &func.sig.output else {
return WrapperReturn::Unit;
};
if options.wrap_result {
let helper = format_ident!("{}_RustCallOwnedString", name);
let free = format_ident!("{}_free_rust_string", name);
let payload = |ty: &Type| payload_of(ty, &helper, &free, true);
if let Some(r) = extract_result_type(ty) {
return WrapperReturn::CResult {
name: format_ident!("CResult_{}", name),
ok: payload(&r.ok_type),
err: payload(&r.err_type),
};
}
if let Some(o) = extract_option_type(ty) {
return WrapperReturn::COption {
name: format_ident!("COption_{}", name),
inner: payload(&o.inner_type),
};
}
}
if function_returns_string(&func.sig) || returns_copied_str(&func.sig) {
return WrapperReturn::OwnedString {
helper: format_ident!("{}_RustCallOwnedString", name),
free: format_ident!("{}_free_rust_string", name),
declare: true,
};
}
if returns_borrowed_str(&func.sig) {
return WrapperReturn::BorrowedStr {
helper: format_ident!("{}_RustCallBorrowedString", name),
declare: true,
};
}
WrapperReturn::Plain((**ty).clone())
}
pub fn transform_function(
func: ItemFn,
module_path: &[String],
panic_hook: PanicHook,
) -> TokenStream2 {
if let Some(refusal) = crate::refusal::function_refusal(&func, module_path, Mode::Crate) {
let error = refusal.compile_error(&cfg_attrs(&func.attrs));
return quote! { #error #func };
}
let wrapper = free_function_wrapper(
&func,
module_path,
&FreeFnOptions {
panic_hook,
..FreeFnOptions::default()
},
);
quote! {
#func
#wrapper
}
}
fn inline_method_is_wrapped(site: crate::refusal::MethodSite<'_>, m: &MethodModel) -> bool {
crate::refusal::method_refusal(site, m).is_none()
}
pub(crate) fn method_wrapper_refusal(
self_ty: &Type,
struct_name: &Ident,
m: &MethodModel,
) -> Option<Refusal> {
let Type::Path(self_path) = unparen(self_ty) else {
return None;
};
let stem = struct_stem(&[], struct_name);
let owned_helper = format_ident!("{}_RustCallOwnedString", stem);
let owned_free = format_ident!("{}_free_rust_string", stem);
let borrowed_helper = format_ident!("{}_RustCallBorrowedString", stem);
wrapper_refusal(method_spec(
&self_path.path,
struct_name,
&stem,
m,
&owned_helper,
&owned_free,
&borrowed_helper,
true,
PanicHook::External,
))
}
pub fn plain_function_wrapper(func: &ItemFn, module_path: &[String]) -> TokenStream2 {
free_function_wrapper(
func,
module_path,
&FreeFnOptions {
panic_hook: PanicHook::FileOwned,
wrap_result: false,
},
)
}
pub fn crate_struct_needs_owned_string_helper(item_struct: &ItemStruct) -> bool {
let syn::Fields::Named(ref fields) = item_struct.fields else {
return false;
};
fields
.named
.iter()
.any(|f| f.ident.is_some() && field_has_accessors(&f.ty) && is_string_type(&f.ty))
}
pub(crate) fn guard_struct_helper(tokens: TokenStream2, hook: PanicHook) -> TokenStream2 {
let mut function: ItemFn = syn::parse2(tokens).expect("generated struct helper is a function");
let symbol = &function.sig.ident;
let suffix: String = symbol
.to_string()
.bytes()
.map(|b| format!("{b:02X}"))
.collect();
let slot = format_ident!("__RUSTCALL_HELPER_PANIC_{}", suffix);
let reader = format_ident!("{}", panic_symbol(&symbol.to_string()));
let channel = panic_channel(&cfg_attrs(&function.attrs), &slot, &reader);
let original = function.block.clone();
let (sentinel, unit, body) = match function.sig.output.clone() {
ReturnType::Default => (quote! {}, true, quote! { #original }),
ReturnType::Type(_, ty) if matches!(unparen(&ty), Type::Tuple(t) if t.elems.is_empty()) => {
(quote! {}, true, quote! { #original })
}
ReturnType::Type(_, ty) if is_vec_type(&ty) => (
quote! { ::std::vec::Vec::new() },
false,
quote! { #original },
),
ReturnType::Type(arrow, ty) => {
function.sig.output =
ReturnType::Type(arrow, syn::parse_quote!(::std::mem::MaybeUninit<#ty>));
(
quote! { ::std::mem::MaybeUninit::zeroed() },
false,
quote! { ::std::mem::MaybeUninit::new(#original) },
)
}
};
let body = guarded_body(
&symbol.to_string(),
&slot,
"e! {},
body,
sentinel,
unit,
hook,
);
function.block = syn::parse_quote!({ #body });
quote! { #channel #function }
}
fn crate_field_accessors(
item_struct: &ItemStruct,
stem: &Ident,
cfgs: &[Attribute],
) -> TokenStream2 {
let hook = PanicHook::Runtime;
let struct_name = &item_struct.ident;
let owned_helper = format_ident!("{}_RustCallOwnedString", stem);
let owned_free = format_ident!("{}_free_rust_string", stem);
let mut ffi_functions = TokenStream2::new();
if crate_struct_needs_owned_string_helper(item_struct) {
ffi_functions.extend(owned_string_helper(cfgs, &owned_helper, &owned_free));
}
if let syn::Fields::Named(ref fields) = item_struct.fields {
for field in &fields.named {
let Some(ref field_name) = field.ident else {
continue;
};
let field_ty = &field.ty;
if !field_has_accessors(field_ty) {
continue;
}
let mut field_cfgs = cfgs.to_vec();
field_cfgs.extend(cfg_attrs(&field.attrs));
let cfgs = field_cfgs.as_slice();
let getter_name = format_ident!("{}_get_{}", stem, field_name);
if is_string_type(field_ty) {
ffi_functions.extend(guard_struct_helper(quote! {
#(#cfgs)*
#[no_mangle]
pub extern "C" fn #getter_name(ptr: *const #struct_name) -> #owned_helper {
let mut rustcall_bytes = unsafe { (*ptr).#field_name.clone().into_bytes() };
let rustcall_ret = #owned_helper {
ptr: rustcall_bytes.as_mut_ptr(),
len: rustcall_bytes.len(),
cap: rustcall_bytes.capacity(),
};
std::mem::forget(rustcall_bytes);
rustcall_ret
}
}, hook));
} else {
ffi_functions.extend(guard_struct_helper(
quote! {
#(#cfgs)*
#[no_mangle]
pub extern "C" fn #getter_name(ptr: *const #struct_name) -> #field_ty {
unsafe { (*ptr).#field_name }
}
},
hook,
));
}
let setter_name = format_ident!("{}_set_{}", stem, field_name);
ffi_functions.extend(struct_field_setter(
struct_name,
field_name,
field_ty,
&setter_name,
cfgs,
hook,
));
}
}
ffi_functions
}
pub(crate) fn struct_field_setter(
owner: &impl quote::ToTokens,
field: &Ident,
ty: &Type,
setter: &Ident,
cfgs: &[Attribute],
hook: PanicHook,
) -> TokenStream2 {
let value = format_ident!("value");
let (args, conversion) = if is_string_type(ty) {
string_arg_conversion(&value, ty, &["ptr".into()])
} else {
(vec![quote! { value: #ty }], None)
};
guard_struct_helper(
quote! {
#(#cfgs)*
#[no_mangle]
pub extern "C" fn #setter(ptr: *mut #owner, #(#args),*) {
#conversion
unsafe { (*ptr).#field = value; }
}
},
hook,
)
}
pub(crate) fn struct_free_wrapper(
struct_type: &syn::Path,
stem: &Ident,
cfgs: &[Attribute],
hook: PanicHook,
) -> TokenStream2 {
let free_fn_name = format_ident!("{}_free", stem);
let slot_suffix: String = free_fn_name
.to_string()
.bytes()
.map(|byte| format!("{byte:02X}"))
.collect();
let slot = format_ident!("__RUSTCALL_DROP_PANIC_{}", slot_suffix);
let reader = format_ident!("{}", panic_symbol(&free_fn_name.to_string()));
let channel = panic_channel(cfgs, &slot, &reader);
let body = guarded_body(
&format!("{}::drop", path_tail(struct_type)),
&slot,
"e! {},
quote! {
if !ptr.is_null() {
unsafe { drop(Box::from_raw(ptr)); }
}
},
quote! {},
true,
hook,
);
quote! {
#channel
#(#cfgs)*
#[no_mangle]
pub extern "C" fn #free_fn_name(ptr: *mut #struct_type) {
#body
}
}
}
fn struct_stem(module_path: &[String], struct_name: &Ident) -> Ident {
format_ident!("{}", symbol_stem(module_path, &struct_name.to_string()))
}
pub fn transform_struct_crate(mut item_struct: ItemStruct, module_path: &[String]) -> TokenStream2 {
if let Some(refusal) = crate::refusal::struct_refusal(&item_struct, Mode::Crate) {
let error = refusal.compile_error(&cfg_attrs(&item_struct.attrs));
return quote! { #error #item_struct };
}
let repr_c: Attribute = syn::parse_quote!(#[repr(C)]);
item_struct.attrs.insert(0, repr_c);
item_struct.vis = Visibility::Public(syn::token::Pub::default());
let stem = struct_stem(module_path, &item_struct.ident);
let cfgs = cfg_attrs(&item_struct.attrs);
let struct_name = &item_struct.ident;
let free = struct_free_wrapper(
&syn::parse_quote!(#struct_name),
&stem,
&cfgs,
PanicHook::Runtime,
);
let accessors = crate_field_accessors(&item_struct, &stem, &cfgs);
quote! {
#item_struct
#free
#accessors
}
}
pub fn impl_target_module_path(module_path: &[String], self_ty: &Type) -> Vec<String> {
crate::paths::type_path_qualifier(self_ty).macro_target_path(module_path)
}
pub fn transform_impl_crate(mut item_impl: ItemImpl, module_path: &[String]) -> TokenStream2 {
if let Some(refusal) = crate::refusal::impl_refusal(&item_impl) {
let error = refusal.compile_error(&cfg_attrs(&item_impl.attrs));
for item in &mut item_impl.items {
if let syn::ImplItem::Fn(method) = item {
method.attrs.retain(|attr| !attr.path().is_ident("julia"));
}
}
return quote! { #error #item_impl };
}
let struct_path = impl_target_module_path(module_path, &item_impl.self_ty);
let host = ImplHost::of(&item_impl);
let block_cfgs = cfg_attrs(&item_impl.attrs);
let mut ffi_wrappers = TokenStream2::new();
for item in &mut item_impl.items {
if let syn::ImplItem::Fn(method) = item {
let has_julia_attr = method
.attrs
.iter()
.any(|attr| attr.path().is_ident("julia"));
if has_julia_attr {
method.attrs.retain(|attr| !attr.path().is_ident("julia"));
let mut gated = method.clone();
gated.attrs.splice(0..0, block_cfgs.iter().cloned());
ffi_wrappers.extend(method_wrapper_in_block(&host, &struct_path, &gated));
}
}
}
quote! {
#item_impl
#ffi_wrappers
}
}
pub fn transform_module(item_mod: ItemMod, module_path: &[String]) -> TokenStream2 {
if let Some(refusal) = crate::refusal::module_refusal(&item_mod) {
return refusal.compile_error(&cfg_attrs(&item_mod.attrs));
}
let Some((_, items)) = item_mod.content else {
return TokenStream2::new();
};
let mut path = module_path.to_vec();
path.push(item_mod.ident.to_string());
let mut body = TokenStream2::new();
for item in items {
body.extend(expand_marked_item(item, &path));
}
let attrs = &item_mod.attrs;
let vis = &item_mod.vis;
let unsafety = &item_mod.unsafety;
let ident = &item_mod.ident;
quote! { #(#attrs)* #vis #unsafety mod #ident { #body } }
}
fn expand_marked_item(item: Item, module_path: &[String]) -> TokenStream2 {
fn take_julia(attrs: &mut Vec<Attribute>) -> bool {
let before = attrs.len();
attrs.retain(|attr| !crate::attrs::is_julia_attr(attr));
attrs.len() != before
}
match item {
Item::Fn(mut f) => {
if take_julia(&mut f.attrs) {
transform_function(f, module_path, PanicHook::Runtime)
} else {
quote! { #f }
}
}
Item::Struct(mut s) => {
if take_julia(&mut s.attrs) {
transform_struct_crate(s, module_path)
} else {
quote! { #s }
}
}
Item::Impl(mut i) => {
if take_julia(&mut i.attrs) {
transform_impl_crate(i, module_path)
} else {
quote! { #i }
}
}
Item::Mod(mut m) => {
if take_julia(&mut m.attrs) {
transform_module(m, module_path)
} else {
quote! { #m }
}
}
other => match crate::refusal::julia_item_refusal(&other) {
Some(refusal) => {
let error = refusal.compile_error(&cfg_attrs(&crate::refusal::item_attrs(&other)));
let kept = crate::refusal::without_julia_attr(other);
quote! { #error #kept }
}
None => quote! { #other },
},
}
}
pub fn transform_unsupported_item(item: TokenStream2) -> TokenStream2 {
let error = crate::refusal::attribute_target_refusal(&item).compile_error(&[]);
quote! {
#error
#item
}
}
pub fn is_marked_module(item_mod: &ItemMod) -> bool {
item_mod.attrs.iter().any(crate::attrs::is_julia_attr)
}
pub(crate) fn boxed_result_marker(symbol: &str) -> String {
format!("{symbol}_boxed_result_v1")
}
pub fn returns_boxed_struct(struct_name: &Ident, method: &syn::ImplItemFn) -> bool {
returns_own_type(&method.sig.output, struct_name, None)
}
pub fn returns_own_type(output: &ReturnType, struct_name: &Ident, own_ty: Option<&Type>) -> bool {
let ReturnType::Type(_, ty) = output else {
return false;
};
let ty = unparen(ty);
let is_self = matches!(ty, Type::Path(tp) if tp.qself.is_none() && tp.path.is_ident("Self"));
is_self
|| match own_ty {
Some(own) => {
matches!(ty, Type::Path(_)) && crate::receiver::same_spelling(ty, unparen(own))
}
None => is_self_type(ty, struct_name),
}
}
pub fn generate_method_wrapper_crate(
self_ty: &Type,
module_path: &[String],
method: &syn::ImplItemFn,
) -> TokenStream2 {
method_wrapper_in_block(
&ImplHost {
generics: syn::Generics::default(),
self_ty: self_ty.clone(),
trait_: None,
},
module_path,
method,
)
}
fn method_wrapper_in_block(
host: &ImplHost,
module_path: &[String],
method: &syn::ImplItemFn,
) -> TokenStream2 {
let self_ty = &host.self_ty;
let mut model = MethodModel::from_fn(method, crate::manifest::Attribute::Julia);
model.host = Some(host.clone());
let Some(struct_name) = last_ident(self_ty) else {
return crate::refusal::impl_header_refusal(self_ty)
.map(|refusal| refusal.compile_error(&cfg_attrs(&method.attrs)))
.unwrap_or_default();
};
method_wrapper_at_impl_site(
self_ty,
struct_name,
module_path,
&model,
PanicHook::Runtime,
)
}
pub fn method_wrapper_at_impl_site(
self_ty: &Type,
struct_name: &Ident,
struct_module_path: &[String],
m: &MethodModel,
panic_hook: PanicHook,
) -> TokenStream2 {
let Type::Path(self_path) = unparen(self_ty) else {
return crate::refusal::impl_header_refusal(self_ty)
.map(|refusal| refusal.compile_error(&cfg_attrs(&m.func.attrs)))
.unwrap_or_default();
};
let site = match panic_hook {
PanicHook::Runtime => crate::refusal::MethodSite::Crate { self_ty },
_ => crate::refusal::MethodSite::Inline {
self_ty,
struct_name,
},
};
if let Some(refusal) = crate::refusal::method_refusal(site, m) {
return refusal.compile_error(&cfg_attrs(&m.func.attrs));
}
let stem = struct_stem(struct_module_path, struct_name);
let owner = format_ident!(
"{}",
method_string_owner(&stem.to_string(), &m.method_stem())
);
let owned_helper = format_ident!("{}_RustCallOwnedString", owner);
let owned_free = format_ident!("{}_free_rust_string", owner);
let borrowed_helper = format_ident!("{}_RustCallBorrowedString", owner);
generate_wrapper(method_spec(
&self_path.path,
struct_name,
&stem,
m,
&owned_helper,
&owned_free,
&borrowed_helper,
true,
panic_hook,
))
}
pub fn inline_foreign_method_wrapper(
self_ty: &Type,
struct_name: &Ident,
struct_module_path: &[String],
m: &MethodModel,
) -> TokenStream2 {
let mut gated = m.clone();
gated
.func
.attrs
.splice(0..0, m.enclosing_cfg.iter().cloned());
method_wrapper_at_impl_site(
self_ty,
struct_name,
struct_module_path,
&gated,
PanicHook::FileOwned,
)
}
#[derive(Debug, Default, Clone)]
pub struct InlineStructMeta {
pub has_clone: bool,
pub has_owned_string_helper: bool,
pub has_borrowed_string_helper: bool,
pub accessors: Vec<(String, String, String)>,
}
fn method_result_return(m: &MethodModel) -> Option<crate::types::ResultTypeInfo> {
match &m.func.sig.output {
ReturnType::Type(_, ty) if method_wraps_result(ty) => extract_result_type(ty),
_ => None,
}
}
fn method_option_return(m: &MethodModel) -> Option<crate::types::OptionTypeInfo> {
match &m.func.sig.output {
ReturnType::Type(_, ty) if method_wraps_option(ty) => extract_option_type(ty),
_ => None,
}
}
fn method_needs_owned_string(m: &MethodModel) -> bool {
if method_returns_string(m) || method_copies_str(m) {
return true;
}
if let Some(r) = method_result_return(m) {
return !payload_abi(&r.ok_type).is_empty() || !payload_abi(&r.err_type).is_empty();
}
if let Some(o) = method_option_return(m) {
return !payload_abi(&o.inner_type).is_empty();
}
false
}
fn method_returns_string(m: &MethodModel) -> bool {
matches!(&m.func.sig.output, ReturnType::Type(_, ty) if is_string_type(ty))
}
fn method_copies_str(m: &MethodModel) -> bool {
returns_copied_str(&m.func.sig)
}
fn method_returns_borrowed_str(m: &MethodModel) -> bool {
returns_borrowed_str(&m.func.sig)
}
fn inline_method_is_ctor(struct_name: &Ident, m: &MethodModel) -> bool {
m.returns_boxed_struct(struct_name)
}
pub fn inline_struct_wrappers(
model: &StructModel,
module_path: &[String],
) -> (TokenStream2, InlineStructMeta) {
let struct_name = &model.item.ident;
let stem = struct_stem(module_path, struct_name);
let mut out = TokenStream2::new();
let mut meta = InlineStructMeta::default();
let cfgs = cfg_attrs(&model.item.attrs);
out.extend(struct_free_wrapper(
&syn::parse_quote!(#struct_name),
&stem,
&cfgs,
PanicHook::FileOwned,
));
let fields = model.named_fields();
let accessible: Vec<&(Ident, Type)> = fields
.iter()
.filter(|(_, ty)| field_has_accessors(ty))
.collect();
let local: Vec<&MethodModel> = model
.methods
.iter()
.filter(|m| m.is_local_to(module_path))
.collect();
let self_ty: Type = syn::parse_quote!(#struct_name);
let site = crate::refusal::MethodSite::Inline {
self_ty: &self_ty,
struct_name,
};
let wrapped = || local.iter().filter(|m| inline_method_is_wrapped(site, m));
let needs_owned = accessible.iter().any(|(_, ty)| is_string_type(ty))
|| wrapped()
.any(|m| method_needs_owned_string(m) && !inline_method_is_ctor(struct_name, m));
let needs_borrowed =
wrapped().any(|m| method_returns_borrowed_str(m) && !inline_method_is_ctor(struct_name, m));
let owned_helper = format_ident!("{}_RustCallOwnedString", stem);
let borrowed_helper = format_ident!("{}_RustCallBorrowedString", stem);
let owned_free = format_ident!("{}_free_rust_string", stem);
if needs_owned {
meta.has_owned_string_helper = true;
out.extend(owned_string_helper(&cfgs, &owned_helper, &owned_free));
}
if needs_borrowed {
meta.has_borrowed_string_helper = true;
out.extend(borrowed_string_helper(&cfgs, &borrowed_helper));
}
for (field_name, field_ty) in &accessible {
let getter = format_ident!("{}_get_{}", stem, field_name);
let setter = format_ident!("{}_set_{}", stem, field_name);
meta.accessors.push((
field_name.to_string(),
getter.to_string(),
setter.to_string(),
));
let mut field_cfgs = cfgs.clone();
field_cfgs.extend(model.field_cfg_attrs(field_name));
if is_string_type(field_ty) {
out.extend(guard_struct_helper(
quote! {
#(#field_cfgs)*
#[no_mangle]
pub extern "C" fn #getter(ptr: *const #struct_name) -> #owned_helper {
let mut rustcall_bytes = unsafe { (*ptr).#field_name.clone().into_bytes() };
let rustcall_ret = #owned_helper {
ptr: rustcall_bytes.as_mut_ptr(),
len: rustcall_bytes.len(),
cap: rustcall_bytes.capacity(),
};
std::mem::forget(rustcall_bytes);
rustcall_ret
}
},
PanicHook::FileOwned,
));
} else {
out.extend(guard_struct_helper(
quote! {
#(#field_cfgs)*
#[no_mangle]
pub extern "C" fn #getter(ptr: *const #struct_name) -> #field_ty {
unsafe { (*ptr).#field_name }
}
},
PanicHook::FileOwned,
));
}
out.extend(struct_field_setter(
struct_name,
field_name,
field_ty,
&setter,
&field_cfgs,
PanicHook::FileOwned,
));
}
if model.derives.iter().any(|d| d == "Clone") {
meta.has_clone = true;
let clone_name = format_ident!("{}_clone", stem);
out.extend(guard_struct_helper(
quote! {
#(#cfgs)*
#[no_mangle]
pub extern "C" fn #clone_name(ptr: *const #struct_name) -> *mut #struct_name {
unsafe { Box::into_raw(Box::new((*ptr).clone())) }
}
},
PanicHook::FileOwned,
));
}
for m in &local {
let mut gated = (*m).clone();
gated
.func
.attrs
.splice(0..0, cfgs.iter().chain(m.enclosing_cfg.iter()).cloned());
if let Some(refusal) = crate::refusal::method_refusal(site, m) {
out.extend(refusal.compile_error(&cfg_attrs(&gated.func.attrs)));
continue;
}
out.extend(inline_method_wrapper(
struct_name,
&stem,
&gated,
&owned_helper,
&owned_free,
&borrowed_helper,
));
}
(out, meta)
}
#[allow(clippy::too_many_arguments)]
fn method_spec(
self_path: &syn::Path,
struct_name: &Ident,
stem: &Ident,
m: &MethodModel,
owned_helper: &Ident,
owned_free: &Ident,
borrowed_helper: &Ident,
declare: bool,
panic_hook: PanicHook,
) -> WrapperSpec {
let method_name = m.func.sig.ident.clone();
let method_stem = m.method_stem();
let symbol = format_ident!("{}", method_symbol_of(&stem.to_string(), &method_stem));
let shape = m.receiver();
let receiver = (!shape.is_static()).then(|| WrapperReceiver {
ty: self_path.clone(),
shape: shape.clone(),
borrow: m
.func
.sig
.receiver()
.map(crate::environment::SelfBorrow::of)
.unwrap_or(crate::environment::SelfBorrow::None),
});
let target = CallTarget::Method {
ty: self_path.clone(),
path: crate::environment::method_item_path(m.host.as_ref(), self_path, &method_name),
};
let ret = if let Some(result) = m.fallible_constructor(struct_name) {
WrapperReturn::CResult {
name: format_ident!("CResult_{}_{}", stem, method_stem),
ok: WrapperPayload::BoxedVerified(self_path.clone()),
err: payload_of(&result.err_type, owned_helper, owned_free, declare),
}
} else if inline_method_is_ctor(struct_name, m) {
WrapperReturn::Boxed(self_path.clone())
} else if let Some(r) = method_result_return(m) {
WrapperReturn::CResult {
name: format_ident!("CResult_{}_{}", stem, method_stem),
ok: payload_of(&r.ok_type, owned_helper, owned_free, declare),
err: payload_of(&r.err_type, owned_helper, owned_free, declare),
}
} else if let Some(o) = method_option_return(m) {
WrapperReturn::COption {
name: format_ident!("COption_{}_{}", stem, method_stem),
inner: payload_of(&o.inner_type, owned_helper, owned_free, declare),
}
} else if method_returns_string(m) || method_copies_str(m) {
WrapperReturn::OwnedString {
helper: owned_helper.clone(),
free: owned_free.clone(),
declare,
}
} else if method_returns_borrowed_str(m) {
WrapperReturn::BorrowedStr {
helper: borrowed_helper.clone(),
declare,
}
} else {
match &m.func.sig.output {
ReturnType::Default => WrapperReturn::Unit,
ReturnType::Type(_, ty) => WrapperReturn::Plain((**ty).clone()),
}
};
WrapperSpec {
symbol,
cfg_attrs: cfg_attrs(&m.func.attrs),
receiver,
generics: m.func.sig.generics.clone(),
host: Some(m.host.clone().unwrap_or_else(|| ImplHost {
generics: syn::Generics::default(),
self_ty: Type::Path(syn::TypePath {
qself: None,
path: self_path.clone(),
}),
trait_: None,
})),
args: arg_pairs(&m.func.sig),
ret,
target,
call_suffix: TokenStream2::new(),
panic_hook,
}
}
fn inline_method_wrapper(
struct_name: &Ident,
stem: &Ident,
m: &MethodModel,
owned_helper: &Ident,
owned_free: &Ident,
borrowed_helper: &Ident,
) -> TokenStream2 {
generate_wrapper(method_spec(
&syn::Path::from(struct_name.clone()),
struct_name,
stem,
m,
owned_helper,
owned_free,
borrowed_helper,
false,
PanicHook::FileOwned,
))
}
fn wrapper_param_names(decl: &syn::Generics, self_ty: &Type) -> Vec<String> {
let declared: Vec<String> = decl
.params
.iter()
.filter_map(|p| match p {
syn::GenericParam::Type(tp) => Some(tp.ident.to_string()),
_ => None,
})
.collect();
let mut ordered: Vec<String> = Vec::new();
if let Type::Path(tp) = self_ty {
if let Some(seg) = tp.path.segments.last() {
if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
for a in &args.args {
if let syn::GenericArgument::Type(Type::Path(p)) = a {
if p.qself.is_none() && p.path.segments.len() == 1 {
let n = p.path.segments[0].ident.to_string();
if declared.contains(&n) && !ordered.contains(&n) {
ordered.push(n);
}
}
}
}
}
}
}
for n in declared {
if !ordered.contains(&n) {
ordered.push(n);
}
}
ordered
}
fn wrapper_generics(
model: &StructModel,
m: &MethodModel,
) -> (syn::Generics, Option<syn::WhereClause>, Type) {
let owner = model.impls.iter().find(|imp| {
imp.items
.iter()
.any(|ii| matches!(ii, syn::ImplItem::Fn(f) if f.sig.ident == m.func.sig.ident))
});
let self_ty: Type = match owner {
Some(imp) => (*imp.self_ty).clone(),
None => {
let name = &model.item.ident;
let (_, ty_generics, _) = model.item.generics.split_for_impl();
syn::parse_quote!(#name #ty_generics)
}
};
let mut merged = owner
.map(|imp| imp.generics.clone())
.unwrap_or_else(|| model.item.generics.clone());
for p in &m.func.sig.generics.params {
merged.params.push(p.clone());
}
let mut predicates: Vec<syn::WherePredicate> = merged
.where_clause
.take()
.map(|w| w.predicates.into_iter().collect())
.unwrap_or_default();
if let Some(w) = &m.func.sig.generics.where_clause {
predicates.extend(w.predicates.iter().cloned());
}
if !merged.params.is_empty() {
merged.lt_token = Some(Default::default());
merged.gt_token = Some(Default::default());
}
let where_clause = if predicates.is_empty() {
None
} else {
Some(syn::WhereClause {
where_token: Default::default(),
predicates: predicates.into_iter().collect(),
})
};
(merged, where_clause, self_ty)
}
fn fn_source(func: ItemFn) -> String {
let file = syn::File {
shebang: None,
attrs: Vec::new(),
items: vec![syn::Item::Fn(func)],
};
prettyplease::unparse(&file)
}
pub fn generic_method_wrapper_name(struct_stem: &str, method: &str) -> String {
format!("{}_{}", unraw(struct_stem), method_stem(None, method))
}
pub fn inline_generic_method_refusals(model: &StructModel) -> TokenStream2 {
let struct_name = &model.item.ident;
let mut out = TokenStream2::new();
for m in &model.methods {
let Some(refusal) = crate::refusal::method_refusal(
crate::refusal::MethodSite::InlineGeneric { struct_name },
m,
) else {
continue;
};
let mut cfgs = cfg_attrs(&model.item.attrs);
cfgs.extend(m.enclosing_cfg.iter().cloned());
cfgs.extend(cfg_attrs(&m.func.attrs));
out.extend(refusal.compile_error(&cfgs));
}
out
}
pub fn inline_generic_wrappers(model: &StructModel, module_path: &[String]) -> Vec<GenericWrapper> {
let struct_name = &model.item.ident;
let stem = symbol_stem(module_path, &struct_name.to_string());
let generics = &model.item.generics;
let cfgs = cfg_attrs(&model.item.attrs);
let gated = |mut func: ItemFn, extra: &[Attribute]| -> ItemFn {
func.attrs
.splice(0..0, cfgs.iter().chain(extra.iter()).cloned());
func
};
let (_, ty_generics, _) = generics.split_for_impl();
let decl_generics = {
let mut g = generics.clone();
g.where_clause = None;
g
};
let mut wrappers = Vec::new();
let site = crate::refusal::MethodSite::InlineGeneric { struct_name };
for m in model
.methods
.iter()
.filter(|m| inline_method_is_wrapped(site, m))
{
let method_name = &m.func.sig.ident;
let wrapper_name = format_ident!(
"{}",
generic_method_wrapper_name(&stem, &method_name.to_string())
);
let (decl_generics, where_clause, self_ty) = wrapper_generics(model, m);
let where_clause = where_clause.map(|w| quote! { #w }).unwrap_or_default();
let mut wrapper_args: Vec<TokenStream2> = Vec::new();
let mut call_args: Vec<TokenStream2> = Vec::new();
let receiver = m.receiver();
if !receiver.is_static() {
if receiver.is_mutable() {
wrapper_args.push(quote! { ptr: *mut #self_ty });
} else {
wrapper_args.push(quote! { ptr: *const #self_ty });
}
}
for (i, arg) in m.func.sig.inputs.iter().enumerate() {
let FnArg::Typed(pat_type) = arg else {
continue;
};
let ty = &pat_type.ty;
let name: Ident = match pat_type.pat.as_ref() {
Pat::Ident(pi) => pi.ident.clone(),
_ => format_ident!("arg{}", i),
};
wrapper_args.push(quote! { #name: #ty });
call_args.push(quote! { #name });
}
let is_ctor = inline_method_is_ctor(struct_name, m);
let borrow = m
.func
.sig
.receiver()
.map(crate::environment::SelfBorrow::of)
.unwrap_or(crate::environment::SelfBorrow::None);
let (decl_generics, ret) = match (&m.func.sig.output, &borrow) {
(ReturnType::Type(_, ty), crate::environment::SelfBorrow::Ref(named))
if crate::environment::has_elided_lifetime(ty) =>
{
let mut g = decl_generics.clone();
let lifetime: syn::Lifetime = match named {
Some(named) => named.clone(),
None => {
let fresh = {
let predicates = &where_clause;
crate::environment::fresh_lifetime(
quote! { #g #predicates #(#wrapper_args)* #ty },
)
};
for param in g.params.iter_mut() {
if let syn::GenericParam::Type(tp) = param {
tp.bounds.push(syn::TypeParamBound::Lifetime(fresh.clone()));
}
}
g.params.insert(
0,
syn::GenericParam::Lifetime(syn::LifetimeParam::new(fresh.clone())),
);
fresh
}
};
let mut ty = (**ty).clone();
crate::environment::name_elided_lifetimes(&mut ty, &lifetime);
(g, quote! { -> #ty })
}
(other, _) => (decl_generics.clone(), quote! { #other }),
};
let ret = &ret;
let func: ItemFn = if is_ctor {
syn::parse_quote! {
pub fn #wrapper_name #decl_generics (#(#wrapper_args),*) -> *mut #self_ty #where_clause {
let obj = #struct_name::#method_name(#(#call_args),*);
Box::into_raw(Box::new(obj))
}
}
} else {
let self_obj = format_ident!("self_obj");
let binding = receiver.binding(&self_obj, &format_ident!("ptr"));
let args = receiver
.argument(&self_obj)
.into_iter()
.chain(call_args.iter().cloned());
syn::parse_quote! {
pub fn #wrapper_name #decl_generics (#(#wrapper_args),*) #ret #where_clause {
#binding
<#self_ty>::#method_name(#(#args),*)
}
}
};
let mut func = func;
crate::environment::expand_self_in_signature(
&ImplHost {
generics: decl_generics.clone(),
self_ty: self_ty.clone(),
trait_: None,
},
&mut func.sig,
);
let mut method_cfgs = m.enclosing_cfg.clone();
method_cfgs.extend(cfg_attrs(&m.func.attrs));
wrappers.push(GenericWrapper {
name: wrapper_name.to_string(),
source: fn_source(gated(func, &method_cfgs)),
type_params: wrapper_param_names(&decl_generics, &self_ty),
});
}
let struct_predicates: Vec<syn::WherePredicate> = generics
.where_clause
.as_ref()
.map(|w| w.predicates.iter().cloned().collect())
.unwrap_or_default();
let where_of = |extra: Option<syn::WherePredicate>| -> TokenStream2 {
let mut preds = struct_predicates.clone();
preds.extend(extra);
if preds.is_empty() {
quote! {}
} else {
quote! { where #(#preds),* }
}
};
let struct_where = where_of(None);
let struct_param_names = model.type_param_names();
let method_symbols: Vec<String> = wrappers.iter().map(|w| w.name.clone()).collect();
for (field_name, field_ty) in model.named_fields() {
if !generic_field_has_accessors(&field_ty, &struct_param_names) {
continue;
}
let getter = format_ident!("{}", field_getter_symbol(&stem, &field_name.to_string()));
if method_symbols.contains(&getter.to_string()) {
continue;
}
let setter = format_ident!("{}", field_setter_symbol(&stem, &field_name.to_string()));
let (body, getter_where) = if is_string_type(&field_ty) {
(
quote! { unsafe { (*ptr).#field_name.clone() } },
where_of(Some(syn::parse_quote!(#field_ty: Clone))),
)
} else {
(
quote! { unsafe { (*ptr).#field_name } },
where_of(Some(syn::parse_quote!(#field_ty: Copy))),
)
};
let g: ItemFn = syn::parse_quote! {
pub fn #getter #decl_generics (ptr: *const #struct_name #ty_generics) -> #field_ty #getter_where { #body }
};
let s: ItemFn = syn::parse_quote! {
pub fn #setter #decl_generics (ptr: *mut #struct_name #ty_generics, value: #field_ty) #struct_where {
unsafe { (*ptr).#field_name = value; }
}
};
let field_cfgs = model.field_cfg_attrs(&field_name);
let g = gated(g, &field_cfgs);
let s = gated(s, &field_cfgs);
wrappers.push(GenericWrapper {
name: getter.to_string(),
source: fn_source(g),
type_params: struct_param_names.clone(),
});
wrappers.push(GenericWrapper {
name: setter.to_string(),
source: fn_source(s),
type_params: struct_param_names.clone(),
});
}
let free_name = format_ident!("{}", struct_free_symbol(&stem));
let f: ItemFn = syn::parse_quote! {
pub fn #free_name #decl_generics (ptr: *mut #struct_name #ty_generics) #struct_where {
if !ptr.is_null() {
unsafe { drop(Box::from_raw(ptr)); }
}
}
};
wrappers.push(GenericWrapper {
name: free_name.to_string(),
source: fn_source(gated(f, &[])),
type_params: struct_param_names,
});
wrappers
}