use proc_macro2::{
Delimiter, Group, Literal, Punct, Spacing, Span, TokenStream as TokenStream2, TokenTree,
};
use quote::{quote, ToTokens};
use syn::spanned::Spanned;
use syn::{Attribute, Ident, Item, ItemFn, ItemImpl, ItemMod, ItemStruct, ReturnType, Type};
use crate::manifest::{skip_reason, Mode};
use crate::model::{ImplHost, MethodModel};
use crate::types::{extract_option_type, extract_result_type, type_to_string};
#[derive(Debug, Clone)]
pub struct Refusal {
pub kind: &'static str,
pub detail: String,
pub span: Span,
pub end: Span,
pub message: String,
}
pub const IMPL_NOT_A_PATH: &str = "impl_not_a_path";
pub const FILE_MODULE: &str = "file_module";
pub const UNSUPPORTED_ITEM: &str = "unsupported_item";
impl Refusal {
pub(crate) fn new(
kind: &'static str,
detail: impl Into<String>,
span: Span,
message: impl Into<String>,
) -> Self {
Refusal {
kind,
detail: detail.into(),
span,
end: span,
message: message.into(),
}
}
pub(crate) fn over(
kind: &'static str,
detail: impl Into<String>,
node: &dyn ToTokens,
message: impl Into<String>,
) -> Self {
let tokens: Vec<TokenTree> = node.to_token_stream().into_iter().collect();
let first = tokens
.first()
.map(TokenTree::span)
.unwrap_or_else(Span::call_site);
let last = tokens.last().map(TokenTree::span).unwrap_or(first);
Refusal {
end: last,
..Refusal::new(kind, detail, first, message)
}
}
pub fn skip_reason(&self) -> String {
if self.detail.is_empty() {
self.kind.to_string()
} else {
skip_reason::detailed(self.kind, &self.detail)
}
}
pub fn compile_error(&self, cfgs: &[Attribute]) -> TokenStream2 {
let mut bang = Punct::new('!', Spacing::Alone);
bang.set_span(self.span);
let mut message = Literal::string(&self.message);
message.set_span(self.end);
let mut args = Group::new(Delimiter::Parenthesis, TokenTree::from(message).into());
args.set_span(self.end);
let mut semi = Punct::new(';', Spacing::Alone);
semi.set_span(self.end);
let error: TokenStream2 = [
TokenTree::from(Ident::new("compile_error", self.span)),
bang.into(),
args.into(),
semi.into(),
]
.into_iter()
.collect();
if cfgs.is_empty() {
error
} else {
quote! { #(#cfgs)* #error }
}
}
}
fn generic_param_list(generics: &syn::Generics) -> Vec<String> {
generics
.params
.iter()
.filter_map(|p| match p {
syn::GenericParam::Type(t) => Some(format!("`{}`", t.ident)),
syn::GenericParam::Const(c) => Some(format!("`const {}`", c.ident)),
syn::GenericParam::Lifetime(_) => None,
})
.collect()
}
fn generic_param_detail(generics: &syn::Generics) -> String {
generic_param_list(generics)
.iter()
.map(|p| p.trim_matches('`').to_string())
.collect::<Vec<_>>()
.join(", ")
}
fn crate_generic_refusal(generics: &syn::Generics, what: &str, name: &Ident) -> Option<Refusal> {
let params = generic_param_list(generics);
if params.is_empty() {
return None;
}
let msg = format!(
"#[julia] {what} `{name}` is generic over {}: an `extern \"C\"` entry point needs \
concrete types, and #[julia] cannot know which instantiations Julia will call. \
Write a non-generic `#[julia]` item that uses it, or define it in a `rust\"\"\"` block, where \
RustCall monomorphizes generics on demand.",
params.join(", ")
);
Some(Refusal::over(
skip_reason::GENERIC_SIGNATURE,
generic_param_detail(generics),
generics,
msg,
))
}
fn crate_signature_refusal(sig: &syn::Signature, what: &str) -> Option<Refusal> {
if let Some(refusal) = crate_generic_refusal(&sig.generics, what, &sig.ident) {
return Some(refusal);
}
if crate::types::has_impl_trait(sig) {
let msg = format!(
"#[julia] {what} `{}` uses `impl Trait` in its signature, which makes it generic: \
an `extern \"C\"` entry point needs concrete types. Name the concrete type instead.",
sig.ident
);
return Some(Refusal::over(skip_reason::IMPL_TRAIT, "", sig, msg));
}
None
}
fn unsafe_function_refusal(func: &ItemFn) -> Option<Refusal> {
let unsafety = func.sig.unsafety.as_ref()?;
Some(Refusal::new(
skip_reason::UNSAFE_FN,
"",
unsafety.span(),
"#[julia] cannot be applied to unsafe functions directly. The function will be made \
extern \"C\" which has its own safety semantics.",
))
}
pub fn payload_is_representable(ty: &Type) -> bool {
crate::types::is_string_type(ty)
|| crate::types::is_str_ref_type(ty)
|| !crate::types::is_non_ffi_type(ty)
}
fn non_ffi_payload_refusal(func: &ItemFn) -> Option<Refusal> {
let ReturnType::Type(_, ty) = &func.sig.output else {
return None;
};
let name = &func.sig.ident;
let refuse = |what: &str, payload: &Type| {
let spelled = type_to_string(payload);
Refusal::over(
skip_reason::NON_FFI_PAYLOAD,
spelled.clone(),
payload,
format!(
"#[julia] function `{name}` returns {what} type `{spelled}`. Use a primitive or \
#[repr(C)] type instead."
),
)
};
if let Some(r) = extract_result_type(ty) {
if !payload_is_representable(&r.ok_type) {
return Some(refuse("Result with non-FFI-compatible Ok", &r.ok_type));
}
if !payload_is_representable(&r.err_type) {
return Some(refuse("Result with non-FFI-compatible Err", &r.err_type));
}
}
if let Some(o) = extract_option_type(ty) {
if !payload_is_representable(&o.inner_type) {
return Some(refuse("Option with non-FFI-compatible", &o.inner_type));
}
}
None
}
fn inline_generic_function_refusal(func: &ItemFn) -> Option<Refusal> {
let name = &func.sig.ident;
if crate::types::has_impl_trait(&func.sig) {
return Some(Refusal::over(
skip_reason::IMPL_TRAIT,
"",
&func.sig,
format!(
"#[julia] function `{name}` uses `impl Trait` in its signature; `impl Trait` is \
not supported by RustCall"
),
));
}
let consts = crate::types::const_param_names(&func.sig.generics);
if consts.is_empty() {
return None;
}
Some(Refusal::over(
skip_reason::GENERIC_SIGNATURE,
consts
.iter()
.map(|c| format!("const {c}"))
.collect::<Vec<_>>()
.join(", "),
&func.sig.generics,
format!(
"#[julia] function `{name}` has const generic parameter(s) {}; const generics are \
not supported by RustCall",
consts.join(", ")
),
))
}
fn function_is_generic(func: &ItemFn) -> bool {
crate::types::has_type_params(&func.sig.generics) || crate::types::has_impl_trait(&func.sig)
}
pub fn function_refusal(func: &ItemFn, module_path: &[String], mode: Mode) -> Option<Refusal> {
if let Some(refusal) = unsafe_function_refusal(func) {
return Some(refusal);
}
let type_generic = crate::types::has_type_params(&func.sig.generics);
if mode == Mode::Crate || !type_generic {
if let Some(refusal) = non_ffi_payload_refusal(func) {
return Some(refusal);
}
}
let generic = match mode {
Mode::Crate => crate_signature_refusal(&func.sig, "function"),
Mode::Inline => inline_generic_function_refusal(func),
};
if generic.is_some() {
return generic;
}
if function_is_generic(func) {
return None;
}
crate::codegen::free_function_wrapper_refusal(func, module_path)
}
#[derive(Debug, Clone, Copy)]
pub enum MethodSite<'a> {
Crate { self_ty: &'a Type },
Inline {
self_ty: &'a Type,
struct_name: &'a Ident,
},
InlineGeneric { struct_name: &'a Ident },
}
fn method_is_generic(m: &MethodModel) -> bool {
crate::types::has_type_params(&m.func.sig.generics) || crate::types::has_impl_trait(&m.func.sig)
}
fn inline_generic_method_refusal(
struct_name: &Ident,
struct_is_generic: bool,
m: &MethodModel,
) -> Option<Refusal> {
if !method_is_generic(m) {
return None;
}
let sig = &m.func.sig;
let method = &sig.ident;
let params = generic_param_list(&sig.generics);
let (kind, detail, what, span) = if params.is_empty() {
(
skip_reason::IMPL_TRAIT,
String::new(),
"uses `impl Trait` in its signature".to_string(),
sig.span(),
)
} else {
(
skip_reason::GENERIC_SIGNATURE,
generic_param_detail(&sig.generics),
format!("is generic over {}", params.join(", ")),
sig.generics.span(),
)
};
let msg = if struct_is_generic {
format!(
"`{struct_name}::{method}` {what}: a generic `#[julia]` struct in a `rust\"\"\"` \
block has its methods instantiated per struct type, which binds the struct's own \
type parameters and no parameter only the method has. Make it a generic free \
function, which RustCall instantiates for the argument types of each call, write \
one method per type Julia calls using only the struct's parameters (it may \
delegate to the generic one), or drop `pub` if Julia does not call it (#477)."
)
} else {
format!(
"`{struct_name}::{method}` {what}: every `pub fn` of a `#[julia]` struct in a \
`rust\"\"\"` block gets an `extern \"C\"` entry point, which needs concrete types, and \
RustCall monomorphizes on demand only generic free functions and generic structs. \
Make it a generic free function, which RustCall instantiates for the argument types \
of each call, write one non-generic method per type Julia calls (it may delegate to \
the generic one), or drop `pub` if Julia does not call it (#471)."
)
};
Some(Refusal::new(kind, detail, span, msg))
}
fn unsafe_method_refusal(struct_name: &Ident, m: &MethodModel) -> Option<Refusal> {
let unsafety = m.func.sig.unsafety.as_ref()?;
let method = &m.func.sig.ident;
Some(Refusal::new(
skip_reason::UNSAFE_FN,
"",
unsafety.span(),
format!(
"`{struct_name}::{method}` is an `unsafe fn`: its `extern \"C\"` entry point would let \
Julia call it with none of the requirements its `unsafe` states upheld. Expose a \
safe method that upholds them and calls this one, and let Julia call that instead \
(#491)."
),
))
}
fn trait_receiver_refusal(struct_name: &Ident, m: &MethodModel) -> Option<Refusal> {
m.host.as_ref()?.trait_.as_ref()?;
let receiver = m.func.sig.receiver()?;
let method = &m.func.sig.ident;
let spelled = type_to_string(&receiver.ty);
match crate::codegen::TraitReceiver::of(Some(receiver)) {
Err(_) => Some(Refusal::over(
skip_reason::TRAIT_RECEIVER,
spelled,
&receiver.ty,
format!(
"`{struct_name}::{method}`: the wrapper calls this trait method through the \
trait, which passes the receiver exactly as declared, and this receiver type \
does not show its shape. Write it as `self`, `&self`, `&mut self` or reference \
layers over `Self` (`self: &&Self`) — not a type alias, a smart pointer or the \
type's own name — or expose an inherent method that calls this one (#509)."
),
)),
Ok(_)
if receiver.reference.is_none()
&& !m.is_mutable
&& matches!(
crate::types::unparen(&receiver.ty),
Type::Reference(r) if r.mutability.is_some()
) =>
{
Some(Refusal::over(
skip_reason::TRAIT_RECEIVER,
spelled,
&receiver.ty,
format!(
"`{struct_name}::{method}`: a `self: &mut Self` receiver is not yet wrapped \
(#509). Write it as `&mut self`."
),
))
}
Ok(_) => None,
}
}
pub fn method_refusal(site: MethodSite<'_>, m: &MethodModel) -> Option<Refusal> {
match site {
MethodSite::Crate { self_ty } => {
if let Some(host) = &m.host {
if let Some(refusal) = generic_block_refusal(host) {
return Some(refusal);
}
}
if let Some(refusal) = crate_signature_refusal(&m.func.sig, "method") {
return Some(refusal);
}
let struct_name = crate::types::last_ident(self_ty)?;
if let Some(refusal) = unsafe_method_refusal(struct_name, m)
.or_else(|| trait_receiver_refusal(struct_name, m))
{
return Some(refusal);
}
crate::codegen::method_wrapper_refusal(self_ty, struct_name, m)
}
MethodSite::Inline {
self_ty,
struct_name,
} => {
if let Some(refusal) = inline_generic_method_refusal(struct_name, false, m)
.or_else(|| unsafe_method_refusal(struct_name, m))
.or_else(|| trait_receiver_refusal(struct_name, m))
{
return Some(refusal);
}
crate::codegen::method_wrapper_refusal(self_ty, struct_name, m)
}
MethodSite::InlineGeneric { struct_name } => {
inline_generic_method_refusal(struct_name, true, m)
.or_else(|| unsafe_method_refusal(struct_name, m))
}
}
}
pub fn struct_refusal(item: &ItemStruct, mode: Mode) -> Option<Refusal> {
match mode {
Mode::Crate => crate_generic_refusal(&item.generics, "struct", &item.ident),
Mode::Inline => None,
}
}
fn generic_block_refusal(host: &ImplHost) -> Option<Refusal> {
if !crate::types::has_type_params(&host.generics) {
return None;
}
let name = crate::types::last_ident(&host.self_ty)?;
crate_generic_refusal(&host.generics, "impl block for", name)
}
pub fn impl_refusal(item: &ItemImpl) -> Option<Refusal> {
impl_header_refusal(&item.self_ty).or_else(|| generic_block_refusal(&ImplHost::of(item)))
}
pub fn impl_header_refusal(self_ty: &Type) -> Option<Refusal> {
if crate::types::last_ident(self_ty).is_some() {
return None;
}
Some(Refusal::over(
IMPL_NOT_A_PATH,
"",
self_ty,
"#[julia] on impl block requires a simple type path",
))
}
pub fn module_refusal(item: &ItemMod) -> Option<Refusal> {
if item.content.is_some() {
return None;
}
Some(Refusal::over(
FILE_MODULE,
item.ident.to_string(),
item,
"#[julia] on a file module (`mod name;`) is not supported: attribute macros cannot \
expand a non-inline module. Write the module inline (`#[julia] pub mod name { ... }`) \
to give its items a module-qualified symbol.",
))
}
const UNSUPPORTED_ITEM_MESSAGE: &str =
"#[julia] can only be applied to functions, structs, impl blocks, or inline modules";
pub fn unsupported_item_kind(item: &Item) -> Option<String> {
let named = |what: &str, ident: &Ident| format!("{what} `{ident}`");
Some(match item {
Item::Fn(_) | Item::Struct(_) | Item::Impl(_) | Item::Mod(_) => return None,
Item::Const(i) => named("const", &i.ident),
Item::Enum(i) => named("enum", &i.ident),
Item::ExternCrate(i) => named("extern crate", &i.ident),
Item::ForeignMod(_) => "an `extern` block".to_string(),
Item::Macro(i) => match &i.ident {
Some(ident) => named("macro_rules!", ident),
None => "a macro invocation".to_string(),
},
Item::Static(i) => named("static", &i.ident),
Item::Trait(i) => named("trait", &i.ident),
Item::TraitAlias(i) => named("trait alias", &i.ident),
Item::Type(i) => named("type alias", &i.ident),
Item::Union(i) => named("union", &i.ident),
Item::Use(_) => "a `use` declaration".to_string(),
Item::Verbatim(_) => "an item".to_string(),
_ => "an item".to_string(),
})
}
pub fn item_attrs(item: &Item) -> Vec<Attribute> {
match item {
Item::Const(i) => i.attrs.clone(),
Item::Enum(i) => i.attrs.clone(),
Item::ExternCrate(i) => i.attrs.clone(),
Item::Fn(i) => i.attrs.clone(),
Item::ForeignMod(i) => i.attrs.clone(),
Item::Impl(i) => i.attrs.clone(),
Item::Macro(i) => i.attrs.clone(),
Item::Mod(i) => i.attrs.clone(),
Item::Static(i) => i.attrs.clone(),
Item::Struct(i) => i.attrs.clone(),
Item::Trait(i) => i.attrs.clone(),
Item::TraitAlias(i) => i.attrs.clone(),
Item::Type(i) => i.attrs.clone(),
Item::Union(i) => i.attrs.clone(),
Item::Use(i) => i.attrs.clone(),
Item::Verbatim(tokens) => leading_attrs(tokens.clone()),
_ => leading_attrs(item.to_token_stream()),
}
}
fn leading_attrs(tokens: TokenStream2) -> Vec<Attribute> {
struct Leading(Vec<Attribute>);
impl syn::parse::Parse for Leading {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let attrs = input.call(Attribute::parse_outer)?;
input.parse::<TokenStream2>()?;
Ok(Leading(attrs))
}
}
syn::parse2::<Leading>(tokens)
.map(|l| l.0)
.unwrap_or_default()
}
pub fn item_kind_refusal(item: &Item) -> Option<Refusal> {
let what = unsupported_item_kind(item)?;
Some(Refusal::over(
UNSUPPORTED_ITEM,
what,
item,
UNSUPPORTED_ITEM_MESSAGE,
))
}
pub fn julia_item_refusal(item: &Item) -> Option<Refusal> {
if !item_attrs(item).iter().any(crate::attrs::is_julia_attr) {
return None;
}
item_kind_refusal(item)
}
pub fn without_julia_attr(mut item: Item) -> Item {
let strip = |attrs: &mut Vec<Attribute>| attrs.retain(|a| !crate::attrs::is_julia_attr(a));
match &mut item {
Item::Const(i) => strip(&mut i.attrs),
Item::Enum(i) => strip(&mut i.attrs),
Item::ExternCrate(i) => strip(&mut i.attrs),
Item::Fn(i) => strip(&mut i.attrs),
Item::ForeignMod(i) => strip(&mut i.attrs),
Item::Impl(i) => strip(&mut i.attrs),
Item::Macro(i) => strip(&mut i.attrs),
Item::Mod(i) => strip(&mut i.attrs),
Item::Static(i) => strip(&mut i.attrs),
Item::Struct(i) => strip(&mut i.attrs),
Item::Trait(i) => strip(&mut i.attrs),
Item::TraitAlias(i) => strip(&mut i.attrs),
Item::Type(i) => strip(&mut i.attrs),
Item::Union(i) => strip(&mut i.attrs),
Item::Use(i) => strip(&mut i.attrs),
_ => {}
}
item
}
pub fn attribute_target_refusal(tokens: &TokenStream2) -> Refusal {
syn::parse2::<Item>(tokens.clone())
.ok()
.and_then(|item| item_kind_refusal(&item))
.unwrap_or_else(|| Refusal::over(UNSUPPORTED_ITEM, "", tokens, UNSUPPORTED_ITEM_MESSAGE))
}