use crate::codegen::{panic_symbol, struct_free_symbol};
use crate::manifest::{Arg, Function, ReturnKind, Struct};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Namespace {
Value,
Type,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Scope {
Global,
Module(Vec<String>),
Unknown,
}
impl Scope {
pub fn meets(&self, other: &Scope) -> bool {
match (self, other) {
(Scope::Global, Scope::Global) => true,
(Scope::Module(a), Scope::Module(b)) => a == b,
_ => false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Claim {
pub name: String,
pub exported: bool,
pub namespace: Namespace,
pub scope: Scope,
}
impl Claim {
pub fn clashes_with(&self, other: &Claim) -> bool {
self.name == other.name
&& self.namespace == other.namespace
&& self.scope.meets(&other.scope)
}
fn exported(name: String) -> Claim {
Claim {
name,
exported: true,
namespace: Namespace::Value,
scope: Scope::Global,
}
}
fn private(name: String, namespace: Namespace) -> Claim {
Claim {
name,
exported: false,
namespace,
scope: Scope::Unknown,
}
}
fn in_scope(mut self, scope: &Scope) -> Claim {
if !self.exported {
self.scope = scope.clone();
}
self
}
pub fn in_real_module(mut self, module: &[String]) -> Claim {
if matches!(self.scope, Scope::Module(_)) {
self.scope = Scope::Module(module.to_vec());
}
self
}
}
fn scoped(claims: Vec<Claim>, scope: &Scope) -> Vec<Claim> {
claims
.into_iter()
.map(|claim| claim.in_scope(scope))
.collect()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StringHelpers {
AsDeclared,
Reserved,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Policy {
pub strings: StringHelpers,
pub skip_cfg_gated: bool,
}
impl Policy {
pub const JULIA: Policy = Policy {
strings: StringHelpers::AsDeclared,
skip_cfg_gated: true,
};
pub const PYO3_SCAN: Policy = Policy {
strings: StringHelpers::Reserved,
skip_cfg_gated: false,
};
}
pub fn panic_slot(symbol: &str) -> String {
format!("__RUSTCALL_PANIC_{}", symbol.to_uppercase())
}
pub fn helper_panic_slot(symbol: &str) -> String {
let suffix: String = symbol.bytes().map(|b| format!("{b:02X}")).collect();
format!("__RUSTCALL_HELPER_PANIC_{suffix}")
}
pub fn owned_string_names(owner: &str) -> [String; 2] {
[
format!("{owner}_RustCallOwnedString"),
format!("{owner}_free_rust_string"),
]
}
pub fn borrowed_string_name(owner: &str) -> String {
format!("{owner}_RustCallBorrowedString")
}
pub fn owned_vec_names(getter: &str) -> String {
format!("{getter}_RustCallOwnedVec")
}
fn exported_first(mut claims: Vec<Claim>) -> Vec<Claim> {
claims.sort_by_key(|claim| !claim.exported);
claims
}
pub fn wrapper_claims(symbol: &str) -> Vec<Claim> {
let mut out = helper_claims(symbol);
out.push(Claim::private(panic_slot(symbol), Namespace::Value));
out
}
pub fn helper_claims(symbol: &str) -> Vec<Claim> {
vec![
Claim::exported(symbol.to_string()),
Claim::exported(panic_symbol(symbol)),
]
}
pub fn string_claims(owner: &str, owned: bool, borrowed: bool, policy: Policy) -> Vec<Claim> {
let (owned, borrowed) = match policy.strings {
StringHelpers::AsDeclared => (owned, borrowed),
StringHelpers::Reserved => {
let any = owned || borrowed;
(any, any)
}
};
let mut out = Vec::new();
if owned {
let [ty, free] = owned_string_names(owner);
out.push(Claim::private(ty, Namespace::Type));
out.push(Claim::exported(free));
}
if borrowed {
out.push(Claim::private(borrowed_string_name(owner), Namespace::Type));
}
out
}
pub fn aggregate_name(kind: ReturnKind, owner: &str) -> Option<String> {
match kind {
ReturnKind::Result | ReturnKind::PyResult => Some(format!("CResult_{owner}")),
ReturnKind::Option => Some(format!("COption_{owner}")),
ReturnKind::Plain | ReturnKind::Unit => None,
}
}
fn aggregate_claims(kind: ReturnKind, owner: &str, args: &[Arg]) -> Vec<Claim> {
(0..=trailing_default_count(args))
.filter_map(|omitted| aggregate_name(kind, &default_arity_name(owner, omitted)))
.map(|name| Claim::private(name, Namespace::Type))
.collect()
}
pub fn declares_owned_string(abis: [&str; 4]) -> bool {
abis.contains(&"string")
}
pub fn declares_borrowed_string(abis: [&str; 4]) -> bool {
abis.contains(&"str")
}
pub fn trailing_default_count(args: &[Arg]) -> usize {
args.iter()
.rev()
.take_while(|arg| !arg.python_default.is_empty())
.count()
}
pub fn default_arity_name(base: &str, omitted: usize) -> String {
if omitted == 0 {
base.to_string()
} else {
format!("{base}__default_{omitted}")
}
}
pub fn function_claims(f: &Function, policy: Policy) -> Vec<Claim> {
if !f.exported || f.symbol.is_empty() || (policy.skip_cfg_gated && !f.cfg.is_empty()) {
return Vec::new();
}
if !f.attribute.generates_wrapper() {
return vec![Claim::exported(f.symbol.clone())];
}
let mut out = wrapper_claims(&f.symbol);
if !f.ffi_name.is_empty() {
out.extend(string_claims(
&f.ffi_name,
f.has_owned_string_helper,
f.has_borrowed_string_helper,
policy,
));
out.extend(aggregate_claims(f.return_kind, &f.ffi_name, &f.args));
}
exported_first(scoped(out, &Scope::Module(f.module_path.clone())))
}
pub fn struct_claims(s: &Struct, policy: Policy) -> Vec<Claim> {
if (policy.skip_cfg_gated && !s.cfg.is_empty()) || s.ffi_name.is_empty() {
return Vec::new();
}
let here = Scope::Module(s.module_path.clone());
let mut out = Vec::new();
if s.type_params.is_empty() {
out.extend(helper_claims(&struct_free_symbol(&s.ffi_name)));
}
if s.has_clone {
out.extend(helper_claims(&format!("{}_clone", s.ffi_name)));
}
for field in &s.fields {
for accessor in [&field.getter, &field.setter] {
if !accessor.is_empty() {
out.extend(helper_claims(accessor));
}
}
if field.abi == "vec" && !field.getter.is_empty() {
out.push(
Claim::private(owned_vec_names(&field.getter), Namespace::Type).in_scope(&here),
);
if !field.free_symbol.is_empty() {
out.push(Claim::exported(field.free_symbol.clone()));
}
}
}
let mut buffers: Vec<(String, bool, bool)> = Vec::new();
let note = |owner: &str, owned: bool, borrowed: bool, buffers: &mut Vec<_>| {
if owner.is_empty() || (!owned && !borrowed) {
return;
}
match buffers
.iter_mut()
.find(|(o, _, _): &&mut (String, bool, bool)| o == owner)
{
Some(entry) => {
entry.1 |= owned;
entry.2 |= borrowed;
}
None => buffers.push((owner.to_string(), owned, borrowed)),
}
};
note(
&s.ffi_name,
s.has_owned_string_helper,
s.has_borrowed_string_helper,
&mut buffers,
);
for m in &s.methods {
if policy.skip_cfg_gated && !m.cfg.is_empty() {
continue;
}
if !m.symbol.is_empty() {
let where_ = if m.string_owner == s.ffi_name || m.string_owner.is_empty() {
here.clone()
} else {
Scope::Unknown
};
let mut claims = wrapper_claims(&m.symbol);
claims.extend(aggregate_claims(
m.return_kind,
&crate::codegen::method_string_owner(&s.ffi_name, &m.name),
&m.args,
));
out.extend(scoped(claims, &where_));
}
let abis = [
m.return_abi.as_str(),
m.ok_abi.as_str(),
m.err_abi.as_str(),
m.inner_abi.as_str(),
];
let owner = if m.string_owner.is_empty() {
crate::codegen::method_string_owner(&s.ffi_name, &m.name)
} else {
m.string_owner.clone()
};
note(
&owner,
declares_owned_string(abis),
declares_borrowed_string(abis),
&mut buffers,
);
}
for (owner, owned, borrowed) in buffers {
let where_ = if owner == s.ffi_name {
here.clone()
} else {
Scope::Unknown
};
out.extend(scoped(
string_claims(&owner, owned, borrowed, policy),
&where_,
));
}
exported_first(out)
}
pub fn clash_kind(claim: &Claim) -> &'static str {
if claim.exported {
"exported symbol"
} else {
"generated item"
}
}
pub fn internal_origin(claim: &Claim) -> &'static str {
if claim.exported {
return "";
}
if claim.name.starts_with("__RUSTCALL_PANIC_") {
"the thread-local slot of a wrapper's panic channel, named by \
upper-casing the wrapper's symbol — so two wrappers whose symbols \
differ only in case meet here"
} else if claim.name.starts_with("CResult_") || claim.name.starts_with("COption_") {
"the `#[repr(C)]` type a `Result` / `Option` wrapper returns, named \
`CResult_<owner>` / `COption_<owner>` after the function, or after \
`<Struct>_<method>` for a method"
} else if claim.name.ends_with("_RustCallOwnedString")
|| claim.name.ends_with("_RustCallBorrowedString")
{
"the string buffer type a wrapper returns, named after the item that \
owns the buffer"
} else if claim.name.ends_with("_RustCallOwnedVec") {
"the owned-vector buffer type a field getter returns"
} else {
"an item RustCall generates next to the wrapper"
}
}