use syn::spanned::Spanned;
use syn::{FnArg, Item, ItemFn, ItemImpl, Pat, ReturnType};
use crate::attrs::{has_no_mangle, rustcall_attribute};
use crate::cfg::{body_has_cfg, predicate_string, CfgSet};
use crate::codegen::symbol_stem;
use crate::manifest::{
Arg, Attribute, Field, Function, Manifest, Method, Mode, ReturnKind, Struct,
};
use crate::model::{impl_has_julia, wrapped_methods, StructModel};
use crate::paths::{imports_of_use, locate, ImplHeader, Located, ScannedImport, Unresolved};
use crate::types::{
callback_signature, extract_option_type, extract_result_type, field_has_accessors,
generics_to_type_params, has_impl_trait, has_type_params, is_str_ref_type, is_string_type,
return_type_to_string, type_to_string,
};
pub fn extract(source: &str, mode: Mode) -> Result<Manifest, ExtractError> {
extract_with_cfg(source, mode, None)
}
pub fn extract_with_cfg(
source: &str,
mode: Mode,
cfg: Option<&CfgSet>,
) -> Result<Manifest, ExtractError> {
match mode {
Mode::Inline => Ok(crate::expand::expand_with_cfg(source, cfg)?.manifest),
Mode::Crate => extract_crate_with_cfg(source, cfg),
}
}
pub fn fn_args(sig: &syn::Signature) -> Vec<Arg> {
sig.inputs
.iter()
.filter_map(|a| match a {
FnArg::Typed(pt) => Some(typed_arg(pt)),
FnArg::Receiver(_) => None,
})
.collect()
}
pub fn typed_arg(pt: &syn::PatType) -> Arg {
let (callback_args, callback_return) = match callback_signature(&pt.ty) {
Some((inputs, output)) => (
inputs.iter().map(type_to_string).collect(),
output.as_ref().map(type_to_string).unwrap_or_default(),
),
None => (Vec::new(), String::new()),
};
Arg {
name: match pt.pat.as_ref() {
Pat::Ident(pi) => pi.ident.to_string(),
other => quote::quote!(#other).to_string(),
},
rust_type: type_to_string(&pt.ty),
abi: arg_abi(&pt.ty).to_string(),
handle: String::new(),
callback_args,
callback_return,
python_default: String::new(),
python_kind: String::new(),
py_shape: None,
}
}
pub fn plain_return_kind(output: &ReturnType) -> ReturnKind {
match output {
ReturnType::Default => ReturnKind::Unit,
ReturnType::Type(..) => {
if return_type_to_string(output) == "()" {
ReturnKind::Unit
} else {
ReturnKind::Plain
}
}
}
}
#[derive(Debug, Default, Clone)]
pub struct MethodReturnShape {
pub kind: ReturnKind,
pub ok_type: String,
pub err_type: String,
pub inner_type: String,
pub ok_abi: String,
pub err_abi: String,
pub inner_abi: String,
}
pub fn method_return_shape(
struct_name: &syn::Ident,
m: &crate::model::MethodModel,
wrapped: bool,
) -> MethodReturnShape {
let output = &m.func.sig.output;
let mut shape = MethodReturnShape {
kind: plain_return_kind(output),
..Default::default()
};
if wrapped {
if let Some(result) = m.boxed_self_result(struct_name) {
shape.kind = ReturnKind::Result;
shape.ok_type = type_to_string(&result.ok_type);
shape.err_type = type_to_string(&result.err_type);
shape.ok_abi = "boxed".into();
shape.err_abi = crate::codegen::payload_abi(&result.err_type).into();
return shape;
}
}
if !wrapped || m.returns_boxed_struct(struct_name) {
return shape;
}
let ReturnType::Type(_, ty) = output else {
return shape;
};
if crate::codegen::method_wraps_result(ty) {
if let Some(r) = extract_result_type(ty) {
shape.kind = ReturnKind::Result;
shape.ok_type = type_to_string(&r.ok_type);
shape.err_type = type_to_string(&r.err_type);
shape.ok_abi = crate::codegen::payload_abi(&r.ok_type).to_string();
shape.err_abi = crate::codegen::payload_abi(&r.err_type).to_string();
}
} else if crate::codegen::method_wraps_option(ty) {
if let Some(o) = extract_option_type(ty) {
shape.kind = ReturnKind::Option;
shape.inner_type = type_to_string(&o.inner_type);
shape.inner_abi = crate::codegen::payload_abi(&o.inner_type).to_string();
}
}
shape
}
pub fn arg_abi(ty: &syn::Type) -> &'static str {
if is_string_type(ty) {
"string"
} else if is_str_ref_type(ty) {
"str"
} else if callback_signature(ty).is_some() {
"callback"
} else {
""
}
}
pub fn borrowed_struct_arg(ty: &syn::Type) -> Option<(bool, &syn::Type)> {
if !arg_abi(ty).is_empty() {
return None;
}
let syn::Type::Reference(r) = crate::types::unparen(ty) else {
return None;
};
matches!(crate::types::unparen(&r.elem), syn::Type::Path(_))
.then_some((r.mutability.is_some(), &*r.elem))
}
pub fn is_self_type(ty: &syn::Type) -> bool {
matches!(crate::types::unparen(ty), syn::Type::Path(p)
if p.qself.is_none() && p.path.leading_colon.is_none()
&& p.path.segments.len() == 1
&& p.path.segments[0].ident == "Self"
&& p.path.segments[0].arguments.is_none())
}
pub fn mark_handle_arg(arg: &mut Arg, mutable: bool, ffi_name: &str) {
arg.abi = if mutable { "handle_mut" } else { "handle" }.to_string();
arg.handle = ffi_name.to_string();
}
pub fn borrow_is_call_scoped(ty: &syn::Type, sig: &syn::Signature) -> bool {
let syn::Type::Reference(r) = crate::types::unparen(ty) else {
return false;
};
let Some(lifetime) = &r.lifetime else {
return true;
};
let name = lifetime.ident.to_string();
if name == "_" {
return true;
}
if name == "static" {
return false;
}
let declared_unbounded = sig.generics.params.iter().any(|p| {
matches!(p, syn::GenericParam::Lifetime(lp)
if lp.lifetime.ident == lifetime.ident && lp.bounds.is_empty())
});
if !declared_unbounded {
return false;
}
let where_clause = &sig.generics.where_clause;
let output = &sig.output;
!names_lifetime(quote::quote!(#where_clause), &name)
&& !names_lifetime(quote::quote!(#output), &name)
}
fn names_lifetime(tokens: proc_macro2::TokenStream, name: &str) -> bool {
let mut previous_tick = false;
for tree in tokens {
match tree {
proc_macro2::TokenTree::Punct(p) => {
previous_tick = p.as_char() == '\'';
continue;
}
proc_macro2::TokenTree::Ident(i) if previous_tick && i == name => return true,
proc_macro2::TokenTree::Group(g) if names_lifetime(g.stream(), name) => return true,
_ => {}
}
previous_tick = false;
}
false
}
pub fn mark_handle_args(
args: &mut [Arg],
sig: &syn::Signature,
mut resolve: impl FnMut(&syn::Type) -> Option<String>,
) {
let typed = sig.inputs.iter().filter_map(|a| match a {
FnArg::Typed(pt) => Some(&*pt.ty),
FnArg::Receiver(_) => None,
});
for (arg, ty) in args.iter_mut().zip(typed) {
if !borrow_is_call_scoped(ty, sig) {
continue;
}
if let Some((mutable, pointee)) = borrowed_struct_arg(ty) {
if let Some(ffi_name) = resolve(pointee) {
mark_handle_arg(arg, mutable, &ffi_name);
}
}
}
}
fn item_fn_source(func: &ItemFn) -> String {
let file = syn::File {
shebang: None,
attrs: Vec::new(),
items: vec![Item::Fn(func.clone())],
};
prettyplease::unparse(&file)
}
pub fn function_entry(
func: &ItemFn,
attribute: Attribute,
mode: Mode,
module_path: &[String],
enclosing_cfg: &[syn::Attribute],
) -> Function {
let effective_cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &func.attrs);
let is_generic = has_type_params(&func.sig.generics) || has_impl_trait(&func.sig);
let refusal = (attribute == Attribute::Julia)
.then(|| crate::refusal::function_refusal(func, module_path, mode))
.flatten();
let wrapped = attribute == Attribute::Julia && (mode == Mode::Crate || !is_generic);
let return_type = return_type_to_string(&func.sig.output);
let mut ok_type = String::new();
let mut err_type = String::new();
let mut inner_type = String::new();
let mut ok_abi = String::new();
let mut err_abi = String::new();
let mut inner_abi = String::new();
let return_kind = match &func.sig.output {
ReturnType::Default => ReturnKind::Unit,
ReturnType::Type(_, ty) => {
if let (true, Some(r)) = (wrapped, extract_result_type(ty)) {
ok_type = type_to_string(&r.ok_type);
err_type = type_to_string(&r.err_type);
ok_abi = crate::codegen::payload_abi(&r.ok_type).to_string();
err_abi = crate::codegen::payload_abi(&r.err_type).to_string();
ReturnKind::Result
} else if let (true, Some(o)) = (wrapped, extract_option_type(ty)) {
inner_type = type_to_string(&o.inner_type);
inner_abi = crate::codegen::payload_abi(&o.inner_type).to_string();
ReturnKind::Option
} else if return_type == "()" {
ReturnKind::Unit
} else {
ReturnKind::Plain
}
}
};
let exported = if is_generic || refusal.is_some() {
false
} else if wrapped {
true
} else {
has_no_mangle(&func.attrs)
&& func
.sig
.abi
.as_ref()
.and_then(|abi| abi.name.as_ref())
.map(|n| n.value() == "C")
.unwrap_or(false)
};
let name = func.sig.ident.to_string();
let ffi_name = crate::codegen::symbol_stem(module_path, &name);
let symbol = match attribute {
Attribute::Julia if !is_generic => crate::codegen::function_symbol(module_path, &name),
_ => crate::codegen::unraw(&name).to_string(),
};
let return_abi = if wrapped && !is_generic {
crate::codegen::return_abi(&func.sig)
} else {
""
};
Function {
callable_path: Vec::new(),
name,
ffi_name,
symbol,
attribute,
vis: crate::attrs::visibility_string(&func.vis),
skip_reason: refusal.map(|r| r.skip_reason()).unwrap_or_default(),
python_name: String::new(),
python_path: Vec::new(),
exported,
cfg: predicate_string(&effective_cfg),
cfg_features: crate::cfg::predicate_features(&effective_cfg),
is_generic,
type_params: generics_to_type_params(&func.sig.generics),
args: fn_args(&func.sig),
return_type,
return_kind,
return_abi: return_abi.to_string(),
ok_type,
err_type,
inner_type,
ok_abi,
err_abi,
inner_abi,
has_owned_string_helper: return_abi == "string",
has_borrowed_string_helper: return_abi == "str",
source: if is_generic {
let mut stripped = func.clone();
crate::attrs::strip_rustcall_attrs(&mut stripped.attrs);
item_fn_source(&stripped)
} else {
String::new()
},
body_has_cfg: body_has_cfg(&func.block),
line: func.span().start().line,
module_path: module_path.to_vec(),
py_return: None,
}
}
#[derive(Debug)]
pub enum ExtractError {
Parse(syn::Error),
Unsupported(String),
}
impl std::fmt::Display for ExtractError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ExtractError::Parse(e) => write!(f, "{e}"),
ExtractError::Unsupported(msg) => f.write_str(msg),
}
}
}
impl std::error::Error for ExtractError {}
impl From<syn::Error> for ExtractError {
fn from(e: syn::Error) -> Self {
ExtractError::Parse(e)
}
}
pub fn extract_crate(source: &str) -> Result<Manifest, ExtractError> {
extract_crate_with_cfg(source, None)
}
pub fn extract_crate_with_cfg(
source: &str,
cfg: Option<&CfgSet>,
) -> Result<Manifest, ExtractError> {
extract_crate_with_cfg_scan(source, cfg, true)
}
pub fn extract_crate_with_cfg_scan(
source: &str,
cfg: Option<&CfgSet>,
pyo3_scan: bool,
) -> Result<Manifest, ExtractError> {
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::Crate);
let mut scan = CrateScan::new();
scan.file(
&file.items,
&FilePosition::module(&[], true, &[]),
&mut manifest,
"",
)?;
scan.finish(&mut manifest)?;
if pyo3_scan {
crate::pyo3::extract_pyo3_items(&file.items, &mut manifest);
}
Ok(manifest)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingInclude {
pub path: String,
pub position: FilePosition,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FilePosition {
pub module_path: Vec<String>,
pub reachable: bool,
pub enclosing_cfg: Vec<syn::Attribute>,
pub symbol_path: Vec<String>,
pub marked: bool,
}
impl FilePosition {
pub fn module(
module_path: &[String],
reachable: bool,
enclosing_cfg: &[syn::Attribute],
) -> Self {
FilePosition {
module_path: module_path.to_vec(),
reachable,
enclosing_cfg: enclosing_cfg.to_vec(),
symbol_path: Vec::new(),
marked: true,
}
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct PullIns {
pub modules: Vec<crate::pyo3::PendingModule>,
pub includes: Vec<PendingInclude>,
}
#[derive(Debug, Default)]
pub struct TreeScan {
julia: CrateScan,
pyo3: crate::pyo3::Pyo3Scan,
}
impl TreeScan {
pub fn new() -> Self {
TreeScan::default()
}
pub fn with_edition(edition: &str) -> Self {
Self {
julia: CrateScan {
edition_2015: edition == "2015",
..CrateScan::default()
},
pyo3: crate::pyo3::Pyo3Scan::with_edition(edition),
}
}
pub fn with_include_environment(environment: crate::include_paths::IncludeEnvironment) -> Self {
Self {
julia: CrateScan {
include_environment: Some(environment),
..CrateScan::default()
},
pyo3: crate::pyo3::Pyo3Scan::default(),
}
}
pub fn with_include_environment_and_edition(
environment: crate::include_paths::IncludeEnvironment,
edition: &str,
) -> Self {
Self {
julia: CrateScan {
include_environment: Some(environment),
edition_2015: edition == "2015",
..CrateScan::default()
},
pyo3: crate::pyo3::Pyo3Scan::with_edition(edition),
}
}
pub fn file(
&mut self,
source: &str,
cfg: Option<&CfgSet>,
position: &FilePosition,
manifest: &mut Manifest,
file: &str,
) -> Result<PullIns, ExtractError> {
let mut parsed = syn::parse_file(source)?;
if let Some(set) = cfg {
crate::cfg::prune_file_or_error(set, &mut parsed)?;
}
let includes = self.julia.file(&parsed.items, position, manifest, file)?;
let modules = self.pyo3.file(
&parsed.items,
&position.module_path,
position.reachable,
&position.enclosing_cfg,
manifest,
);
Ok(PullIns { modules, includes })
}
pub fn finish(self, manifest: &mut Manifest) -> Result<(), ExtractError> {
self.julia.finish(manifest)?;
self.pyo3.finish(manifest);
Ok(())
}
}
fn unmarked_module_error(kind: &str, name: &str, full_path: &[String]) -> ExtractError {
let module = full_path.last().map(String::as_str).unwrap_or("");
ExtractError::Unsupported(format!(
"#[julia] {kind} `{name}` sits in the inline module `{}`, which is not marked \
`#[julia]`. The proc-macro cannot see the module an item is in, so it would \
export `{name}` under the crate-root symbol; mark the module — `#[julia] pub mod \
{module} {{ ... }}` — so the items inside it get module-qualified symbols (#300).",
full_path.join("::")
))
}
fn refused_container(
refusal: crate::refusal::Refusal,
what: &str,
module_path: &[String],
) -> ExtractError {
ExtractError::Unsupported(format!(
"{} ({what} in `{}`)",
refusal.message,
crate_path(module_path)
))
}
fn crate_path(path: &[String]) -> String {
if path.is_empty() {
"crate".to_string()
} else {
format!("crate::{}", path.join("::"))
}
}
fn plain_target_error(imp: &ScannedImpl, target: &Candidate) -> ExtractError {
let header = imp.header.display();
let where_ = location(imp.line, &imp.file);
let name = &target.name;
let module = if target.module_path.is_empty() {
"the crate root".to_string()
} else {
format!("module `{}`", target.module_path.join("::"))
};
let declared = if target.file.is_empty() {
String::new()
} else {
format!(" (in {})", target.file)
};
ExtractError::Unsupported(format!(
"`{header}` {where_} names `{name}` in {module}{declared}, which is not a \
`#[julia]` struct. Mark that struct with `#[julia]`, or point the block at the \
annotated one with an explicit path (`impl crate::path::to::{name}`)."
))
}
fn alias_target_error(imp: &ScannedImpl, target: &Candidate) -> ExtractError {
let header = imp.header.display();
let where_ = location(imp.line, &imp.file);
let name = &target.name;
let module = if target.module_path.is_empty() {
"the crate root".to_string()
} else {
format!("module `{}`", target.module_path.join("::"))
};
ExtractError::Unsupported(format!(
"#[julia] trait impl `{header}` {where_} names `{name}`, a `type` alias in {module}. \
The proc macro exports its methods under the alias's name, and the scan cannot \
tell which struct the alias names, so they could not be bound. Write the \
`#[julia]` struct's own name in the impl header, or remove `#[julia]` from the \
block (#506)."
))
}
fn location(line: usize, file: &str) -> String {
if file.is_empty() {
format!("(line {line})")
} else {
format!("(line {line} in {file})")
}
}
#[derive(Debug, Default)]
pub struct CrateScan {
include_environment: Option<crate::include_paths::IncludeEnvironment>,
structs: Vec<ScannedStruct>,
plain_structs: Vec<PlainStruct>,
impls: Vec<ScannedImpl>,
imports: Vec<ScannedImport>,
claimed: Vec<(crate::claims::Claim, String)>,
handle_fns: Vec<PendingHandleFn>,
edition_2015: bool,
}
#[derive(Debug)]
struct PendingHandleFn {
index: usize,
module_path: Vec<String>,
sig: syn::Signature,
}
#[derive(Debug)]
struct ScannedStruct {
model: StructModel,
name: String,
module_path: Vec<String>,
symbol_path: Vec<String>,
cfg: Vec<syn::Attribute>,
file: String,
}
impl Located for ScannedStruct {
fn name(&self) -> &str {
&self.name
}
fn module_path(&self) -> &[String] {
&self.module_path
}
}
#[derive(Debug)]
struct PlainStruct {
name: String,
module_path: Vec<String>,
file: String,
alias: bool,
}
#[derive(Debug)]
struct Candidate {
name: String,
module_path: Vec<String>,
julia: Option<usize>,
file: String,
alias: bool,
}
impl Located for Candidate {
fn name(&self) -> &str {
&self.name
}
fn module_path(&self) -> &[String] {
&self.module_path
}
}
#[derive(Debug)]
struct ScannedImpl {
item: ItemImpl,
header: ImplHeader,
symbol_path: Vec<String>,
cfg: Vec<syn::Attribute>,
enclosing_cfg: Vec<syn::Attribute>,
trait_impl: bool,
line: usize,
file: String,
}
impl CrateScan {
pub fn new() -> Self {
CrateScan::default()
}
pub fn file(
&mut self,
items: &[Item],
position: &FilePosition,
manifest: &mut Manifest,
file: &str,
) -> Result<Vec<PendingInclude>, ExtractError> {
let mut path = position.module_path.clone();
let mut includes = Vec::new();
self.level(
items,
&mut path,
&position.symbol_path,
&position.enclosing_cfg,
position.marked,
position.reachable,
manifest,
file,
&mut includes,
)?;
Ok(includes)
}
#[allow(clippy::too_many_arguments)]
fn level(
&mut self,
items: &[Item],
module_path: &mut Vec<String>,
symbol_path: &[String],
enclosing_cfg: &[syn::Attribute],
marked: bool,
reachable: bool,
manifest: &mut Manifest,
file: &str,
includes: &mut Vec<PendingInclude>,
) -> Result<(), ExtractError> {
for item in items {
if let Some(refusal) = crate::refusal::julia_item_refusal(item) {
let what = refusal.detail.clone();
return Err(refused_container(refusal, &what, module_path));
}
match item {
Item::Fn(f) => {
let attribute = rustcall_attribute(&f.attrs);
if attribute != Attribute::None && !marked {
return Err(unmarked_module_error(
"function",
&f.sig.ident.to_string(),
module_path,
));
}
if attribute == Attribute::Julia {
let entry =
function_entry(f, attribute, Mode::Crate, symbol_path, enclosing_cfg);
for (claim, owner) in entry.claims() {
self.claim(claim, owner, file, module_path)?;
}
manifest.functions.push(entry);
if f.sig.inputs.iter().any(|a| {
matches!(a, FnArg::Typed(pt) if borrowed_struct_arg(&pt.ty).is_some())
}) {
self.handle_fns.push(PendingHandleFn {
index: manifest.functions.len() - 1,
module_path: module_path.clone(),
sig: f.sig.clone(),
});
}
}
}
Item::Enum(e) => {
self.plain_structs.push(PlainStruct {
name: e.ident.to_string(),
module_path: module_path.clone(),
file: file.to_string(),
alias: false,
});
}
Item::Union(u) => {
self.plain_structs.push(PlainStruct {
name: u.ident.to_string(),
module_path: module_path.clone(),
file: file.to_string(),
alias: false,
});
}
Item::Type(t) => {
self.plain_structs.push(PlainStruct {
name: t.ident.to_string(),
module_path: module_path.clone(),
file: file.to_string(),
alias: true,
});
}
Item::Struct(s) => {
let Some(model) = StructModel::of(s, Mode::Crate) else {
self.plain_structs.push(PlainStruct {
name: s.ident.to_string(),
module_path: module_path.clone(),
file: file.to_string(),
alias: false,
});
continue;
};
if !marked {
return Err(unmarked_module_error("struct", &model.name(), module_path));
}
self.structs.push(ScannedStruct {
name: model.name(),
model,
module_path: module_path.clone(),
symbol_path: symbol_path.to_vec(),
cfg: enclosing_cfg.to_vec(),
file: file.to_string(),
});
}
Item::Impl(imp) => {
if !impl_has_julia(imp) {
continue;
}
let Some(header) = ImplHeader::of_any(imp, module_path) else {
if let Some(refusal) = crate::refusal::impl_header_refusal(&imp.self_ty) {
return Err(refused_container(refusal, "an impl block", module_path));
}
continue;
};
self.impls.push(ScannedImpl {
item: imp.clone(),
header,
symbol_path: symbol_path.to_vec(),
cfg: crate::cfg::effective_cfg_attrs(enclosing_cfg, &imp.attrs),
enclosing_cfg: enclosing_cfg.to_vec(),
trait_impl: imp.trait_.is_some(),
line: imp.span().start().line,
file: file.to_string(),
});
}
Item::Use(u) => {
self.imports.extend(imports_of_use(u, module_path));
}
Item::Macro(m) if m.mac.path.is_ident("include") => {
let path = match &self.include_environment {
Some(environment) => environment
.resolve(m.mac.tokens.clone())
.map_err(ExtractError::Unsupported)?,
None => {
let Ok(literal) = m.mac.parse_body::<syn::LitStr>() else {
continue;
};
literal.value()
}
};
includes.push(PendingInclude {
path,
position: FilePosition {
module_path: module_path.clone(),
reachable,
enclosing_cfg: crate::cfg::effective_cfg_attrs(enclosing_cfg, &m.attrs),
symbol_path: symbol_path.to_vec(),
marked,
},
});
}
Item::Mod(m) => {
let inner_reachable = reachable && matches!(m.vis, syn::Visibility::Public(_));
let Some((_, inner)) = &m.content else {
if crate::codegen::is_marked_module(m) {
if let Some(refusal) = crate::refusal::module_refusal(m) {
return Err(refused_container(
refusal,
&format!("module `{}`", m.ident),
module_path,
));
}
}
continue;
};
module_path.push(m.ident.to_string());
let cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &m.attrs);
let result = if crate::codegen::is_marked_module(m) {
let mut inner_symbol = symbol_path.to_vec();
inner_symbol.push(m.ident.to_string());
self.level(
inner,
module_path,
&inner_symbol,
&cfg,
true,
inner_reachable,
manifest,
file,
includes,
)
} else {
self.level(
inner,
module_path,
&[],
&cfg,
false,
inner_reachable,
manifest,
file,
includes,
)
};
module_path.pop();
result?;
}
_ => {}
}
}
Ok(())
}
fn claim(
&mut self,
claim: crate::claims::Claim,
owner: String,
file: &str,
module: &[String],
) -> Result<(), ExtractError> {
let claim = claim.in_real_module(module);
let here = if file.is_empty() {
owner
} else {
format!("{owner} in {file}")
};
let symbol = claim.name.clone();
let symbol = &symbol;
if let Some((_, first)) = self.claimed.iter().find(|(c, _)| c.clashes_with(&claim)) {
let kind = crate::claims::clash_kind(&claim);
let detail = if claim.exported {
"Two #[julia] items of one crate export the same symbol; only inline modules \
marked `#[julia]` (`#[julia] pub mod name { ... }`) qualify a symbol by \
their name, while file modules (`mod name;`) do not. Wrap one of the items in \
a `#[julia]` module block or rename it (#300)."
.to_string()
} else {
format!(
"This name is not exported and not one you wrote: it is {}. Two of them in \
one crate are a duplicate definition rather than a duplicate export, and \
rustc would report it inside generated code. Rename one of the items \
(#338).",
crate::claims::internal_origin(&claim)
)
};
return Err(ExtractError::Unsupported(format!(
"duplicate {kind} `{symbol}`: claimed by {first} and by {here}. {detail}"
)));
}
self.claimed.push((claim, here));
Ok(())
}
pub fn finish(mut self, manifest: &mut Manifest) -> Result<(), ExtractError> {
let candidates: Vec<Candidate> = self
.structs
.iter()
.enumerate()
.map(|(i, s)| Candidate {
name: s.name.clone(),
module_path: s.module_path.clone(),
julia: Some(i),
file: s.file.clone(),
alias: false,
})
.chain(self.plain_structs.iter().map(|p| Candidate {
name: p.name.clone(),
module_path: p.module_path.clone(),
julia: None,
file: p.file.clone(),
alias: p.alias,
}))
.collect();
let mut impls = std::mem::take(&mut self.impls);
impls.sort_by(|a, b| {
a.header
.module_path
.cmp(&b.header.module_path)
.then(a.line.cmp(&b.line))
.then(a.file.cmp(&b.file))
});
for imp in &impls {
if wrapped_methods(&imp.item, Mode::Crate, &imp.cfg).is_empty() {
continue;
}
let index = match locate(&candidates, &imp.header, &self.imports) {
Ok(index) => match candidates[index].julia {
Some(julia) => julia,
None if imp.trait_impl && candidates[index].alias => {
return Err(alias_target_error(imp, &candidates[index]))
}
None if imp.trait_impl => continue,
None => return Err(plain_target_error(imp, &candidates[index])),
},
Err(Unresolved::NotFound) if imp.trait_impl => continue,
Err(why) => return Err(self.unresolved_impl(imp, why)),
};
for index in self.cfg_variants_for(index, &imp.enclosing_cfg) {
self.check_symbol_path(imp, index)?;
self.structs[index].model.attach_impl(
&imp.item,
Mode::Crate,
&imp.cfg,
Some(&imp.header.module_path),
);
}
}
let scanned_structs = std::mem::take(&mut self.structs);
let mut entries: Vec<Struct> = scanned_structs
.iter()
.map(|scanned| crate_struct_entry(&scanned.model, &scanned.symbol_path, &scanned.cfg))
.collect();
let handle_names: Vec<Option<String>> = entries
.iter()
.map(|e| {
(e.type_params.is_empty() && e.skip_reason.is_empty()).then(|| e.ffi_name.clone())
})
.collect();
let edition_2015 = self.edition_2015;
let resolve = |ty: &syn::Type, module: &[String]| -> Option<String> {
let index = crate::paths::locate_borrowed_type(
&candidates,
ty,
module,
&self.imports,
edition_2015,
)?;
handle_names[candidates[index].julia?].clone()
};
for (i, (entry, scanned)) in entries.iter_mut().zip(&scanned_structs).enumerate() {
let own = handle_names[i].clone();
for method in entry.methods.iter_mut() {
let Some(model) = scanned
.model
.methods
.iter()
.find(|m| m.name() == method.name && m.trait_path() == method.trait_path)
else {
continue;
};
let module = model
.site
.as_ref()
.map(|site| site.module_path.clone())
.unwrap_or_else(|| scanned.module_path.clone());
mark_handle_args(&mut method.args, &model.func.sig, |ty| {
if is_self_type(ty) {
own.clone()
} else {
resolve(ty, &module)
}
});
}
}
for pending in std::mem::take(&mut self.handle_fns) {
let function = &mut manifest.functions[pending.index];
mark_handle_args(&mut function.args, &pending.sig, |ty| {
resolve(ty, &pending.module_path)
});
}
for (scanned, entry) in scanned_structs.into_iter().zip(entries) {
for (claim, owner) in entry.claims() {
self.claim(claim, owner, &scanned.file, &scanned.module_path)?;
}
if let Some(clash) = julia_name_clash(&entry) {
return Err(ExtractError::Unsupported(clash));
}
manifest.structs.push(entry);
}
Ok(())
}
fn cfg_variants_for(&self, index: usize, cfg: &[syn::Attribute]) -> Vec<usize> {
let want = predicate_string(cfg);
let here = &self.structs[index];
let same = |s: &ScannedStruct| s.name == here.name && s.module_path == here.module_path;
if predicate_string(&here.cfg) == want {
return vec![index];
}
if let Some(exact) = self
.structs
.iter()
.position(|s| same(s) && predicate_string(&s.cfg) == want)
{
return vec![exact];
}
let overlapping: Vec<usize> = self
.structs
.iter()
.enumerate()
.filter(|(_, s)| {
same(s) && !crate::pyo3::cfg_exclusive(&predicate_string(&s.cfg), &want)
})
.map(|(i, _)| i)
.collect();
if !overlapping.is_empty() {
return overlapping;
}
vec![index]
}
fn unresolved_impl(&self, imp: &ScannedImpl, why: Unresolved) -> ExtractError {
let header = imp.header.display();
let where_ = location(imp.line, &imp.file);
let name = &imp.header.target;
ExtractError::Unsupported(match why {
Unresolved::NotFound => {
let looked = if imp.header.qualifier.is_uninformative() {
"anywhere in the crate".to_string()
} else {
let places: Vec<String> = imp
.header
.qualifier
.candidates(&imp.header.module_path)
.iter()
.map(|p| format!("`{}`", crate_path(p)))
.collect();
if places.is_empty() {
"where the header points (it walks above the crate root)".to_string()
} else {
format!("at {}", places.join(" or "))
}
};
format!(
"#[julia] `{header}` {where_} names no #[julia] struct: no `struct {name}` \
marked `#[julia]` is declared {looked}. A `#[julia] impl` block wraps the \
methods of a `#[julia]` struct, so mark the struct, or point the header at \
one that is (#315)."
)
}
Unresolved::Ambiguous(paths) => {
let places: Vec<String> = paths
.iter()
.map(|p| format!("`{}`", crate_path(p)))
.collect();
let first = paths.first().map(|p| crate_path(p)).unwrap_or_default();
format!(
"#[julia] `{header}` {where_} is ambiguous: `#[julia] struct {name}` is \
declared in {}, and neither the header nor a `use` in `{}` picks one. Write \
the struct's path in the header (`impl {first}::{name}`) (#315).",
places.join(" and "),
crate_path(&imp.header.module_path)
)
}
})
}
fn check_symbol_path(&self, imp: &ScannedImpl, index: usize) -> Result<(), ExtractError> {
let scanned = &self.structs[index];
let name = scanned.model.name();
let macro_path = imp.header.qualifier.macro_target_path(&imp.symbol_path);
let macro_stem = symbol_stem(¯o_path, &imp.header.target.to_string());
let struct_stem = symbol_stem(&scanned.symbol_path, &name);
if macro_stem == struct_stem {
return Ok(());
}
let header = imp.header.display();
let where_ = location(imp.line, &imp.file);
let block_is = if imp.symbol_path.is_empty() {
"outside any `#[julia]` module".to_string()
} else {
format!(
"inside the `#[julia]` module `{}`",
imp.symbol_path.join("::")
)
};
let real = crate_path(&scanned.module_path);
let fix = if scanned.module_path == scanned.symbol_path {
format!("write the header as `impl {real}::{name}`")
} else if scanned.symbol_path.is_empty() {
format!(
"bring the struct into scope (`use {real}::{name};`) and write `impl {name}` \
outside any `#[julia]` module — the modules in `{real}` are file modules or \
unmarked ones, transparent to the symbol scheme (#300), so a header naming \
them would qualify the symbols by them"
)
} else {
format!(
"bring the struct into scope (`use {real}::{name};`) and write `impl {name}` \
inside `#[julia] mod {}` (module path `{}`), or move the block next to the \
struct",
scanned.symbol_path.last().map(String::as_str).unwrap_or(""),
scanned.symbol_path.join("::")
)
};
Err(ExtractError::Unsupported(format!(
"#[julia] `{header}` {where_}, {block_is}, would export its methods as \
`rustcall_{macro_stem}_<method>`, but the struct it names, `{real}::{name}`, has \
the FFI name `{struct_stem}` (`{struct_stem}_free`, \
`rustcall_{struct_stem}_<method>`). The proc-macro derives a method's symbol from \
the impl header and the `#[julia]` modules around the block — it cannot see \
where the struct is declared — so the header has to spell the struct's path: \
{fix} (#315)."
)))
}
}
fn julia_method_names(methods: &mut [Method]) {
use crate::codegen::unraw as bare;
let names: Vec<(String, String)> = methods
.iter()
.map(|m| (m.trait_path.clone(), bare(&m.name).to_string()))
.collect();
for m in methods.iter_mut() {
let name = bare(&m.name).to_string();
let shared = !m.trait_path.is_empty()
&& names
.iter()
.any(|(trait_path, other)| *other == name && *trait_path != m.trait_path);
if shared {
let trait_name = syn::parse_str::<syn::Path>(&m.trait_path)
.ok()
.and_then(|path| crate::codegen::trait_name_of(&path))
.unwrap_or_default();
m.julia_name = format!("{trait_name}_{name}");
} else if name != m.name {
m.julia_name = name;
}
}
}
fn julia_name_clash(entry: &Struct) -> Option<String> {
let bound: Vec<&Method> = entry
.methods
.iter()
.filter(|m| {
!m.is_constructor && !crate::manifest::skip_reason::is_codegen_refusal(&m.skip_reason)
})
.collect();
let describe = |m: &Method| {
if m.trait_path.is_empty() {
format!("`{}::{}`", entry.name, m.name)
} else {
format!("`<{} as {}>::{}`", entry.name, m.trait_path, m.name)
}
};
for (i, a) in bound.iter().enumerate() {
for b in &bound[i + 1..] {
if a.julia_name() == b.julia_name() && !crate::pyo3::cfg_exclusive(&a.cfg, &b.cfg) {
return Some(format!(
"#[julia] {} and {} of struct `{}` would both be bound in Julia as `{}`. \
A trait impl's method that shares its name with another method of the \
struct is bound as `<Trait>_<method>`; rename one of the methods, or \
remove `#[julia]` from one of them (#506).",
describe(a),
describe(b),
entry.name,
a.julia_name()
));
}
}
}
None
}
fn crate_struct_entry(
model: &StructModel,
module_path: &[String],
enclosing_cfg: &[syn::Attribute],
) -> Struct {
let struct_name = &model.item.ident;
let effective_cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &model.item.attrs);
let stem = crate::codegen::symbol_stem(module_path, &struct_name.to_string());
let refusal = crate::refusal::struct_refusal(&model.item, Mode::Crate);
let fields = model
.named_fields()
.iter()
.map(|(name, ty)| {
let ffi_compatible = refusal.is_none() && field_has_accessors(ty);
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,
getter: if ffi_compatible {
crate::codegen::field_getter_symbol(&stem, &name.to_string())
} else {
String::new()
},
setter: if ffi_compatible {
crate::codegen::field_setter_symbol(&stem, &name.to_string())
} else {
String::new()
},
python_name: String::new(),
vis: String::new(),
cfg: String::new(),
pyo3_get: false,
pyo3_set: false,
precollision: None,
py_shape: None,
}
})
.collect();
let shapes: Vec<MethodReturnShape> = model
.methods
.iter()
.map(|m| method_return_shape(struct_name, m, true))
.collect();
let bare: syn::Type = syn::parse_quote!(#struct_name);
let methods = model
.methods
.iter()
.enumerate()
.map(|(i, m)| Method {
skip_reason: crate::refusal::method_refusal(
crate::refusal::MethodSite::Crate {
self_ty: m.site.as_ref().map(|s| &s.self_ty).unwrap_or(&bare),
},
m,
)
.map(|r| r.skip_reason())
.unwrap_or_default(),
name: m.name(),
trait_path: m.trait_path(),
julia_name: String::new(),
symbol: crate::codegen::method_symbol_of(&stem, &m.method_stem()),
is_static: m.is_static(),
is_mutable: m.is_mutable(),
is_constructor: m.is_constructor(struct_name),
is_classmethod: false,
vis: crate::attrs::visibility_string(&m.func.vis),
python_name: String::new(),
accessor: String::new(),
attribute: m.attribute,
string_owner: crate::codegen::method_string_owner(&stem, &m.method_stem()),
return_kind: shapes[i].kind,
ok_type: shapes[i].ok_type.clone(),
err_type: shapes[i].err_type.clone(),
inner_type: shapes[i].inner_type.clone(),
ok_abi: shapes[i].ok_abi.clone(),
err_abi: shapes[i].err_abi.clone(),
inner_abi: shapes[i].inner_abi.clone(),
returns_boxed_struct: m.returns_boxed_struct(struct_name),
cfg: crate::cfg::predicate_string(&crate::cfg::effective_cfg_attrs(
&m.enclosing_cfg,
&m.func.attrs,
)),
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(),
py_return: None,
})
.collect::<Vec<_>>();
let mut methods = methods;
julia_method_names(&mut methods);
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: refusal
.as_ref()
.map(|r| r.skip_reason())
.unwrap_or_default(),
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,
methods,
derives: model.derives.clone(),
has_clone: false,
has_owned_string_helper: refusal.is_none()
&& crate::codegen::crate_struct_needs_owned_string_helper(&model.item),
has_borrowed_string_helper: false,
context_source: String::new(),
generic_wrappers: Vec::new(),
line: model.line,
module_path: module_path.to_vec(),
}
}