properly handle generics in all contexts

This commit is contained in:
Moritz Bischof
2021-11-01 23:31:20 +01:00
parent e2a88635a1
commit 98edb48eef
10 changed files with 173 additions and 68 deletions
+45
View File
@@ -0,0 +1,45 @@
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::Type;
#[derive(Default)]
pub struct Dependencies(Vec<TokenStream>);
impl Dependencies {
/// Adds all dependencies from the given type
pub fn append_from(&mut self, ty: &Type) {
self.0
.push(quote!(dependencies.append(&mut <#ty as ts_rs::TS>::dependencies());));
}
/// Adds the given type if it's *not* transparent.
/// If it is, all it's child dependencies are added instead.
pub fn push_or_append_from(&mut self, ty: &Type) {
self.0.push(quote! {
if <#ty as ts_rs::TS>::transparent() {
dependencies.append(&mut <#ty as ts_rs::TS>::dependencies());
} else {
dependencies.push((std::any::TypeId::of::<#ty>(), <#ty as ts_rs::TS>::name()));
}
});
}
pub fn append(&mut self, other: Dependencies) {
self.0.push(quote! {
dependencies.append(&mut #other)
})
}
}
impl ToTokens for Dependencies {
fn to_tokens(&self, tokens: &mut TokenStream) {
let dependencies = &self.0;
tokens.extend(quote! {
{
let mut dependencies = vec![];
#( #dependencies )*
dependencies
}
})
}
}
+3 -1
View File
@@ -4,18 +4,20 @@
use proc_macro2::{Ident, TokenStream};
use quote::quote;
use syn::{parse_quote, spanned::Spanned, GenericParam, Generics, Item, Result, WhereClause};
use crate::deps::Dependencies;
#[macro_use]
mod utils;
mod attr;
mod types;
mod deps;
struct DerivedTS {
name: String,
inline: TokenStream,
decl: TokenStream,
inline_flattened: Option<TokenStream>,
dependencies: TokenStream,
dependencies: Dependencies,
}
impl DerivedTS {
+3 -8
View File
@@ -1,10 +1,11 @@
use proc_macro2::TokenStream;
use quote::quote;
use syn::{GenericArgument, GenericParam, Generics, PathArguments, Type};
use crate::deps::Dependencies;
pub fn format_type(
ty: &Type,
dependencies: &mut Vec<TokenStream>,
dependencies: &mut Dependencies,
generics: &Generics,
) -> TokenStream {
// If the type matches one of the generic parameters, just pass the identifier:
@@ -28,13 +29,7 @@ pub fn format_type(
return quote!(#generic_ident.to_owned());
}
dependencies.push(quote! {
if <#ty as ts_rs::TS>::transparent() {
dependencies.append(&mut <#ty as ts_rs::TS>::dependencies());
} else {
dependencies.push((std::any::TypeId::of::<#ty>(), <#ty as ts_rs::TS>::name()));
}
});
dependencies.push_or_append_from(ty);
match extract_type_args(ty) {
None => quote!(<#ty as ts_rs::TS>::name()),
+7 -11
View File
@@ -8,6 +8,7 @@ use crate::{
utils::to_ts_ident,
DerivedTS,
};
use crate::deps::Dependencies;
mod generics;
mod named;
@@ -35,8 +36,8 @@ fn type_def(
},
Fields::Unnamed(unnamed) => match unnamed.unnamed.len() {
0 => unit::unit(name, rename_all),
1 => newtype::newtype(name, rename_all, unnamed),
_ => tuple::tuple(name, rename_all, unnamed),
1 => newtype::newtype(name, rename_all, unnamed, generics),
_ => tuple::tuple(name, rename_all, unnamed, generics),
},
Fields::Unit => unit::unit(name, rename_all),
}
@@ -51,7 +52,7 @@ pub(crate) fn r#enum(s: &ItemEnum) -> Result<DerivedTS> {
};
let mut formatted_variants = vec![];
let mut dependencies = vec![];
let mut dependencies = Dependencies::default();
for variant in &s.variants {
format_variant(
&mut formatted_variants,
@@ -65,18 +66,14 @@ pub(crate) fn r#enum(s: &ItemEnum) -> Result<DerivedTS> {
inline: quote!(vec![#(#formatted_variants),*].join(" | ")),
decl: quote!(format!("type {} = {};", #name, Self::inline(0))),
inline_flattened: None,
dependencies: quote! {
let mut dependencies = vec![];
#( #dependencies )*
dependencies
},
dependencies,
name,
})
}
fn format_variant(
formatted_variants: &mut Vec<TokenStream>,
dependencies: &mut Vec<TokenStream>,
dependencies: &mut Dependencies,
enum_attr: &EnumAttr,
variant: &Variant,
) -> Result<()> {
@@ -144,8 +141,7 @@ fn format_variant(
}
Fields::Unit => quote!(format!("{{ {}: \"{}\" }}", #tag, #name)),
_ => {
dependencies
.push(quote!(dependencies.append(&mut #variant_dependencies);));
dependencies.append(variant_dependencies);
quote!(format!("{{ {}: \"{}\" }} & {}", #tag, #name, #inline_type))
}
},
+6 -10
View File
@@ -10,6 +10,7 @@ use crate::{
utils::to_ts_ident,
DerivedTS,
};
use crate::deps::Dependencies;
pub(crate) fn named(
name: &str,
@@ -18,7 +19,7 @@ pub(crate) fn named(
generics: &Generics,
) -> Result<DerivedTS> {
let mut formatted_fields = vec![];
let mut dependencies = vec![];
let mut dependencies = Dependencies::default();
for field in &fields.named {
format_field(
&mut formatted_fields,
@@ -56,18 +57,14 @@ pub(crate) fn named(
decl: quote!(format!("interface {}{} {}", #name, #generic_args, Self::inline(0))),
inline_flattened: Some(fields),
name: name.to_owned(),
dependencies: quote! {
let mut dependencies = vec![];
#( #dependencies )*
dependencies
},
dependencies
})
}
// build an expresion which expands to a string, representing a single field of a struct.
fn format_field(
formatted_fields: &mut Vec<TokenStream>,
dependencies: &mut Vec<TokenStream>,
dependencies: &mut Dependencies,
field: &Field,
rename_all: &Option<Inflection>,
generics: &Generics,
@@ -99,14 +96,13 @@ fn format_field(
}
formatted_fields.push(quote!(<#ty as ts_rs::TS>::inline_flattened(indent)));
dependencies.push(quote!(dependencies.append(&mut <#ty as ts_rs::TS>::dependencies());));
dependencies.append_from(ty);
return Ok(());
}
let formatted_ty = type_override.map(|t| quote!(#t)).unwrap_or_else(|| {
if inline {
dependencies
.push(quote!(dependencies.append(&mut <#ty as ts_rs::TS>::dependencies());));
dependencies.append_from(ty);
quote!(<#ty as ts_rs::TS>::inline(indent + 1))
} else {
format_type(ty, dependencies, generics)
+13 -14
View File
@@ -1,8 +1,10 @@
use quote::quote;
use syn::{FieldsUnnamed, Result};
use syn::{FieldsUnnamed, Generics, Result};
use crate::{
attr::{FieldAttr, Inflection},
deps::Dependencies,
types::generics::format_type,
DerivedTS,
};
@@ -10,6 +12,7 @@ pub(crate) fn newtype(
name: &str,
rename_all: &Option<Inflection>,
fields: &FieldsUnnamed,
generics: &Generics,
) -> Result<DerivedTS> {
if rename_all.is_some() {
syn_err!("`rename_all` is not applicable to newtype structs");
@@ -33,27 +36,23 @@ pub(crate) fn newtype(
};
let inner_ty = &inner.ty;
let mut dependencies = Dependencies::default();
match (inline, &type_override) {
(_, Some(_)) => (),
(true, _) => dependencies.append_from(inner_ty),
(false, _) => dependencies.push_or_append_from(inner_ty),
};
let inline_def = match &type_override {
Some(o) => quote!(#o),
None if inline => quote!(<#inner_ty as ts_rs::TS>::inline(0)),
None => quote!(<#inner_ty as ts_rs::TS>::name()),
None => format_type(inner_ty, &mut dependencies, generics),
};
Ok(DerivedTS {
decl: quote!(format!("type {} = {};", #name, #inline_def)),
inline: inline_def,
inline_flattened: None,
name: name.to_owned(),
dependencies: match (inline, &type_override) {
(_, Some(_)) => quote!(vec![]),
(true, _) => quote! {
<#inner_ty as ts_rs::TS>::dependencies()
},
(false, _) => quote! {
match <#inner_ty as ts_rs::TS>::transparent() {
true => <#inner_ty as ts_rs::TS>::dependencies(),
false => vec![(std::any::TypeId::of::<#inner_ty>(), <#inner_ty as ts_rs::TS>::name())]
}
},
},
dependencies,
})
}
+19 -23
View File
@@ -1,25 +1,28 @@
use proc_macro2::TokenStream;
use quote::quote;
use syn::{Field, FieldsUnnamed, Result};
use syn::{Field, FieldsUnnamed, Generics, Result};
use crate::{
attr::{FieldAttr, Inflection},
deps::Dependencies,
DerivedTS,
};
use crate::types::generics::format_type;
pub(crate) fn tuple(
name: &str,
rename_all: &Option<Inflection>,
fields: &FieldsUnnamed,
generics: &Generics,
) -> Result<DerivedTS> {
if rename_all.is_some() {
syn_err!("`rename_all` is not applicable to tuple structs");
}
let mut formatted_fields = Vec::new();
let mut dependencies = Vec::new();
let mut dependencies = Dependencies::default();
for field in &fields.unnamed {
format_field(&mut formatted_fields, &mut dependencies, field)?;
format_field(&mut formatted_fields, &mut dependencies, field, generics)?;
}
Ok(DerivedTS {
@@ -38,18 +41,15 @@ pub(crate) fn tuple(
},
inline_flattened: None,
name: name.to_owned(),
dependencies: quote! {
let mut dependencies = vec![];
#( #dependencies )*
dependencies
},
dependencies,
})
}
fn format_field(
formatted_fields: &mut Vec<TokenStream>,
dependencies: &mut Vec<TokenStream>,
dependencies: &mut Dependencies,
field: &Field,
generics: &Generics,
) -> Result<()> {
let ty = &field.ty;
let FieldAttr {
@@ -77,22 +77,18 @@ fn format_field(
formatted_fields.push(match &type_override {
Some(o) => quote!(#o.to_owned()),
None if inline => quote!(<#ty as ts_rs::TS>::inline(0)),
None => quote!(<#ty as ts_rs::TS>::name()),
None => format_type(ty, dependencies, generics),
});
dependencies.push(match (inline, &type_override) {
(_, Some(_)) => quote!(),
(false, _) => quote! {
if <#ty as ts_rs::TS>::transparent() {
dependencies.append(&mut <#ty as ts_rs::TS>::dependencies());
} else {
dependencies.push((std::any::TypeId::of::<#ty>(), <#ty as ts_rs::TS>::name()));
}
},
(true, _) => quote! {
dependencies.append(&mut (<#ty as ts_rs::TS>::dependencies()));
},
});
match (inline, &type_override) {
(_, Some(_)) => (),
(false, _) => {
dependencies.push_or_append_from(ty);
}
(true, _) => {
dependencies.append_from(ty);
}
};
Ok(())
}
+2 -1
View File
@@ -2,6 +2,7 @@ use quote::quote;
use syn::Result;
use crate::{attr::Inflection, DerivedTS};
use crate::deps::Dependencies;
pub(crate) fn unit(name: &str, rename_all: &Option<Inflection>) -> Result<DerivedTS> {
if rename_all.is_some() {
@@ -13,6 +14,6 @@ pub(crate) fn unit(name: &str, rename_all: &Option<Inflection>) -> Result<Derive
decl: quote!(format!("type {} = null;", #name)),
inline_flattened: None,
name: name.to_owned(),
dependencies: quote!(vec![]),
dependencies: Dependencies::default(),
})
}
+5
View File
@@ -388,6 +388,11 @@ impl<T: TS> TS for Vec<T> {
"Array".to_owned()
}
fn name_with_type_args(args: Vec<String>) -> String {
assert_eq!(args.len(), 1);
format!("Array<{}>", args[0])
}
fn inline(indent: usize) -> String {
format!("Array<{}>", T::inline(indent))
}
+70
View File
@@ -0,0 +1,70 @@
#![allow(dead_code)]
use ts_rs::TS;
#[test]
fn newtype() {
#[derive(TS)]
struct Newtype(Vec<i32>);
assert_eq!(Newtype::inline(0), "Array<number>");
}
#[test]
fn newtype_nested() {
#[derive(TS)]
struct Newtype(Vec<Vec<i32>>);
assert_eq!(Newtype::inline(0), "Array<Array<number>>");
}
#[test]
fn alias() {
type Alias = Vec<String>;
assert_eq!(Alias::inline(0), "Array<string>");
}
#[test]
fn alias_nested() {
type Alias = Vec<Vec<String>>;
assert_eq!(Alias::inline(0), "Array<Array<string>>");
}
#[test]
fn named() {
#[derive(TS)]
struct Struct {
a: Vec<String>,
}
assert_eq!(
Struct::inline(0),
"{
a: Array<string>,
}"
);
}
#[test]
fn named_nested() {
#[derive(TS)]
struct Struct {
a: Vec<Vec<String>>,
}
assert_eq!(
Struct::inline(0),
"{
a: Array<Array<string>>,
}"
);
}
#[test]
fn tuple() {
#[derive(TS)]
struct Tuple(Vec<i32>, Vec<i32>);
assert_eq!(Tuple::inline(0), "[Array<number>, Array<number>]");
}
#[test]
fn tuple_nested() {
#[derive(TS)]
struct Tuple(Vec<Vec<i32>>, Vec<Vec<i32>>);
assert_eq!(Tuple::inline(0), "[Array<Array<number>>, Array<Array<number>>]");
}