use syn::spanned::Spanned;
use syn::{FnArg, ImplItem, ImplItemFn, Item, ItemFn, ItemStruct, ReturnType, Type};
use crate::attrs::{
julia_owns_entry_point, pyo3_field_access, pyo3_marker, pyo3_method_markers, pyo3_name,
pyo3_signature, visibility_string, Pyo3Marker, Pyo3MethodMarker, Pyo3ParameterKind,
};
use crate::cfg::predicate_string;
use crate::extract::fn_args;
use crate::manifest::{
skip_reason, Attribute, Field, Function, Manifest, Method, ReturnKind, Struct,
};
use crate::paths::{
import_of_type_alias, imports_of_use, locate, ImplHeader, Located, ScannedImport,
};
use crate::types::{
extract_option_type, extract_result_type, generics_to_type_params, has_impl_trait,
has_type_params, is_ffi_compatible_type, is_str_ref_type, is_string_type,
return_type_to_string, type_to_string, unparen,
};
pub fn extract_pyo3_items(items: &[Item], manifest: &mut Manifest) -> Vec<PendingModule> {
let mut scan = Pyo3Scan::new();
let pending = scan.file(items, &[], true, &[], manifest);
scan.finish(manifest);
pending
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingModule {
pub module_path: Vec<String>,
pub reachable: bool,
pub name: String,
pub path_attr: Option<String>,
pub dir_components: Vec<String>,
pub cfg: Vec<syn::Attribute>,
}
#[derive(Debug, Default)]
pub struct Pyo3Scan {
classes: Vec<ScannedClass>,
impls: Vec<ScannedImpl>,
imports: Vec<ScannedImport>,
routes: crate::public_routes::PublicRoutes,
edition_2015: bool,
intrinsic_skips: std::collections::BTreeMap<(Vec<String>, String, usize, String), String>,
}
impl Pyo3Scan {
pub fn with_edition(edition: &str) -> Self {
Self {
routes: crate::public_routes::PublicRoutes::with_edition(edition),
edition_2015: edition == "2015",
..Self::default()
}
}
}
#[derive(Debug)]
struct ScannedClass {
module_path: Vec<String>,
entry: Struct,
visibility: syn::Visibility,
reachable_fields: Vec<Field>,
cfg: Vec<syn::Attribute>,
}
#[derive(Debug)]
struct ScannedImpl {
header: ImplHeader,
line: usize,
funcs: Vec<ImplItemFn>,
cfg: Vec<syn::Attribute>,
enclosing_cfg: Vec<syn::Attribute>,
}
fn cfg_variants_of(
classes: &[ScannedClass],
index: usize,
enclosing: &[syn::Attribute],
) -> Vec<usize> {
let want = crate::cfg::predicate_string(enclosing);
let here = &classes[index];
let same =
|c: &ScannedClass| c.entry.name == here.entry.name && c.module_path == here.module_path;
if crate::cfg::predicate_string(&here.cfg) == want {
return vec![index];
}
if let Some(exact) = classes
.iter()
.position(|c| same(c) && crate::cfg::predicate_string(&c.cfg) == want)
{
return vec![exact];
}
let overlapping: Vec<usize> = classes
.iter()
.enumerate()
.filter(|(_, c)| same(c) && !cfg_exclusive(&crate::cfg::predicate_string(&c.cfg), &want))
.map(|(i, _)| i)
.collect();
if !overlapping.is_empty() {
return overlapping;
}
vec![index]
}
impl Located for ScannedClass {
fn name(&self) -> &str {
&self.entry.name
}
fn module_path(&self) -> &[String] {
&self.module_path
}
fn visible_from(&self, module_path: &[String]) -> bool {
crate::paths::visible_from(&self.visibility, &self.module_path, module_path)
}
}
impl Pyo3Scan {
pub fn new() -> Self {
Pyo3Scan::default()
}
pub fn file(
&mut self,
items: &[Item],
module_path: &[String],
reachable: bool,
enclosing_cfg: &[syn::Attribute],
manifest: &mut Manifest,
) -> Vec<PendingModule> {
self.routes.file(items, module_path, enclosing_cfg);
let mut path = module_path.to_vec();
let mut dirs = Vec::new();
let mut pending = Vec::new();
self.level(
items,
&mut path,
&mut dirs,
reachable,
enclosing_cfg,
manifest,
&mut pending,
&[],
false,
);
pending
}
#[allow(clippy::too_many_arguments)]
fn level(
&mut self,
items: &[Item],
module_path: &mut Vec<String>,
dir_components: &mut Vec<String>,
reachable: bool,
enclosing_cfg: &[syn::Attribute],
manifest: &mut Manifest,
pending: &mut Vec<PendingModule>,
python_path: &[String],
inside_pymodule: bool,
) {
for item in items {
match item {
Item::Type(alias) => {
if let Some(import) =
import_of_type_alias(alias, module_path, self.edition_2015)
{
self.imports.push(import);
}
}
Item::Fn(f) => {
if julia_owns_entry_point(&f.attrs) {
continue;
}
match pyo3_marker(&f.attrs) {
Some(Pyo3Marker::Function) => {
let intrinsic = function_entry(
f,
Attribute::PyFunction,
true,
module_path,
python_path,
enclosing_cfg,
);
self.intrinsic_skips.insert(
(
module_path.clone(),
intrinsic.name.clone(),
intrinsic.line,
intrinsic.cfg.clone(),
),
intrinsic.skip_reason,
);
manifest.functions.push(function_entry(
f,
Attribute::PyFunction,
reachable,
module_path,
python_path,
enclosing_cfg,
));
}
Some(Pyo3Marker::Module) => {
manifest.functions.push(function_entry(
f,
Attribute::PyModule,
reachable,
module_path,
&[],
enclosing_cfg,
));
}
_ => {}
}
}
Item::Struct(s) => {
if julia_owns_entry_point(&s.attrs) {
continue;
}
if pyo3_marker(&s.attrs) == Some(Pyo3Marker::Class) {
self.classes.push(ScannedClass {
module_path: module_path.clone(),
entry: class_entry(
s,
reachable,
module_path,
python_path,
enclosing_cfg,
),
reachable_fields: class_entry(
s,
true,
module_path,
python_path,
enclosing_cfg,
)
.fields,
visibility: s.vis.clone(),
cfg: enclosing_cfg.to_vec(),
});
}
}
Item::Impl(imp) => {
if pyo3_marker(&imp.attrs) != Some(Pyo3Marker::Methods) {
continue;
}
let Some(header) = ImplHeader::of(imp, module_path) else {
continue;
};
self.impls.push(ScannedImpl {
header,
line: imp.span().start().line,
cfg: crate::cfg::effective_cfg_attrs(enclosing_cfg, &imp.attrs),
enclosing_cfg: enclosing_cfg.to_vec(),
funcs: imp
.items
.iter()
.filter_map(|ii| match ii {
ImplItem::Fn(f) => Some(f.clone()),
_ => None,
})
.collect(),
});
}
Item::Use(u) => {
self.imports.extend(imports_of_use(u, module_path));
}
Item::Mod(m) => {
let inner_reachable = reachable && matches!(m.vis, syn::Visibility::Public(_));
let inner_cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &m.attrs);
if pyo3_marker(&m.attrs) == Some(Pyo3Marker::Module) {
manifest
.functions
.push(module_entry(m, module_path, enclosing_cfg));
let inner_python = if inside_pymodule {
let mut path = python_path.to_vec();
path.push(_pyo3_module_python_name(&m.attrs, &m.ident));
path
} else {
Vec::new()
};
module_path.push(m.ident.to_string());
if let Some((_, inner)) = &m.content {
dir_components.push(m.ident.to_string());
self.level(
inner,
module_path,
dir_components,
inner_reachable,
&inner_cfg,
manifest,
pending,
&inner_python,
true,
);
dir_components.pop();
} else {
pending.push(PendingModule {
module_path: module_path.clone(),
reachable: inner_reachable,
name: m.ident.to_string(),
path_attr: path_attribute(&m.attrs),
dir_components: dir_components.clone(),
cfg: inner_cfg,
});
}
module_path.pop();
continue;
}
module_path.push(m.ident.to_string());
match &m.content {
Some((_, inner)) => {
dir_components.push(m.ident.to_string());
self.level(
inner,
module_path,
dir_components,
inner_reachable,
&inner_cfg,
manifest,
pending,
python_path,
inside_pymodule,
);
dir_components.pop();
}
None => pending.push(PendingModule {
module_path: module_path.clone(),
reachable: inner_reachable,
name: m.ident.to_string(),
path_attr: path_attribute(&m.attrs),
dir_components: dir_components.clone(),
cfg: inner_cfg,
}),
}
module_path.pop();
}
_ => {}
}
}
}
pub fn finish(mut self, manifest: &mut Manifest) {
let mut route_cache = std::collections::BTreeMap::new();
for function in &mut manifest.functions {
if !function.attribute.is_pyo3_scan() {
continue;
}
let mut canonical = function.module_path.clone();
canonical.push(function.name.clone());
let routes = route_cache
.entry(function.cfg.clone())
.or_insert_with(|| self.routes.resolve_for(&function.cfg));
if let Some(route) =
routes.get(&(crate::public_routes::Namespace::Value, canonical.clone()))
{
if function.skip_reason == skip_reason::NOT_PUBLIC {
if let Some(intrinsic) = self.intrinsic_skips.get(&(
function.module_path.clone(),
function.name.clone(),
function.line,
function.cfg.clone(),
)) {
function.skip_reason = intrinsic.clone();
}
}
if route.path != canonical {
function.callable_path = route.path.clone();
}
merge_route_cfg(&mut function.cfg, &mut function.cfg_features, route);
}
}
for class in &mut self.classes {
let mut canonical = class.module_path.clone();
canonical.push(class.entry.name.clone());
let routes = route_cache
.entry(class.entry.cfg.clone())
.or_insert_with(|| self.routes.resolve_for(&class.entry.cfg));
if let Some(route) =
routes.get(&(crate::public_routes::Namespace::Type, canonical.clone()))
{
if class.entry.skip_reason == skip_reason::NOT_PUBLIC {
class.entry.skip_reason = item_skip_reason(
&class.visibility,
true,
!class.entry.type_params.is_empty(),
)
.unwrap_or_default();
class.entry.fields = std::mem::take(&mut class.reachable_fields);
}
if route.path != canonical {
class.entry.callable_path = route.path.clone();
}
merge_route_cfg(&mut class.entry.cfg, &mut class.entry.cfg_features, route);
}
}
self.impls.sort_by(|a, b| {
a.header
.module_path
.cmp(&b.header.module_path)
.then(a.line.cmp(&b.line))
});
for imp in &self.impls {
let Ok(index) = locate(&self.classes, &imp.header, &self.imports) else {
continue;
};
let targets = cfg_variants_of(&self.classes, index, &imp.enclosing_cfg);
for index in targets {
let owner_skip = self.classes[index].entry.skip_reason.clone();
let class_path = self.classes[index].module_path.clone();
for func in &imp.funcs {
let returns_self = matches!(
&func.sig.output,
syn::ReturnType::Type(_, ty) if {
let value = py_result_ok_type(ty).unwrap_or_else(|| (**ty).clone());
returns_class(
&value, &self.classes[index], &imp.header.module_path,
&self.classes, &self.imports, self.edition_2015,
)
}
);
let class_ident =
syn::Ident::new(&self.classes[index].entry.name, imp.header.target.span());
let entry = method_entry(
&class_ident,
&class_path,
returns_self,
func,
&owner_skip,
&imp.cfg,
);
self.classes[index].entry.methods.push(entry);
}
}
}
manifest
.structs
.extend(self.classes.into_iter().map(|c| c.entry));
mark_julia_surface_collisions(manifest, &Emitted::new());
}
}
fn mark_julia_surface_collisions(manifest: &mut Manifest, emitted: &Emitted) {
let owners = manifest.clone();
mark_julia_surface_collisions_pass(manifest, None);
mark_symbol_collisions(manifest, emitted);
loop {
let mut next = owners.clone();
mark_julia_surface_collisions_pass(&mut next, Some(manifest));
mark_symbol_collisions(&mut next, emitted);
if next == *manifest {
return;
}
*manifest = next;
}
}
fn mark_julia_surface_collisions_pass(
manifest: &mut Manifest,
aggregate_owners: Option<&Manifest>,
) {
let symbol_excluded = |reason: &str| {
reason.starts_with("symbol_collision:")
|| reason.starts_with("owner_skipped:symbol_collision:")
};
type Scoped = (Vec<String>, String);
type ScopedArity = (Vec<String>, String, usize);
let class_names: Vec<(Scoped, String, String)> = manifest
.structs
.iter()
.enumerate()
.filter(|(i, s)| {
s.attribute.is_pyo3_scan()
&& s.skip_reason.is_empty()
&& aggregate_owners
.is_none_or(|previous| !symbol_excluded(&previous.structs[*i].skip_reason))
})
.map(|(_, s)| {
(
(s.module_path.clone(), s.name.clone()),
qualified(&s.module_path, &s.name),
s.cfg.clone(),
)
})
.collect();
let mut aggregate_names: Vec<(Scoped, String, String)> = aggregate_owners
.into_iter()
.flat_map(|owners| &owners.functions)
.filter(|f| f.attribute.is_pyo3_scan() && f.skip_reason.is_empty())
.filter(|f| {
matches!(
f.return_kind,
ReturnKind::PyResult | ReturnKind::Result | ReturnKind::Option
)
})
.flat_map(|f| {
let prefix = if f.return_kind == ReturnKind::Option {
"COption"
} else {
"CResult"
};
let defaults = f
.args
.iter()
.rev()
.take_while(|arg| !arg.python_default.is_empty())
.count();
(0..=defaults).map(move |omitted| {
let owner = crate::claims::default_arity_name(&f.ffi_name, omitted);
let name = format!("{prefix}_{owner}");
((f.module_path.clone(), name.clone()), name, f.cfg.clone())
})
})
.collect();
for s in aggregate_owners
.into_iter()
.flat_map(|owners| &owners.structs)
.filter(|s| s.attribute.is_pyo3_scan() && s.skip_reason.is_empty())
{
for m in s.methods.iter().filter(|m| {
m.skip_reason.is_empty()
&& matches!(
m.return_kind,
ReturnKind::PyResult | ReturnKind::Result | ReturnKind::Option
)
}) {
let prefix = if m.return_kind == ReturnKind::Option {
"COption"
} else {
"CResult"
};
let owner = crate::codegen::method_string_owner(&s.ffi_name, &m.name);
let defaults = m
.args
.iter()
.rev()
.take_while(|arg| !arg.python_default.is_empty())
.count();
for omitted in 0..=defaults {
let variant = crate::claims::default_arity_name(&owner, omitted);
let name = format!("{prefix}_{variant}");
aggregate_names.push(((s.module_path.clone(), name.clone()), name, m.cfg.clone()));
}
}
}
let aggregate_named = |path: &[String], name: &str, cfg: &str| {
aggregate_names
.iter()
.find(|((p, n), _, c)| p == path && n == name && cfg_clash(c, cfg))
};
let class_named = |path: &[String], name: &str, cfg: &str| {
class_names
.iter()
.find(|((p, n), _, c)| p == path && n == name && cfg_clash(c, cfg))
};
let mut taken: Vec<(ScopedArity, String, String)> = Vec::new();
for (i, f) in manifest.functions.iter_mut().enumerate() {
if !f.attribute.is_pyo3_scan() || !f.skip_reason.is_empty() {
continue;
}
if let Some((_, class, _)) = class_named(&f.module_path, &f.name, &f.cfg) {
f.skip_reason = skip_reason::detailed(skip_reason::JULIA_NAME_COLLISION, class);
continue;
}
if let Some((_, aggregate, _)) = aggregate_named(&f.module_path, &f.name, &f.cfg) {
f.skip_reason = skip_reason::detailed(skip_reason::JULIA_NAME_COLLISION, aggregate);
continue;
}
if aggregate_owners
.is_none_or(|previous| !symbol_excluded(&previous.functions[i].skip_reason))
{
taken.push((
(f.module_path.clone(), f.name.clone(), f.args.len()),
qualified(&f.module_path, &f.name),
f.cfg.clone(),
));
}
}
for (i, s) in manifest.structs.iter_mut().enumerate() {
if !s.attribute.is_pyo3_scan() || !s.skip_reason.is_empty() {
continue;
}
let owner = qualified(&s.module_path, &s.name);
let s_cfg = s.cfg.clone();
if let Some((_, aggregate, _)) = aggregate_named(&s.module_path, &s.name, &s_cfg) {
let reason = skip_reason::detailed(skip_reason::JULIA_NAME_COLLISION, aggregate);
s.skip_reason = reason.clone();
for m in &mut s.methods {
if m.skip_reason.is_empty() {
m.skip_reason = skip_reason::detailed(skip_reason::OWNER_SKIPPED, &reason);
}
}
continue;
}
for (j, m) in s.methods.iter_mut().enumerate() {
if !m.skip_reason.is_empty() || !m.is_static || m.is_constructor {
continue;
}
if let Some((_, class, _)) = class_named(&s.module_path, &m.name, &m.cfg) {
m.skip_reason = skip_reason::detailed(skip_reason::JULIA_NAME_COLLISION, class);
continue;
}
if let Some((_, aggregate, _)) = aggregate_named(&s.module_path, &m.name, &m.cfg) {
m.skip_reason = skip_reason::detailed(skip_reason::JULIA_NAME_COLLISION, aggregate);
continue;
}
let key = (s.module_path.clone(), m.name.clone(), m.args.len());
match taken
.iter()
.find(|(k, _, c)| *k == key && cfg_clash(c, &m.cfg))
{
Some((_, other, _)) => {
m.skip_reason = skip_reason::detailed(skip_reason::JULIA_NAME_COLLISION, other);
}
None => {
if aggregate_owners.is_none_or(|previous| {
!symbol_excluded(&previous.structs[i].methods[j].skip_reason)
}) {
taken.push((key, format!("{owner}::{}", m.name), m.cfg.clone()));
}
}
}
}
}
}
pub(crate) use crate::cfg::cfg_exclusive;
fn cfg_clash(a: &str, b: &str) -> bool {
!cfg_exclusive(a, b)
}
pub type Emitted = std::collections::HashMap<String, std::collections::HashSet<String>>;
fn emitted_arities<'a>(
emitted: &'a Emitted,
owner: &str,
) -> Option<&'a std::collections::HashSet<String>> {
emitted.get(owner)
}
fn from_collision(reason: &str) -> bool {
let body = reason
.strip_prefix(skip_reason::OWNER_SKIPPED)
.and_then(|rest| rest.strip_prefix(':'))
.unwrap_or(reason);
body.starts_with(skip_reason::SYMBOL_COLLISION)
|| body.starts_with(skip_reason::JULIA_NAME_COLLISION)
}
fn clear_collision_reasons(manifest: &mut Manifest) {
for s in &mut manifest.structs {
for f in &mut s.fields {
f.restore_accessors();
}
}
for f in &mut manifest.functions {
if from_collision(&f.skip_reason) {
f.skip_reason.clear();
}
}
for s in &mut manifest.structs {
if from_collision(&s.skip_reason) {
s.skip_reason.clear();
}
for m in &mut s.methods {
if from_collision(&m.skip_reason) {
m.skip_reason.clear();
}
}
}
}
pub fn remark_collisions(manifest: &mut Manifest, lowered: &Manifest, known: &mut Emitted) -> bool {
let mut emitted: Emitted = Emitted::new();
for f in &lowered.functions {
if !f.attribute.is_pyo3_scan() {
continue;
}
if from_collision(&f.skip_reason) {
continue;
}
let key = qualified(&f.module_path, &f.name);
let slot = emitted.entry(key).or_default();
if f.skip_reason.is_empty() {
slot.insert(f.symbol.clone());
}
}
for s in &lowered.structs {
if !s.attribute.is_pyo3_scan() {
continue;
}
let class = qualified(&s.module_path, &s.name);
let class_refused_here = from_collision(&s.skip_reason);
if !class_refused_here {
let slot = emitted.entry(class.clone()).or_default();
if s.skip_reason.is_empty() {
slot.insert(s.ffi_name.clone());
}
}
for m in &s.methods {
if class_refused_here || from_collision(&m.skip_reason) {
continue;
}
let slot = emitted.entry(format!("{class}::{}", m.name)).or_default();
if s.skip_reason.is_empty() && m.skip_reason.is_empty() {
slot.insert(m.symbol.clone());
}
}
}
for (owner, symbols) in emitted {
known.entry(owner).or_insert(symbols);
}
let before = manifest.clone();
clear_collision_reasons(manifest);
mark_julia_surface_collisions(manifest, known);
*manifest != before
}
fn mark_symbol_collisions(manifest: &mut Manifest, emitted: &Emitted) {
let mut taken: Vec<(String, String, String)> = Vec::new();
for f in manifest
.functions
.iter()
.filter(|f| !f.attribute.is_pyo3_scan())
{
for claim in crate::claims::function_claims(f, crate::claims::Policy::PYO3_SCAN) {
taken.push((
claim.name,
qualified(&f.module_path, &f.name),
f.cfg.clone(),
));
}
}
for s in manifest
.structs
.iter()
.filter(|s| !s.attribute.is_pyo3_scan())
{
for claim in crate::claims::struct_claims(s, crate::claims::Policy::PYO3_SCAN) {
taken.push((
claim.name,
qualified(&s.module_path, &s.name),
s.cfg.clone(),
));
}
}
let mut order: Vec<usize> = (0..manifest.functions.len()).collect();
order.sort_by(|&a, &b| {
let (x, y) = (&manifest.functions[a], &manifest.functions[b]);
x.module_path
.cmp(&y.module_path)
.then(x.line.cmp(&y.line))
.then(x.name.cmp(&y.name))
});
for i in order {
let f = &manifest.functions[i];
if !f.attribute.is_pyo3_scan() || !f.skip_reason.is_empty() || f.symbol.is_empty() {
continue;
}
let strings =
declares_string_helpers(&f.return_type, &f.ok_type, &f.err_type, &f.inner_type);
let actual = emitted_arities(emitted, &qualified(&f.module_path, &f.name));
let mut symbols = Vec::new();
for omitted in 0..=crate::claims::trailing_default_count(&f.args) {
let arity = crate::claims::default_arity_name(&f.symbol, omitted);
if actual.is_some_and(|a| !a.contains(&arity)) {
continue;
}
symbols.extend(wrapper_symbols(&arity));
if strings {
symbols.extend(string_helper_symbols(&crate::claims::default_arity_name(
&f.ffi_name,
omitted,
)));
}
}
if symbols.is_empty() {
continue;
}
let f_cfg = f.cfg.clone();
if let Some((_, owner, _)) = taken
.iter()
.find(|(s, _, c)| symbols.contains(s) && cfg_clash(c, &f_cfg))
{
let owner = owner.clone();
manifest.functions[i].skip_reason =
skip_reason::detailed(skip_reason::SYMBOL_COLLISION, &owner);
} else {
let owner = qualified(&f.module_path, &f.name);
for symbol in symbols {
taken.push((symbol, owner.clone(), f_cfg.clone()));
}
}
}
let mut class_names: Vec<(String, String, String)> = manifest
.structs
.iter()
.filter(|s| !s.attribute.is_pyo3_scan())
.map(|s| {
(
s.ffi_name.clone(),
qualified(&s.module_path, &s.name),
s.cfg.clone(),
)
})
.collect();
let mut struct_order: Vec<usize> = (0..manifest.structs.len()).collect();
struct_order.sort_by(|&a, &b| {
let (x, y) = (&manifest.structs[a], &manifest.structs[b]);
x.module_path
.cmp(&y.module_path)
.then(x.line.cmp(&y.line))
.then(x.name.cmp(&y.name))
});
for i in struct_order {
let s = &manifest.structs[i];
if !s.attribute.is_pyo3_scan() || !s.skip_reason.is_empty() {
continue;
}
let class_key = qualified(&s.module_path, &s.name);
if emitted_arities(emitted, &class_key).is_some_and(|a| a.is_empty()) {
continue;
}
let name = s.ffi_name.clone();
let s_cfg = s.cfg.clone();
let free = crate::codegen::struct_free_symbol(&s.ffi_name);
let free_symbols = [crate::codegen::panic_symbol(&free), free];
let class_conflict = class_names
.iter()
.find(|(n, _, c)| *n == name && cfg_clash(c, &s_cfg))
.or_else(|| {
taken.iter().find(|(symbol, _, cfg)| {
free_symbols.contains(symbol) && cfg_clash(cfg, &s_cfg)
})
});
if let Some((_, owner, _)) = class_conflict {
let reason = skip_reason::detailed(skip_reason::SYMBOL_COLLISION, owner);
let s = &mut manifest.structs[i];
s.skip_reason = reason.clone();
for m in &mut s.methods {
if m.skip_reason.is_empty() {
m.skip_reason = skip_reason::detailed(skip_reason::OWNER_SKIPPED, &reason);
}
}
for f in &mut s.fields {
f.remember_accessors();
f.ffi_compatible = false;
f.getter.clear();
f.setter.clear();
f.free_symbol.clear();
}
continue;
}
let owner = qualified(&s.module_path, &s.name);
for symbol in free_symbols {
taken.push((symbol, owner.clone(), s_cfg.clone()));
}
let s = &mut manifest.structs[i];
let class_name = s.ffi_name.clone();
let method_class = class_key;
for m in &mut s.methods {
if !m.skip_reason.is_empty() || m.symbol.is_empty() {
continue;
}
let strings =
declares_string_helpers(&m.return_type, &m.ok_type, &m.err_type, &m.inner_type);
let string_owner = format!("{}_{}", class_name, m.name);
let actual = emitted_arities(emitted, &format!("{method_class}::{}", m.name));
let mut symbols = Vec::new();
for omitted in 0..=crate::claims::trailing_default_count(&m.args) {
let arity = crate::claims::default_arity_name(&m.symbol, omitted);
if actual.is_some_and(|a| !a.contains(&arity)) {
continue;
}
symbols.extend(wrapper_symbols(&arity));
if strings {
symbols.extend(string_helper_symbols(&crate::claims::default_arity_name(
&string_owner,
omitted,
)));
}
}
if symbols.is_empty() {
continue;
}
match taken
.iter()
.find(|(t, _, c)| symbols.contains(t) && cfg_clash(c, &s_cfg))
{
Some((_, other, _)) => {
m.skip_reason = skip_reason::detailed(skip_reason::SYMBOL_COLLISION, other);
}
None => {
for symbol in symbols {
taken.push((symbol, owner.clone(), s_cfg.clone()));
}
}
}
}
if s.fields
.iter()
.any(|f| !f.getter.is_empty() && is_string_spelling(&f.rust_type))
{
let helpers = string_helper_symbols(&class_name);
if taken
.iter()
.any(|(t, _, c)| helpers.contains(t) && cfg_clash(c, &s_cfg))
{
for f in &mut s.fields {
if is_string_spelling(&f.rust_type) {
f.remember_accessors();
f.ffi_compatible = false;
f.getter.clear();
f.setter.clear();
f.free_symbol.clear();
}
}
} else {
for symbol in helpers {
taken.push((symbol, owner.clone(), s_cfg.clone()));
}
}
}
for f in &mut s.fields {
if !f.getter.is_empty() {
let mut symbols = vec![f.getter.clone(), crate::codegen::panic_symbol(&f.getter)];
if f.abi == "vec" {
symbols.push(format!("{}_RustCallOwnedVec", f.getter));
symbols.push(f.free_symbol.clone());
}
if taken
.iter()
.any(|(t, _, c)| symbols.contains(t) && cfg_clash(c, &s_cfg))
{
f.remember_accessors();
f.getter.clear();
f.free_symbol.clear();
} else {
for symbol in symbols {
taken.push((symbol, owner.clone(), s_cfg.clone()));
}
}
}
if !f.setter.is_empty() {
let symbols = [f.setter.clone(), crate::codegen::panic_symbol(&f.setter)];
if taken
.iter()
.any(|(t, _, c)| symbols.contains(t) && cfg_clash(c, &s_cfg))
{
f.remember_accessors();
f.setter.clear();
} else {
for symbol in symbols {
taken.push((symbol, owner.clone(), s_cfg.clone()));
}
}
}
if f.getter.is_empty() && f.setter.is_empty() {
f.ffi_compatible = false;
}
}
class_names.push((name, owner, s_cfg));
}
}
fn string_helper_symbols(owner: &str) -> [String; 3] {
let [owned, free] = crate::claims::owned_string_names(owner);
[owned, free, crate::claims::borrowed_string_name(owner)]
}
fn declares_string_helpers(
return_type: &str,
ok_type: &str,
err_type: &str,
inner_type: &str,
) -> bool {
[return_type, ok_type, err_type, inner_type]
.iter()
.any(|spelling| is_string_spelling(spelling))
}
fn is_string_spelling(spelling: &str) -> bool {
!spelling.is_empty()
&& syn::parse_str::<Type>(spelling)
.map(|ty| is_string_type(&ty) || is_str_ref_type(&ty))
.unwrap_or(false)
}
fn wrapper_symbols(symbol: &str) -> [String; 3] {
let claims = crate::claims::wrapper_claims(symbol);
let mut names = claims.into_iter().map(|c| c.name);
[
names.next().expect("entry point"),
names.next().expect("panic reader"),
names.next().expect("panic slot"),
]
}
fn merge_route_cfg(
cfg: &mut String,
features: &mut Vec<String>,
route: &crate::public_routes::PublicRoute,
) {
let mut predicates = route.predicates.clone();
if !cfg.is_empty() {
predicates.insert(cfg.clone());
}
if predicates.is_empty() {
return;
}
*cfg = if predicates.len() == 1 {
predicates.into_iter().next().unwrap()
} else {
format!(
"all({})",
predicates.into_iter().collect::<Vec<_>>().join(",")
)
};
let meta: syn::Meta =
syn::parse_str(&format!("cfg({cfg})")).expect("cfg predicates came from syn");
let attrs: Vec<syn::Attribute> = vec![syn::parse_quote!(#[#meta])];
*features = crate::cfg::predicate_features(&attrs);
}
fn qualified(module_path: &[String], name: &str) -> String {
if module_path.is_empty() {
name.to_string()
} else {
format!("{}::{}", module_path.join("::"), name)
}
}
fn path_attribute(attrs: &[syn::Attribute]) -> Option<String> {
for attr in attrs {
if !attr.path().is_ident("path") {
continue;
}
if let syn::Meta::NameValue(nv) = &attr.meta {
if let syn::Expr::Lit(lit) = &nv.value {
if let syn::Lit::Str(s) = &lit.lit {
return Some(s.value());
}
}
}
}
None
}
fn _pyo3_module_python_name(attrs: &[syn::Attribute], ident: &syn::Ident) -> String {
let named = pyo3_name(attrs);
if named.is_empty() {
ident.to_string()
} else {
named
}
}
fn module_entry(
item: &syn::ItemMod,
module_path: &[String],
enclosing_cfg: &[syn::Attribute],
) -> Function {
let name = item.ident.to_string();
let effective_cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &item.attrs);
Function {
name: name.clone(),
ffi_name: crate::codegen::symbol_stem(module_path, &name),
symbol: crate::codegen::function_symbol(module_path, &name),
attribute: Attribute::PyModule,
vis: visibility_string(&item.vis),
skip_reason: skip_reason::PYMODULE.to_string(),
python_name: pyo3_name(&item.attrs),
python_path: Vec::new(),
exported: false,
cfg: predicate_string(&effective_cfg),
cfg_features: crate::cfg::predicate_features(&effective_cfg),
is_generic: false,
type_params: Vec::new(),
args: Vec::new(),
return_type: String::new(),
return_kind: ReturnKind::Unit,
return_abi: String::new(),
ok_type: String::new(),
err_type: String::new(),
inner_type: String::new(),
ok_abi: String::new(),
err_abi: String::new(),
inner_abi: String::new(),
has_owned_string_helper: false,
has_borrowed_string_helper: false,
source: String::new(),
body_has_cfg: false,
line: item.span().start().line,
module_path: module_path.to_vec(),
callable_path: Vec::new(),
}
}
fn function_entry(
func: &ItemFn,
attribute: Attribute,
reachable: bool,
module_path: &[String],
python_path: &[String],
enclosing_cfg: &[syn::Attribute],
) -> Function {
let name = func.sig.ident.to_string();
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 return_type = return_type_to_string(&func.sig.output);
let (return_kind, ok_type, err_type, inner_type) = return_shape(&func.sig.output);
let reason = if attribute == Attribute::PyModule {
skip_reason::PYMODULE.to_string()
} else {
item_skip_reason(&func.vis, reachable, is_generic)
.unwrap_or_else(|| signature_skip_reason(&func.sig, return_kind).unwrap_or_default())
};
Function {
name: name.clone(),
ffi_name: crate::codegen::symbol_stem(module_path, &name),
symbol: crate::codegen::function_symbol(module_path, &name),
attribute,
vis: visibility_string(&func.vis),
skip_reason: reason,
python_name: pyo3_name(&func.attrs),
python_path: python_path.to_vec(),
exported: false,
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: pyo3_args(&func.sig, &func.attrs),
return_type,
return_kind,
return_abi: String::new(),
ok_type,
err_type,
inner_type,
ok_abi: String::new(),
err_abi: String::new(),
inner_abi: String::new(),
has_owned_string_helper: false,
has_borrowed_string_helper: false,
source: String::new(),
body_has_cfg: crate::cfg::body_has_cfg(&func.block),
line: func.span().start().line,
module_path: module_path.to_vec(),
callable_path: Vec::new(),
}
}
fn class_entry(
item: &ItemStruct,
reachable: bool,
module_path: &[String],
python_path: &[String],
enclosing_cfg: &[syn::Attribute],
) -> Struct {
let effective_cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &item.attrs);
let is_generic = has_type_params(&item.generics);
let reason = item_skip_reason(&item.vis, reachable, is_generic).unwrap_or_default();
let name = item.ident.to_string();
let stem = crate::codegen::symbol_stem(module_path, &name);
let options = crate::attrs::pyo3_class_options(&item.attrs);
let mut pyo3_options = Vec::new();
if options.subclass {
pyo3_options.push("subclass".to_string());
}
if options.dict {
pyo3_options.push("dict".to_string());
}
if options.weakref {
pyo3_options.push("weakref".to_string());
}
let mut fields = Vec::new();
if let syn::Fields::Named(named) = &item.fields {
for f in &named.named {
let Some(ident) = f.ident.clone() else {
continue;
};
let mut access = pyo3_field_access(&f.attrs);
access.get |= options.get_all;
access.set |= options.set_all;
access.set &= !options.frozen;
if !access.get && !access.set {
continue;
}
let field_is_public = matches!(f.vis, syn::Visibility::Public(_));
let vec_element = crate::types::pyo3_vec_element_type(&f.ty);
let usable = reason.is_empty()
&& field_is_public
&& pyo3_type_in(&f.ty).is_none()
&& (is_ffi_compatible_type(&f.ty)
|| is_string_type(&f.ty)
|| vec_element.is_some());
let getter = if usable && access.get {
crate::codegen::method_symbol_of(&stem, &format!("get_{ident}"))
} else {
String::new()
};
let vec_free = if vec_element.is_some() && !getter.is_empty() {
format!("{getter}_free_rust_vec")
} else {
String::new()
};
fields.push(Field {
name: ident.to_string(),
rust_type: type_to_string(&f.ty),
abi: if vec_element.is_some() {
"vec".to_string()
} else {
crate::codegen::field_abi(&f.ty).to_string()
},
vec_element: vec_element.as_ref().map(type_to_string).unwrap_or_default(),
free_symbol: vec_free,
ffi_compatible: usable,
getter,
setter: if usable && access.set {
crate::codegen::method_symbol_of(&stem, &format!("set_{ident}"))
} else {
String::new()
},
python_name: access.python_name,
vis: visibility_string(&f.vis),
pyo3_get: access.get,
pyo3_set: access.set,
cfg: predicate_string(&f.attrs),
precollision: None,
});
}
}
Struct {
name: name.clone(),
ffi_name: stem,
attribute: Attribute::PyClass,
vis: visibility_string(&item.vis),
skip_reason: reason,
python_name: pyo3_name(&item.attrs),
python_path: python_path.to_vec(),
pyo3_extends: options.extends,
pyo3_options,
python_owned_handle: false,
cfg: predicate_string(&effective_cfg),
cfg_features: crate::cfg::predicate_features(&effective_cfg),
type_params: generics_to_type_params(&item.generics),
fields,
methods: Vec::new(),
derives: crate::attrs::derive_list(&item.attrs),
has_clone: false,
has_owned_string_helper: false,
has_borrowed_string_helper: false,
context_source: String::new(),
generic_wrappers: Vec::new(),
line: item.span().start().line,
module_path: module_path.to_vec(),
callable_path: Vec::new(),
}
}
fn method_entry(
struct_ident: &syn::Ident,
class_path: &[String],
returns_self: bool,
func: &ImplItemFn,
owner_skip: &str,
enclosing_cfg: &[syn::Attribute],
) -> Method {
let effective_cfg = crate::cfg::effective_cfg_attrs(enclosing_cfg, &func.attrs);
let struct_stem = crate::codegen::symbol_stem(class_path, &struct_ident.to_string());
let markers = pyo3_method_markers(&func.attrs);
let has = |m: Pyo3MethodMarker| markers.contains(&m);
let receiver = func.sig.inputs.iter().find_map(|a| match a {
FnArg::Receiver(r) => Some(r),
_ => None,
});
let name = func.sig.ident.to_string();
let is_constructor = has(Pyo3MethodMarker::New);
let accessor = if has(Pyo3MethodMarker::Getter) {
"getter"
} else if has(Pyo3MethodMarker::Setter) {
"setter"
} else {
""
};
let is_generic = has_type_params(&func.sig.generics) || has_impl_trait(&func.sig);
let (return_kind, ok_type, err_type, inner_type) = return_shape(&func.sig.output);
let reason = if !owner_skip.is_empty() {
skip_reason::detailed(skip_reason::OWNER_SKIPPED, owner_skip)
} else {
item_skip_reason(&func.vis, true, is_generic)
.unwrap_or_else(|| signature_skip_reason(&func.sig, return_kind).unwrap_or_default())
};
Method {
trait_path: String::new(),
name: name.clone(),
symbol: crate::codegen::method_symbol_of(&struct_stem, &name),
is_static: receiver.is_none(),
is_mutable: receiver.map(|r| r.mutability.is_some()).unwrap_or(false),
is_constructor,
is_classmethod: has(Pyo3MethodMarker::ClassMethod),
vis: visibility_string(&func.vis),
skip_reason: reason,
python_name: pyo3_name(&func.attrs),
accessor: accessor.to_string(),
attribute: Attribute::PyMethods,
string_owner: String::new(),
return_kind,
ok_type,
err_type,
inner_type,
ok_abi: String::new(),
err_abi: String::new(),
inner_abi: String::new(),
returns_boxed_struct: returns_self,
args: pyo3_args(&func.sig, &func.attrs),
return_type: return_type_to_string(&func.sig.output),
return_abi: String::new(),
generic_wrapper: String::new(),
generic_wrapper_name: String::new(),
cfg: predicate_string(&effective_cfg),
}
}
fn pyo3_args(sig: &syn::Signature, attrs: &[syn::Attribute]) -> Vec<crate::manifest::Arg> {
let mut args = fn_args(sig);
let Ok(Some(parameters)) = pyo3_signature(attrs) else {
return args;
};
for parameter in parameters {
let Some(arg) = args.iter_mut().find(|arg| arg.name == parameter.name) else {
continue;
};
arg.python_default = parameter.default;
arg.python_kind = match parameter.kind {
Pyo3ParameterKind::PositionalOnly => "positional_only",
Pyo3ParameterKind::PositionalOrKeyword => "positional_or_keyword",
Pyo3ParameterKind::KeywordOnly => "keyword_only",
Pyo3ParameterKind::VarArgs => "var_args",
Pyo3ParameterKind::KwArgs => "kw_args",
}
.to_string();
}
args
}
fn returns_class(
ty: &Type,
class: &ScannedClass,
impl_path: &[String],
classes: &[ScannedClass],
imports: &[ScannedImport],
edition_2015: bool,
) -> bool {
let Type::Path(path) = unparen(ty) else {
return false;
};
if path.qself.is_some() {
return false;
}
if path.path.leading_colon.is_some() && !edition_2015 {
return false;
}
if path.path.is_ident("Self") {
return true;
}
let Some(target) = path.path.segments.last() else {
return false;
};
let mut qualifier = crate::paths::type_path_qualifier(ty);
if path.path.leading_colon.is_some() {
qualifier.anchor = crate::paths::PathAnchor::Crate;
}
let header = ImplHeader {
target: target.ident.clone(),
qualifier,
module_path: impl_path.to_vec(),
};
crate::paths::locate_type(classes, &header, imports).is_ok_and(|index| {
classes[index].entry.name == class.entry.name
&& classes[index].module_path == class.module_path
})
}
fn item_skip_reason(vis: &syn::Visibility, reachable: bool, is_generic: bool) -> Option<String> {
if !matches!(vis, syn::Visibility::Public(_)) || !reachable {
return Some(skip_reason::NOT_PUBLIC.to_string());
}
if is_generic {
return Some(skip_reason::GENERIC.to_string());
}
None
}
fn signature_skip_reason(sig: &syn::Signature, return_kind: ReturnKind) -> Option<String> {
if sig.asyncness.is_some() {
return Some(skip_reason::ASYNC_FN.to_string());
}
for input in &sig.inputs {
let FnArg::Typed(pt) = input else { continue };
if let Some(found) = pyo3_type_in(&pt.ty) {
return Some(skip_reason::detailed(skip_reason::PYO3_TYPE, &found));
}
}
if let ReturnType::Type(_, ty) = &sig.output {
let checked = if return_kind == ReturnKind::PyResult {
py_result_ok_type(ty).unwrap_or_else(|| (**ty).clone())
} else {
(**ty).clone()
};
if let Some(found) = pyo3_type_in(&checked) {
return Some(skip_reason::detailed(skip_reason::PYO3_TYPE, &found));
}
}
None
}
fn return_shape(output: &ReturnType) -> (ReturnKind, String, String, String) {
let mut ok_type = String::new();
let mut err_type = String::new();
let mut inner_type = String::new();
let kind = match output {
ReturnType::Default => ReturnKind::Unit,
ReturnType::Type(_, ty) => {
if let Some(ok) = py_result_ok_type(ty) {
ok_type = type_to_string(&ok);
ReturnKind::PyResult
} else if let Some(r) = extract_result_type(ty) {
ok_type = type_to_string(&r.ok_type);
err_type = type_to_string(&r.err_type);
ReturnKind::Result
} else if let Some(o) = extract_option_type(ty) {
inner_type = type_to_string(&o.inner_type);
ReturnKind::Option
} else if return_type_to_string(output) == "()" {
ReturnKind::Unit
} else {
ReturnKind::Plain
}
}
};
(kind, ok_type, err_type, inner_type)
}
pub fn py_result_ok_type(ty: &Type) -> Option<Type> {
let Type::Path(path) = unparen(ty) else {
return None;
};
let segment = path.path.segments.last()?;
if segment.ident != "PyResult" {
return None;
}
match &segment.arguments {
syn::PathArguments::AngleBracketed(args) => args.args.iter().find_map(|a| match a {
syn::GenericArgument::Type(t) => Some(t.clone()),
_ => None,
}),
_ => Some(syn::parse_quote!(())),
}
}
pub fn pyo3_type_in(ty: &Type) -> Option<String> {
let mut found = None;
walk_types(ty, &mut |t| {
if found.is_some() {
return;
}
if let Type::Path(p) = t {
let first_is_pyo3 = p
.path
.segments
.first()
.map(|s| s.ident == "pyo3")
.unwrap_or(false);
let last = p.path.segments.last();
let named = last
.map(|s| {
let id = s.ident.to_string();
id.starts_with("Py")
|| matches!(id.as_str(), "Python" | "GILGuard" | "Bound" | "Borrowed")
})
.unwrap_or(false);
if first_is_pyo3 || named {
found = Some(type_to_string(t));
}
}
});
found
}
fn walk_types(ty: &Type, f: &mut impl FnMut(&Type)) {
let ty = unparen(ty);
f(ty);
match ty {
Type::Path(p) => {
for segment in &p.path.segments {
if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
for arg in &args.args {
if let syn::GenericArgument::Type(t) = arg {
walk_types(t, f);
}
}
}
}
}
Type::Reference(r) => walk_types(&r.elem, f),
Type::Ptr(p) => walk_types(&p.elem, f),
Type::Slice(s) => walk_types(&s.elem, f),
Type::Array(a) => walk_types(&a.elem, f),
Type::Group(g) => walk_types(&g.elem, f),
Type::Tuple(t) => {
for elem in &t.elems {
walk_types(elem, f);
}
}
_ => {}
}
}