use crate::conversion::analysis::fun::{ArgumentAnalysis, ReceiverMutability};
use proc_macro2::TokenStream;
use quote::quote;
use std::borrow::Cow;
use syn::{
parse_quote, punctuated::Punctuated, token::Comma, FnArg, GenericArgument, PatType, Path,
PathSegment, ReturnType, Type, TypePath,
};
pub(crate) fn add_explicit_lifetime_if_necessary<'r>(
param_details: &[ArgumentAnalysis],
mut params: Punctuated<FnArg, Comma>,
ret_type: &'r ReturnType,
) -> (
Option<TokenStream>,
Punctuated<FnArg, Comma>,
Cow<'r, ReturnType>,
) {
let has_mutable_receiver = param_details
.iter()
.any(|pd| matches!(pd.self_type, Some((_, ReceiverMutability::Mutable))));
if !has_mutable_receiver {
return (None, params, Cow::Borrowed(ret_type));
}
let new_return_type = match ret_type {
ReturnType::Type(rarrow, boxed_type) => match boxed_type.as_ref() {
Type::Reference(rtr) => {
let mut new_rtr = rtr.clone();
new_rtr.lifetime = Some(parse_quote! { 'a });
Some(ReturnType::Type(
*rarrow,
Box::new(Type::Reference(new_rtr)),
))
}
_ => None,
},
_ => None,
};
match new_return_type {
None => (None, params, Cow::Borrowed(ret_type)),
Some(new_return_type) => {
for mut param in params.iter_mut() {
match &mut param {
FnArg::Typed(PatType { ty, .. }) => match ty.as_mut() {
Type::Path(TypePath {
path: Path { segments, .. },
..
}) => add_lifetime_to_pinned_reference(segments),
_ => panic!("Expected Pin<T>"),
},
_ => panic!("Unexpected fnarg"),
}
}
(Some(quote! { <'a> }), params, Cow::Owned(new_return_type))
}
}
}
fn add_lifetime_to_pinned_reference(segments: &mut Punctuated<PathSegment, syn::token::Colon2>) {
static EXPECTED_SEGMENTS: &[(&str, bool)] = &[
("std", false),
("pin", false),
("Pin", true), ];
for (seg, (expected_name, act)) in segments.iter_mut().zip(EXPECTED_SEGMENTS.iter()) {
assert!(seg.ident == expected_name);
if *act {
match &mut seg.arguments {
syn::PathArguments::AngleBracketed(aba) => match aba.args.iter_mut().next() {
Some(GenericArgument::Type(Type::Reference(tyr))) => {
tyr.lifetime = Some(parse_quote! { 'a })
}
_ => panic!("Expected generic args with a reference"),
},
_ => panic!("Expected angle bracketed args"),
}
}
}
}