Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hackily support non-'static lifetimes #117

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion macros/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ proc-macro = true
[dependencies]
proc-macro2 = "1"
quote = "1"
syn = { version = "1", features = ["full", "extra-traits"] }
syn = { version = "1", features = ["full", "extra-traits", "visit-mut"] }
Inflector = { version = "0.11", default-features = false }
termcolor = { version = "1", optional = true }
16 changes: 6 additions & 10 deletions macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,30 +112,26 @@ impl DerivedTS {
fn generate_impl(ty: &Ident, generics: &Generics) -> TokenStream {
use GenericParam::*;

let bounds = generics.params.iter().map(|param| match param {
let bounds = generics.params.iter().filter_map(|param| match param {
Type(TypeParam {
ident,
colon_token,
bounds,
..
}) => quote!(#ident #colon_token #bounds),
Lifetime(LifetimeDef {
lifetime,
colon_token,
bounds,
..
}) => quote!(#lifetime #colon_token #bounds),
}) => Some(quote!(#ident #colon_token #bounds)),
// Filter out all lifetime param quantifiers, because we replace them with 'static.
Lifetime(LifetimeDef { .. }) => None,
Const(ConstParam {
const_token,
ident,
colon_token,
ty,
..
}) => quote!(#const_token #ident #colon_token #ty),
}) => Some(quote!(#const_token #ident #colon_token #ty)),
});
let type_args = generics.params.iter().map(|param| match param {
Type(TypeParam { ident, .. }) | Const(ConstParam { ident, .. }) => quote!(#ident),
Lifetime(LifetimeDef { lifetime, .. }) => quote!(#lifetime),
Lifetime(LifetimeDef { .. }) => quote!('static),
});

let where_bound = add_ts_to_where_clause(generics);
Expand Down
43 changes: 38 additions & 5 deletions macros/src/types/generics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,44 @@ pub fn format_generics(deps: &mut Dependencies, generics: &Generics) -> TokenStr
_ => None,
});

let comma_separated = quote!(vec![#(#expanded_params),*].join(", "));
let comma_separated = quote!({
let v: Vec<String> = vec![#(#expanded_params),*];
v.join(", ")
});
quote!(format!("<{}>", #comma_separated))
}

pub fn format_type(ty: &Type, dependencies: &mut Dependencies, generics: &Generics) -> TokenStream {
// Remap all lifetimes to 'static in ty.
struct Visitor;
impl syn::visit_mut::VisitMut for Visitor {
fn visit_type_mut(&mut self, ty: &mut Type) {
match ty {
Type::Reference(ref_type) => {
ref_type.lifetime = ref_type
.lifetime
.as_ref()
.map(|_| syn::parse2(quote!('static)).unwrap());
}
_ => {}
}
syn::visit_mut::visit_type_mut(self, ty);
}

fn visit_generic_argument_mut(&mut self, ga: &mut GenericArgument) {
match ga {
GenericArgument::Lifetime(lt) => {
*lt = syn::parse2(quote!('static)).unwrap();
}
_ => {}
}
syn::visit_mut::visit_generic_argument_mut(self, ga);
}
}
use syn::visit_mut::VisitMut;
let mut ty = ty.clone();
Visitor.visit_type_mut(&mut ty);

// If the type matches one of the generic parameters, just pass the identifier:
if let Some(generic_ident) = generics
.params
Expand All @@ -42,7 +75,7 @@ pub fn format_type(ty: &Type, dependencies: &mut Dependencies, generics: &Generi
})
.find(|type_param| {
matches!(
ty,
&ty,
Type::Path(type_path)
if type_path.qself.is_none()
&& type_path.path.is_ident(&type_param.ident)
Expand All @@ -69,7 +102,7 @@ pub fn format_type(ty: &Type, dependencies: &mut Dependencies, generics: &Generi
let tuple_struct = super::type_def(
&StructAttr::default(),
&format_ident!("_"),
&tuple_type_to_tuple_struct(tuple).fields,
&tuple_type_to_tuple_struct(&tuple).fields,
generics,
)
.unwrap();
Expand All @@ -80,8 +113,8 @@ pub fn format_type(ty: &Type, dependencies: &mut Dependencies, generics: &Generi
_ => (),
};

dependencies.push_or_append_from(ty);
match extract_type_args(ty) {
dependencies.push_or_append_from(&ty);
match extract_type_args(&ty) {
None => quote!(<#ty as ts_rs::TS>::name()),
Some(type_args) => {
let args = type_args
Expand Down
23 changes: 23 additions & 0 deletions ts-rs/tests/generics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,3 +212,26 @@ fn trait_bounds() {

assert_eq!(D::<&str, 41>::decl(), "interface D<T> { t: Array<T>, }")
}

#[test]
fn nonstatic_lifetimes() {
#[derive(TS)]
struct A<'a> {
t: &'a str,
}
assert_eq!(A::decl(), "interface A<> { t: string, }");
}

#[test]
fn nonstatic_lifetimes_with_child() {
#[derive(TS)]
struct A<'a> {
t: &'a str,
}

#[derive(TS)]
struct B<'a> {
t: A<'a>,
}
assert_eq!(B::decl(), "interface B<> { t: A, }");
}