use std::collections::{BTreeMap, BTreeSet};
use proc_macro2::{Span, TokenStream as TokenStream2, TokenTree};
use quote::{quote, quote_spanned};
use syn::visit_mut::VisitMut;
use syn::{Ident, Type};
use crate::model::ImplHost;
use crate::types::{is_str_ref_type, is_string_type};
pub(crate) fn lifetime_names(tokens: TokenStream2, out: &mut BTreeSet<String>) {
let mut after_quote = false;
for tree in tokens {
match tree {
TokenTree::Punct(p) => {
after_quote = p.as_char() == '\'' && p.spacing() == proc_macro2::Spacing::Joint;
continue;
}
TokenTree::Ident(i) if after_quote => {
out.insert(i.to_string());
}
TokenTree::Group(g) => lifetime_names(g.stream(), out),
_ => {}
}
after_quote = false;
}
}
fn names_of(tokens: TokenStream2) -> BTreeSet<String> {
let mut out = BTreeSet::new();
lifetime_names(tokens, &mut out);
out
}
fn lifetime_part(generics: &syn::Generics) -> (Vec<syn::GenericParam>, Vec<syn::WherePredicate>) {
let params: Vec<syn::GenericParam> = generics
.params
.iter()
.filter(|p| matches!(p, syn::GenericParam::Lifetime(_)))
.cloned()
.collect();
let predicates = if params.len() == generics.params.len() {
generics
.where_clause
.iter()
.flat_map(|w| w.predicates.iter().cloned())
.collect()
} else {
Vec::new()
};
(params, predicates)
}
fn generics_of(
params: Vec<syn::GenericParam>,
predicates: Vec<syn::WherePredicate>,
) -> syn::Generics {
syn::Generics {
lt_token: (!params.is_empty()).then(Default::default),
gt_token: (!params.is_empty()).then(Default::default),
params: params.into_iter().collect(),
where_clause: (!predicates.is_empty()).then(|| syn::WhereClause {
where_token: Default::default(),
predicates: predicates.into_iter().collect(),
}),
}
}
pub(crate) fn wrapper_environment(host: Option<&ImplHost>, item: &syn::Generics) -> syn::Generics {
let (mut params, mut predicates) = host.map(|h| lifetime_part(&h.generics)).unwrap_or_default();
let (item_params, item_predicates) = lifetime_part(item);
params.extend(item_params);
predicates.extend(item_predicates);
generics_of(params, predicates)
}
struct SelfAlias<'h> {
host: &'h ImplHost,
out_of_scope: Option<Span>,
}
fn starts_with_self(qself: &Option<syn::QSelf>, path: &syn::Path) -> bool {
qself.is_none()
&& path.leading_colon.is_none()
&& path
.segments
.first()
.is_some_and(|s| s.ident == "Self" && s.arguments.is_none())
}
impl<'h> SelfAlias<'h> {
fn new(host: &'h ImplHost) -> Self {
SelfAlias {
host,
out_of_scope: None,
}
}
fn qualified(&mut self, path: &syn::Path, expression: bool) -> Option<syn::TypePath> {
let mut rest: syn::punctuated::Punctuated<syn::PathSegment, syn::Token![::]> =
path.segments.iter().skip(1).cloned().collect();
if rest.is_empty() {
return None;
}
for segment in rest.iter_mut() {
self.visit_path_segment_mut(segment);
}
let self_ty = &self.host.self_ty;
match &self.host.trait_ {
Some(trait_path) if !expression => {
Some(syn::parse_quote!(<#self_ty as #trait_path>::#rest))
}
Some(trait_path)
if trait_path.leading_colon.is_some() || trait_path.segments.len() > 1 =>
{
if self.out_of_scope.is_none() {
self.out_of_scope = path.segments.first().map(|s| s.ident.span());
}
None
}
_ => Some(syn::parse_quote!(<#self_ty>::#rest)),
}
}
fn header_path(&self) -> Option<syn::Path> {
match &self.host.self_ty {
Type::Path(tp) if tp.qself.is_none() => Some(tp.path.clone()),
_ => None,
}
}
fn alias_path(&mut self, qself: &mut Option<syn::QSelf>, path: &mut syn::Path) -> bool {
if !starts_with_self(qself, path) {
return false;
}
if path.segments.len() > 1 {
return match self.qualified(path, true) {
Some(qualified) => {
*qself = qualified.qself;
*path = qualified.path;
true
}
None => false,
};
}
match self.header_path() {
Some(header) => {
*path = header;
true
}
None => false,
}
}
}
impl VisitMut for SelfAlias<'_> {
fn visit_type_mut(&mut self, ty: &mut Type) {
if let Type::Path(tp) = ty {
if starts_with_self(&tp.qself, &tp.path) {
*ty = match self.qualified(&tp.path, false) {
Some(qualified) => Type::Path(qualified),
None => self.host.self_ty.clone(),
};
return;
}
}
syn::visit_mut::visit_type_mut(self, ty);
}
fn visit_expr_path_mut(&mut self, expr: &mut syn::ExprPath) {
if !self.alias_path(&mut expr.qself, &mut expr.path) {
syn::visit_mut::visit_expr_path_mut(self, expr);
}
}
fn visit_expr_struct_mut(&mut self, expr: &mut syn::ExprStruct) {
if self.alias_path(&mut expr.qself, &mut expr.path) {
for field in expr.fields.iter_mut() {
self.visit_field_value_mut(field);
}
if let Some(rest) = expr.rest.as_mut() {
self.visit_expr_mut(rest);
}
} else {
syn::visit_mut::visit_expr_struct_mut(self, expr);
}
}
}
pub(crate) fn expand_self_in_type(host: &ImplHost, ty: &mut Type) -> Option<Span> {
let mut alias = SelfAlias::new(host);
alias.visit_type_mut(ty);
alias.out_of_scope
}
pub(crate) fn expand_self_in_signature(host: &ImplHost, sig: &mut syn::Signature) {
SelfAlias::new(host).visit_signature_mut(sig);
}
pub(crate) fn expand_self(host: &ImplHost, generics: &mut syn::Generics) -> Option<Span> {
let mut alias = SelfAlias::new(host);
alias.visit_generics_mut(generics);
alias.out_of_scope
}
pub(crate) fn out_of_scope_error(span: Span, host: &ImplHost, julia_name: &str) -> TokenStream2 {
let trait_path = host.trait_.as_ref().map(readable_path).unwrap_or_default();
let self_ty = &host.self_ty;
let self_ty = readable(quote! { #self_ty });
let msg = format!(
"`{julia_name}`: an unqualified `Self::…` constant here resolves as \
`<{self_ty}>::…` — inherent first, then through the traits in scope — and \
the `extern \"C\"` wrapper cannot tell whether `{trait_path}` is in scope where it \
is emitted. Write `<Self as {trait_path}>::…` for the trait's constant, or \
`{self_ty}::…` for an inherent one, or import the trait and name it by its bare \
name in the impl header (#482)."
);
quote_spanned! {span=> compile_error!(#msg); }
}
fn readable_path(path: &syn::Path) -> String {
readable(quote! { #path })
}
pub(crate) fn leftover_self(tokens: TokenStream2) -> Option<(Span, Option<String>)> {
fn find(tokens: TokenStream2, in_macro: &Option<String>) -> Option<(Span, Option<String>)> {
let trees: Vec<TokenTree> = tokens.into_iter().collect();
for (i, tree) in trees.iter().enumerate() {
match tree {
TokenTree::Ident(id) if id == "Self" => {
return Some((id.span(), in_macro.clone()));
}
TokenTree::Group(g) => {
let before = |back: usize| i.checked_sub(back).map(|j| &trees[j]);
let called = match (before(2), before(1)) {
(Some(TokenTree::Ident(name)), Some(TokenTree::Punct(bang)))
if bang.as_char() == '!' =>
{
Some(format!("{name}!"))
}
_ => None,
};
let scope = in_macro.clone().or(called);
if let Some(found) = find(g.stream(), &scope) {
return Some(found);
}
}
_ => {}
}
}
None
}
find(tokens, &None)
}
pub(crate) fn leftover_self_error(
span: Span,
in_macro: Option<&str>,
julia_name: &str,
) -> TokenStream2 {
let msg = match in_macro {
Some(name) => format!(
"`{julia_name}`: this `Self` is inside an invocation of `{name}`, whose tokens are \
not a type until the macro has run, so RustCall cannot spell it as the impl's type \
on the `extern \"C\"` wrapper, which is a free function. Write the type instead of \
`Self` here (#482)."
),
None => format!(
"`{julia_name}`: RustCall does not spell a `Self` in this position as the impl's \
type, and the `extern \"C\"` wrapper, a free function, has no `Self`. Write the \
type instead of `Self` here (#482)."
),
};
quote_spanned! {span=> compile_error!(#msg); }
}
pub(crate) fn prune_unused_lifetimes(
environment: syn::Generics,
signature: TokenStream2,
) -> syn::Generics {
let mut named = names_of(signature);
for param in &environment.params {
if let syn::GenericParam::Lifetime(lp) = param {
for bound in &lp.bounds {
named.insert(bound.ident.to_string());
}
}
}
let predicates: Vec<syn::WherePredicate> = environment
.where_clause
.iter()
.flat_map(|w| w.predicates.iter().cloned())
.collect();
for predicate in &predicates {
lifetime_names(quote! { #predicate }, &mut named);
}
let params = environment
.params
.into_iter()
.filter(|p| match p {
syn::GenericParam::Lifetime(lp) => named.contains(&lp.lifetime.ident.to_string()),
_ => true,
})
.collect();
generics_of(params, predicates)
}
fn readable(tokens: TokenStream2) -> String {
let unparse = |item: syn::Item| {
prettyplease::unparse(&syn::File {
shebang: None,
attrs: Vec::new(),
items: vec![item],
})
};
if let Ok(ty) = syn::parse2::<Type>(tokens.clone()) {
let text = unparse(syn::parse_quote!(type T = #ty;));
if let Some(body) = text.trim().strip_prefix("type T = ") {
return body.trim_end_matches(';').to_string();
}
}
if let Ok(predicate) = syn::parse2::<syn::WherePredicate>(tokens.clone()) {
let text = unparse(syn::parse_quote!(fn f() where #predicate {}));
let body: Vec<&str> = text
.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && *l != "where" && !l.starts_with("fn f()") && *l != "{}")
.collect();
return body.join(" ").trim_end_matches(',').to_string();
}
tokens.to_string()
}
fn fixed_reason(name: &str, fixed: &BTreeMap<String, String>) -> Option<String> {
if name == "static" {
return Some("`'static` outlives every call".to_string());
}
fixed.get(name).cloned()
}
pub(crate) fn lowered_lifetime_error(
environment: &syn::Generics,
args: &[(Ident, Type)],
returned: &[TokenStream2],
julia_name: &str,
) -> Option<TokenStream2> {
let params: BTreeSet<String> = environment
.lifetimes()
.map(|lp| lp.lifetime.ident.to_string())
.collect();
let mut outlives: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
let mut edge = |from: &syn::Lifetime, to: &syn::Lifetime| {
outlives
.entry(from.ident.to_string())
.or_default()
.insert(to.ident.to_string());
};
for lp in environment.lifetimes() {
for bound in &lp.bounds {
edge(&lp.lifetime, bound);
}
}
let mut fixed: BTreeMap<String, String> = BTreeMap::new();
let mut fix = |names: BTreeSet<String>, reason: &dyn Fn() -> String| {
for name in names.into_iter().filter(|n| params.contains(n)) {
fixed.entry(name).or_insert_with(reason);
}
};
for predicate in environment
.where_clause
.iter()
.flat_map(|w| w.predicates.iter())
{
match predicate {
syn::WherePredicate::Lifetime(pl) => {
for bound in &pl.bounds {
edge(&pl.lifetime, bound);
}
}
syn::WherePredicate::Type(pt) => {
let mut strict = names_of(quote! { #pt });
for bound in &pt.bounds {
if let syn::TypeParamBound::Lifetime(l) = bound {
let elsewhere = {
let ty = &pt.bounded_ty;
let others = pt.bounds.iter().filter(|b| {
!matches!(b, syn::TypeParamBound::Lifetime(o) if o.ident == l.ident)
});
let binder = &pt.lifetimes;
names_of(quote! { #binder #ty #(#others)* })
};
if !elsewhere.contains(&l.ident.to_string()) {
strict.remove(&l.ident.to_string());
}
}
}
let spelled = readable(quote! { #pt });
fix(strict, &|| {
format!("the `where` predicate `{spelled}` names it")
});
}
_ => {}
}
}
let mut lowered: Vec<(&Ident, &syn::Lifetime)> = Vec::new();
for (name, ty) in args {
if is_str_ref_type(ty) {
if let Type::Reference(r) = crate::types::unparen(ty) {
if let Some(l) = &r.lifetime {
lowered.push((name, l));
}
}
continue;
}
if is_string_type(ty) {
continue;
}
let inner = match crate::types::unparen(ty) {
Type::Reference(r) => {
let elem = &r.elem;
quote! { #elem }
}
other => quote! { #other },
};
let spelled = readable(quote! { #ty });
fix(names_of(inner), &|| {
format!("argument `{name}: {spelled}` names it inside its type")
});
}
for ty in returned {
let spelled = readable(ty.clone());
fix(names_of(ty.clone()), &|| {
format!("the wrapper returns `{spelled}`, which names it")
});
}
for (arg, lifetime) in lowered {
let start = lifetime.ident.to_string();
let mut seen: BTreeSet<String> = BTreeSet::new();
let mut queue = vec![(start.clone(), Vec::<String>::new())];
while let Some((name, via)) = queue.pop() {
if !seen.insert(name.clone()) {
continue;
}
if let Some(reason) = fixed_reason(&name, &fixed) {
let why = if via.is_empty() {
format!("but {reason}")
} else {
let mut steps = vec![format!("'{start}")];
steps.extend(via.iter().map(|n| format!("'{n}")));
format!(
"but it must outlive `'{name}` (`{}`), and {reason}",
steps.join(": ")
)
};
let msg = if start == "static" {
format!(
"`{julia_name}`: argument `{arg}` arrives from Julia as a pointer and a \
length and is rebuilt into a string that lives only for the call, so it \
cannot be borrowed for `'static`. Take `String` (#482)."
)
} else {
format!(
"`{julia_name}`: argument `{arg}` arrives from Julia as a pointer and a \
length and is rebuilt into a string that lives only for the call, so \
`'{start}` cannot be required to outlive the call; {why}. Take `String`, \
or relate `'{start}` to nothing that outlives the call (#482)."
)
};
let span = lifetime.ident.span();
return Some(quote_spanned! {span=> compile_error!(#msg); });
}
for next in outlives.get(&name).into_iter().flatten() {
let mut via = via.clone();
via.push(next.clone());
queue.push((next.clone(), via));
}
}
}
None
}
struct Positions<'l> {
rename: Option<&'l syn::Lifetime>,
elided: Vec<Span>,
named: BTreeSet<String>,
}
impl Positions<'_> {
fn lifetime(&mut self, lifetime: &mut syn::Lifetime) {
if lifetime.ident == "_" {
self.elided.push(lifetime.span());
if let Some(name) = self.rename {
*lifetime = name.clone();
}
} else {
self.named.insert(lifetime.ident.to_string());
}
}
}
impl VisitMut for Positions<'_> {
fn visit_type_reference_mut(&mut self, r: &mut syn::TypeReference) {
match &mut r.lifetime {
Some(lifetime) => self.lifetime(lifetime),
None => {
self.elided.push(r.and_token.span);
r.lifetime = self.rename.cloned();
}
}
self.visit_type_mut(&mut r.elem);
}
fn visit_lifetime_mut(&mut self, lifetime: &mut syn::Lifetime) {
self.lifetime(lifetime);
}
fn visit_type_bare_fn_mut(&mut self, _: &mut syn::TypeBareFn) {}
fn visit_parenthesized_generic_arguments_mut(
&mut self,
_: &mut syn::ParenthesizedGenericArguments,
) {
}
fn visit_trait_bound_mut(&mut self, bound: &mut syn::TraitBound) {
if bound.lifetimes.is_none() {
syn::visit_mut::visit_trait_bound_mut(self, bound);
}
}
}
fn positions(ty: &mut Type, rename: Option<&syn::Lifetime>) -> (Vec<Span>, BTreeSet<String>) {
let mut p = Positions {
rename,
elided: Vec::new(),
named: BTreeSet::new(),
};
p.visit_type_mut(ty);
(p.elided, p.named)
}
pub(crate) fn has_elided_lifetime(ty: &Type) -> bool {
!positions(&mut ty.clone(), None).0.is_empty()
}
pub(crate) fn name_elided_lifetimes(ty: &mut Type, lifetime: &syn::Lifetime) {
positions(ty, Some(lifetime));
}
#[derive(Clone, Debug)]
pub(crate) enum SelfBorrow {
None,
Ref(Option<syn::Lifetime>),
}
impl SelfBorrow {
pub(crate) fn of(receiver: &syn::Receiver) -> Self {
match crate::types::unparen(&receiver.ty) {
Type::Reference(r) => SelfBorrow::Ref(r.lifetime.clone().filter(|l| l.ident != "_")),
_ => SelfBorrow::None,
}
}
}
pub(crate) fn fresh_lifetime(spelled: TokenStream2) -> syn::Lifetime {
let taken = names_of(spelled);
let name = std::iter::once("rustcall".to_string())
.chain((1..).map(|n| format!("rustcall{n}")))
.find(|n| !taken.contains(n))
.expect("an unbounded sequence has a free name");
syn::Lifetime::new(&format!("'{name}"), Span::call_site())
}
pub(crate) enum ElidedReturn {
Named,
Undecidable,
Refused(TokenStream2),
}
pub(crate) fn name_elided_return(
environment: &mut syn::Generics,
receiver: &SelfBorrow,
args: &mut [(Ident, Type)],
returned: Vec<&mut Type>,
julia_name: &str,
) -> ElidedReturn {
if !returned.iter().any(|ty| has_elided_lifetime(ty)) {
return ElidedReturn::Named;
}
let fresh = {
let predicates = &environment.where_clause;
let arg_types = args.iter().map(|(_, ty)| ty);
let returned = &returned;
fresh_lifetime(quote! { #environment #predicates #(#arg_types)* #(#returned)* })
};
let declare = |environment: &mut syn::Generics, lifetime: &syn::Lifetime| {
environment
.params
.push(syn::GenericParam::Lifetime(syn::LifetimeParam::new(
lifetime.clone(),
)));
environment.lt_token.get_or_insert_with(Default::default);
environment.gt_token.get_or_insert_with(Default::default);
};
let lifetime = match receiver {
SelfBorrow::Ref(Some(named)) => named.clone(),
SelfBorrow::Ref(None) => {
declare(environment, &fresh);
fresh
}
SelfBorrow::None => {
let mut elided: Vec<(usize, Span)> = Vec::new();
let mut named: BTreeSet<String> = BTreeSet::new();
for (i, (_, ty)) in args.iter().enumerate() {
let (spans, names) = positions(&mut ty.clone(), None);
elided.extend(spans.into_iter().map(|s| (i, s)));
named.extend(names);
}
match (elided.as_slice(), named.len()) {
([], 1) => {
let name = named.into_iter().next().expect("one name");
syn::Lifetime::new(&format!("'{name}"), Span::call_site())
}
([(i, span)], 0) => {
let (arg, ty) = &mut args[*i];
if is_str_ref_type(ty) {
let msg = format!(
"`{julia_name}`: the returned reference borrows from argument `{arg}` \
by lifetime elision, but `{arg}` arrives from Julia as a pointer and \
a length and is rebuilt into a string that lives only for the call, \
so nothing borrowed from it can be returned. Return an owned value, \
or give the returned reference a lifetime that does not come from \
`{arg}` (#484)."
);
let span = *span;
return ElidedReturn::Refused(
quote_spanned! {span=> compile_error!(#msg); },
);
}
name_elided_lifetimes(ty, &fresh);
declare(environment, &fresh);
fresh
}
([], 0) => return ElidedReturn::Named,
_ => return ElidedReturn::Undecidable,
}
}
};
for ty in returned {
name_elided_lifetimes(ty, &lifetime);
}
ElidedReturn::Named
}