From 029f7f6ccd807dc413a1edcc145d19d1c989d7a9 Mon Sep 17 00:00:00 2001 From: Samir Bioud Date: Wed, 11 Oct 2023 10:55:37 +0100 Subject: [PATCH 01/60] Feat: Added Result support --- ts-rs/src/lib.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/ts-rs/src/lib.rs b/ts-rs/src/lib.rs index a624cf6..b25c051 100644 --- a/ts-rs/src/lib.rs +++ b/ts-rs/src/lib.rs @@ -459,6 +459,23 @@ impl TS for Option { } } +impl TS for Result{ + fn name() -> String{ + unreachable!(); + } + fn transparent() -> bool { + return true; + } + fn dependencies() -> Vec + where + Self: 'static { + [Dependency::from_ty::()].into_iter().flatten().collect() + } + fn inline() -> String { + format!("{{ ok : {} }} | {{ err : {} }}", T::inline(), E::inline()) + } +} + impl TS for Vec { fn name() -> String { "Array".to_owned() From 23e2ba2d003ba04256a968a1ba4370cdbbcd6e3c Mon Sep 17 00:00:00 2001 From: Tim Date: Fri, 3 Nov 2023 12:56:01 +0100 Subject: [PATCH 02/60] feat: impl for semver:Version --- README.md | 3 +++ ts-rs/Cargo.toml | 2 ++ ts-rs/src/lib.rs | 6 ++++++ 3 files changed, 11 insertions(+) diff --git a/README.md b/README.md index ee26579..9dbd343 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,9 @@ When running `cargo test`, the TypeScript bindings will be exported to the file Implement `TS` for `Vec` from heapless +- `semver-impl` + Implement `TS` for `Version` from semver + If there's a type you're dealing with which doesn't implement `TS`, use `#[ts(type = "..")]` or open a PR. diff --git a/ts-rs/Cargo.toml b/ts-rs/Cargo.toml index 0457407..d50b2e1 100644 --- a/ts-rs/Cargo.toml +++ b/ts-rs/Cargo.toml @@ -24,6 +24,7 @@ default = ["serde-compat"] indexmap-impl = ["indexmap"] ordered-float-impl = ["ordered-float"] heapless-impl = ["heapless"] +semver-impl = ["semver"] [dev-dependencies] serde = { version = "1.0", features = ["derive"] } @@ -39,6 +40,7 @@ uuid = { version = "1.1.2", optional = true } bson = { version = "2.2.0", optional = true } bytes = { version = "1.0", optional = true } url = { version = "2.3", optional = true } +semver = { semver = "3.0.0", optional = true } thiserror = "1" indexmap = { version = "2.0.0", optional = true } ordered-float = { version = "3.0.0", optional = true } diff --git a/ts-rs/src/lib.rs b/ts-rs/src/lib.rs index a624cf6..d32f261 100644 --- a/ts-rs/src/lib.rs +++ b/ts-rs/src/lib.rs @@ -106,6 +106,9 @@ //! - `heapless-impl` //! //! Implement `TS` for `Vec` from heapless +//! +//! - `semver-impl` +//! Implement `TS` for `Version` from semver //! //! //! If there's a type you're dealing with which doesn't implement `TS`, use `#[ts(type = "..")]` or open a PR. @@ -623,6 +626,9 @@ impl_shadow!(as HashMap: impl TS for indexmap::IndexMap: impl TS for heapless::Vec); +#[cfg(feature = "semver-impl")] +impl_primitives! { semver::Version => "string" } + #[cfg(feature = "bytes-impl")] mod bytes { use super::TS; From a5c510ae39f9420c5a82754f2a46899aabf53385 Mon Sep 17 00:00:00 2001 From: Samir Bioud Date: Sat, 11 Nov 2023 12:20:50 +0000 Subject: [PATCH 03/60] Addressed issues mentioned by axos88 --- ts-rs/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ts-rs/src/lib.rs b/ts-rs/src/lib.rs index b25c051..92c6e52 100644 --- a/ts-rs/src/lib.rs +++ b/ts-rs/src/lib.rs @@ -469,10 +469,10 @@ impl TS for Result{ fn dependencies() -> Vec where Self: 'static { - [Dependency::from_ty::()].into_iter().flatten().collect() + [Dependency::from_ty::(), Dependency::from_ty::()].into_iter().flatten().collect() } fn inline() -> String { - format!("{{ ok : {} }} | {{ err : {} }}", T::inline(), E::inline()) + format!("{{ Ok : {} }} | {{ Err : {} }}", T::inline(), E::inline()) } } From 6e65117d4c310e9261c162e4b5a9f1bd893256a4 Mon Sep 17 00:00:00 2001 From: Tim Guggenmos Date: Wed, 29 Nov 2023 21:46:04 +0100 Subject: [PATCH 04/60] add support for `serde(skip)` on enum newtype variants --- macros/src/types/enum.rs | 50 ++++++++++++++++++++-------- macros/src/types/newtype.rs | 2 +- ts-rs/tests/union_serde_skip.rs | 59 +++++++++++++++++++++++++++++++++ 3 files changed, 96 insertions(+), 15 deletions(-) create mode 100644 ts-rs/tests/union_serde_skip.rs diff --git a/macros/src/types/enum.rs b/macros/src/types/enum.rs index 043379a..4c73b75 100644 --- a/macros/src/types/enum.rs +++ b/macros/src/types/enum.rs @@ -91,18 +91,33 @@ fn format_variant( Tagged::Untagged => quote!(#inline_type), Tagged::Externally => match &variant.fields { Fields::Unit => quote!(format!("\"{}\"", #name)), + Fields::Unnamed(unnamed) if unnamed.unnamed.len() == 1 => { + let FieldAttr { skip, .. } = FieldAttr::from_attrs(&unnamed.unnamed[0].attrs)?; + if skip { + quote!(format!("\"{}\"", #name)) + } else { + quote!(format!("{{ \"{}\": {} }}", #name, #inline_type)) + } + } _ => quote!(format!("{{ \"{}\": {} }}", #name, #inline_type)), }, Tagged::Adjacently { tag, content } => match &variant.fields { Fields::Unnamed(unnamed) if unnamed.unnamed.len() == 1 => { - let FieldAttr { type_override, .. } = - FieldAttr::from_attrs(&unnamed.unnamed[0].attrs)?; - let ty = if let Some(type_override) = type_override { - quote! { #type_override } + let FieldAttr { + type_override, + skip, + .. + } = FieldAttr::from_attrs(&unnamed.unnamed[0].attrs)?; + if skip { + quote!(format!("{{ \"{}\": \"{}\" }}", #tag, #name)) } else { - format_type(&unnamed.unnamed[0].ty, dependencies, generics) - }; - quote!(format!("{{ \"{}\": \"{}\", \"{}\": {} }}", #tag, #name, #content, #ty)) + let ty = if let Some(type_override) = type_override { + quote! { #type_override } + } else { + format_type(&unnamed.unnamed[0].ty, dependencies, generics) + }; + quote!(format!("{{ \"{}\": \"{}\", \"{}\": {} }}", #tag, #name, #content, #ty)) + } } Fields::Unit => quote!(format!("{{ \"{}\": \"{}\" }}", #tag, #name)), _ => quote!( @@ -120,14 +135,21 @@ fn format_variant( }, None => match &variant.fields { Fields::Unnamed(unnamed) if unnamed.unnamed.len() == 1 => { - let FieldAttr { type_override, .. } = - FieldAttr::from_attrs(&unnamed.unnamed[0].attrs)?; - let ty = if let Some(type_override) = type_override { - quote! { #type_override } + let FieldAttr { + type_override, + skip, + .. + } = FieldAttr::from_attrs(&unnamed.unnamed[0].attrs)?; + if skip { + quote!(format!("{{ \"{}\": \"{}\" }}", #tag, #name)) } else { - format_type(&unnamed.unnamed[0].ty, dependencies, generics) - }; - quote!(format!("{{ \"{}\": \"{}\" }} & {}", #tag, #name, #ty)) + let ty = if let Some(type_override) = type_override { + quote! { #type_override } + } else { + format_type(&unnamed.unnamed[0].ty, dependencies, generics) + }; + quote!(format!("{{ \"{}\": \"{}\" }} & {}", #tag, #name, #ty)) + } } Fields::Unit => quote!(format!("{{ \"{}\": \"{}\" }}", #tag, #name)), _ => { diff --git a/macros/src/types/newtype.rs b/macros/src/types/newtype.rs index b5070d7..30b0775 100644 --- a/macros/src/types/newtype.rs +++ b/macros/src/types/newtype.rs @@ -32,7 +32,7 @@ pub(crate) fn newtype( match (&rename_inner, skip, optional, flatten) { (Some(_), ..) => syn_err!("`rename` is not applicable to newtype fields"), - (_, true, ..) => syn_err!("`skip` is not applicable to newtype fields"), + (_, true, ..) => return super::unit::null(attr, name), (_, _, true, ..) => syn_err!("`optional` is not applicable to newtype fields"), (_, _, _, true) => syn_err!("`flatten` is not applicable to newtype fields"), _ => {} diff --git a/ts-rs/tests/union_serde_skip.rs b/ts-rs/tests/union_serde_skip.rs new file mode 100644 index 0000000..1dfae1c --- /dev/null +++ b/ts-rs/tests/union_serde_skip.rs @@ -0,0 +1,59 @@ +#![allow(dead_code)] + +use serde::Deserialize; +use ts_rs::TS; + +#[derive(TS, Deserialize)] +#[serde(untagged)] +enum TestUntagged { + A, // serde_json -> `null` + B(), // serde_json -> `[]` + C(#[serde(skip)] i32), // serde_json -> `null` +} + +#[derive(TS, Deserialize)] +enum TestExternally { + A, // serde_json -> `"A"` + B(), // serde_json -> `{"B":[]}` + C(#[serde(skip)] i32), // serde_json -> `"C"` +} + +#[derive(TS, Deserialize)] +#[serde(tag = "type", content = "content")] +enum TestAdjacently { + A, // serde_json -> `{"type":"A"}` + B(), // serde_json -> `{"type":"B","content":[]}` + C(#[serde(skip)] i32), // serde_json -> `{"type":"C"}` +} + +#[derive(TS, Deserialize)] +#[serde(tag = "type")] +enum TestInternally { + A, // serde_json -> `{"type":"A"}` + B, // serde_json -> `{"type":"B"}` + C(#[serde(skip)] i32), // serde_json -> `{"type":"C"}` +} + +#[cfg(feature = "serde-compat")] +#[test] +fn test() { + assert_eq!( + TestUntagged::decl(), + r#"type TestUntagged = null | never[] | null;"# + ); + + assert_eq!( + TestExternally::decl(), + r#"type TestExternally = "A" | { "B": never[] } | "C";"# + ); + + assert_eq!( + TestAdjacently::decl(), + r#"type TestAdjacently = { "type": "A" } | { "type": "B", "content": never[] } | { "type": "C" };"# + ); + + assert_eq!( + TestInternally::decl(), + r#"type TestInternally = { "type": "A" } | { "type": "B" } | { "type": "C" };"# + ); +} From 5fbc845f3a86ccc2a5e7f53798f1fbfe868c2815 Mon Sep 17 00:00:00 2001 From: Tim Guggenmos Date: Wed, 29 Nov 2023 22:11:09 +0100 Subject: [PATCH 05/60] added tests for named enum variants as well --- ts-rs/tests/union_named_serde_skip.rs | 71 +++++++++++++++++++ ...de_skip.rs => union_unnamed_serde_skip.rs} | 0 2 files changed, 71 insertions(+) create mode 100644 ts-rs/tests/union_named_serde_skip.rs rename ts-rs/tests/{union_serde_skip.rs => union_unnamed_serde_skip.rs} (100%) diff --git a/ts-rs/tests/union_named_serde_skip.rs b/ts-rs/tests/union_named_serde_skip.rs new file mode 100644 index 0000000..804e058 --- /dev/null +++ b/ts-rs/tests/union_named_serde_skip.rs @@ -0,0 +1,71 @@ +#![allow(dead_code)] + +use serde::Deserialize; +use ts_rs::TS; + +#[derive(TS, Deserialize)] +#[serde(untagged)] +enum TestUntagged { + A, // serde_json -> `null` + B(), // serde_json -> `[]` + C { + #[serde(skip)] + val: i32, + }, // serde_json -> `{}` +} + +#[derive(TS, Deserialize)] +enum TestExternally { + A, // serde_json -> `"A"` + B(), // serde_json -> `{"B":[]}` + C { + #[serde(skip)] + val: i32, + }, // serde_json -> `{"C":{}}` +} + +#[derive(TS, Deserialize)] +#[serde(tag = "type", content = "content")] +enum TestAdjacently { + A, // serde_json -> `{"type":"A"}` + B(), // serde_json -> `{"type":"B","content":[]}` + C { + #[serde(skip)] + val: i32, + }, // serde_json -> `{"type":"C","content":{}}` +} + +#[derive(TS, Deserialize)] +#[serde(tag = "type")] +enum TestInternally { + A, // serde_json -> `{"type":"A"}` + B, // serde_json -> `{"type":"B"}` + C { + #[serde(skip)] + val: i32, + }, // serde_json -> `{"type":"C"}` +} + +#[cfg(feature = "serde-compat")] +#[test] +fn test() { + assert_eq!( + TestUntagged::decl(), + r#"type TestUntagged = null | never[] | { };"# + ); + + assert_eq!( + TestExternally::decl(), + r#"type TestExternally = "A" | { "B": never[] } | { "C": { } };"# + ); + + assert_eq!( + TestAdjacently::decl(), + r#"type TestAdjacently = { "type": "A" } | { "type": "B", "content": never[] } | { "type": "C", "content": { } };"# + ); + + assert_eq!( + TestInternally::decl(), + r#"type TestInternally = { "type": "A" } | { "type": "B" } | { "type": "C", };"# + ); +} diff --git a/ts-rs/tests/union_serde_skip.rs b/ts-rs/tests/union_unnamed_serde_skip.rs similarity index 100% rename from ts-rs/tests/union_serde_skip.rs rename to ts-rs/tests/union_unnamed_serde_skip.rs From 9f38240017660509f135f8968b59663c3bf20ff2 Mon Sep 17 00:00:00 2001 From: darthturska Date: Sun, 10 Dec 2023 15:00:35 +0200 Subject: [PATCH 06/60] fix: Include borrowed type's type arguments in typescript --- macros/src/types/generics.rs | 7 +++++-- ts-rs/tests/lifetimes.rs | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/macros/src/types/generics.rs b/macros/src/types/generics.rs index 290659e..cea3e3c 100644 --- a/macros/src/types/generics.rs +++ b/macros/src/types/generics.rs @@ -1,7 +1,8 @@ use proc_macro2::TokenStream; use quote::{format_ident, quote}; use syn::{ - GenericArgument, GenericParam, Generics, ItemStruct, PathArguments, Type, TypeGroup, TypeTuple, + GenericArgument, GenericParam, Generics, ItemStruct, PathArguments, Type, TypeGroup, + TypeReference, TypeTuple, }; use crate::{attr::StructAttr, deps::Dependencies}; @@ -109,7 +110,9 @@ pub fn format_type(ty: &Type, dependencies: &mut Dependencies, generics: &Generi fn extract_type_args(ty: &Type) -> Option> { let last_segment = match ty { - Type::Group(TypeGroup { elem, .. }) => return extract_type_args(elem), + Type::Group(TypeGroup { elem, .. }) | Type::Reference(TypeReference { elem, .. }) => { + return extract_type_args(elem) + } Type::Path(type_path) => type_path.path.segments.last(), _ => None, }?; diff --git a/ts-rs/tests/lifetimes.rs b/ts-rs/tests/lifetimes.rs index 75bdb64..835610e 100644 --- a/ts-rs/tests/lifetimes.rs +++ b/ts-rs/tests/lifetimes.rs @@ -10,3 +10,25 @@ fn contains_borrow() { assert_eq!(S::decl(), "interface S { s: string, }") } + +#[test] +fn contains_borrow_type_args() { + #[derive(TS)] + #[allow(dead_code)] + struct B<'a, T: 'a> { + a: &'a T, + } + + #[derive(TS)] + #[allow(dead_code)] + struct A<'a> { + a: &'a &'a &'a Vec, //Multiple References + b: &'a Vec>, //Nesting + c: &'a std::collections::HashMap, //Multiple type args + } + + assert_eq!( + A::decl(), + "interface A { a: Array, b: Array>, c: Record, }" + ); +} From 0a419101121a11c3e958f4c0ade65ede85b93dad Mon Sep 17 00:00:00 2001 From: escritorio-gustavo <131818645+escritorio-gustavo@users.noreply.github.com> Date: Tue, 12 Dec 2023 10:25:44 -0300 Subject: [PATCH 07/60] impl TS on slices Allows for structs for deriving `TS` on structs with a field of type `Box<[T]>` --- ts-rs/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/ts-rs/src/lib.rs b/ts-rs/src/lib.rs index a624cf6..5706a4e 100644 --- a/ts-rs/src/lib.rs +++ b/ts-rs/src/lib.rs @@ -583,6 +583,7 @@ impl_shadow!(as Vec: impl TS for HashSet); impl_shadow!(as Vec: impl TS for BTreeSet); impl_shadow!(as HashMap: impl TS for BTreeMap); impl_shadow!(as Vec: impl TS for [T; N]); +impl_shadow!(as Vec: impl TS for [T]); impl_wrapper!(impl TS for Box); impl_wrapper!(impl TS for std::sync::Arc); From 214e92bc3f72687b5550390a28bd5001417063c4 Mon Sep 17 00:00:00 2001 From: escritorio-gustavo <131818645+escritorio-gustavo@users.noreply.github.com> Date: Tue, 12 Dec 2023 10:32:55 -0300 Subject: [PATCH 08/60] Update Cargo.toml - Minor version bump --- ts-rs/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ts-rs/Cargo.toml b/ts-rs/Cargo.toml index 0457407..af1fc1b 100644 --- a/ts-rs/Cargo.toml +++ b/ts-rs/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ts-rs" -version = "7.0.0" +version = "7.1.0" authors = ["Moritz Bischof "] edition = "2021" license = "MIT" From b7de8cfff2e2ab48a7ac1454def141a7192a03fa Mon Sep 17 00:00:00 2001 From: Gustavo Date: Tue, 12 Dec 2023 11:06:44 -0300 Subject: [PATCH 09/60] Add slice support for derive macro --- macros/Cargo.toml | 2 +- macros/src/types/generics.rs | 11 ++++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/macros/Cargo.toml b/macros/Cargo.toml index 8517120..71555a2 100644 --- a/macros/Cargo.toml +++ b/macros/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ts-rs-macros" -version = "7.0.0" +version = "7.1.0" authors = ["Moritz Bischof "] edition = "2021" description = "derive macro for ts-rs" diff --git a/macros/src/types/generics.rs b/macros/src/types/generics.rs index 290659e..0176f91 100644 --- a/macros/src/types/generics.rs +++ b/macros/src/types/generics.rs @@ -1,7 +1,8 @@ use proc_macro2::TokenStream; use quote::{format_ident, quote}; use syn::{ - GenericArgument, GenericParam, Generics, ItemStruct, PathArguments, Type, TypeGroup, TypeTuple, + GenericArgument, GenericParam, Generics, ItemStruct, PathArguments, Type, TypeArray, TypeGroup, + TypeSlice, TypeTuple, }; use crate::{attr::StructAttr, deps::Dependencies}; @@ -61,10 +62,10 @@ pub fn format_type(ty: &Type, dependencies: &mut Dependencies, generics: &Generi // special treatment for arrays and tuples match ty { - // the field is an array (`[T; n]`) so it technically doesn't have a generic argument. - // therefore, we handle it explicitly here like a `Vec` - Type::Array(array) => { - let inner_ty = &array.elem; + // The field is an array (`[T; n]`) or a slice (`[T]`) so it technically doesn't have a + // generic argument. Therefore, we handle it explicitly here like a `Vec` + Type::Array(TypeArray { ref elem, .. }) | Type::Slice(TypeSlice { ref elem, .. }) => { + let inner_ty = elem; let vec_ty = syn::parse2::(quote!(Vec::<#inner_ty>)).unwrap(); return format_type(&vec_ty, dependencies, generics); } From 8f1a58a1342fcdd04169a13fc29741714e251d9a Mon Sep 17 00:00:00 2001 From: Gustavo Date: Tue, 12 Dec 2023 11:09:00 -0300 Subject: [PATCH 10/60] Add slice support to derive macro --- macros/Cargo.toml | 2 +- macros/src/types/generics.rs | 11 ++++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/macros/Cargo.toml b/macros/Cargo.toml index 8517120..71555a2 100644 --- a/macros/Cargo.toml +++ b/macros/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ts-rs-macros" -version = "7.0.0" +version = "7.1.0" authors = ["Moritz Bischof "] edition = "2021" description = "derive macro for ts-rs" diff --git a/macros/src/types/generics.rs b/macros/src/types/generics.rs index 290659e..0176f91 100644 --- a/macros/src/types/generics.rs +++ b/macros/src/types/generics.rs @@ -1,7 +1,8 @@ use proc_macro2::TokenStream; use quote::{format_ident, quote}; use syn::{ - GenericArgument, GenericParam, Generics, ItemStruct, PathArguments, Type, TypeGroup, TypeTuple, + GenericArgument, GenericParam, Generics, ItemStruct, PathArguments, Type, TypeArray, TypeGroup, + TypeSlice, TypeTuple, }; use crate::{attr::StructAttr, deps::Dependencies}; @@ -61,10 +62,10 @@ pub fn format_type(ty: &Type, dependencies: &mut Dependencies, generics: &Generi // special treatment for arrays and tuples match ty { - // the field is an array (`[T; n]`) so it technically doesn't have a generic argument. - // therefore, we handle it explicitly here like a `Vec` - Type::Array(array) => { - let inner_ty = &array.elem; + // The field is an array (`[T; n]`) or a slice (`[T]`) so it technically doesn't have a + // generic argument. Therefore, we handle it explicitly here like a `Vec` + Type::Array(TypeArray { ref elem, .. }) | Type::Slice(TypeSlice { ref elem, .. }) => { + let inner_ty = elem; let vec_ty = syn::parse2::(quote!(Vec::<#inner_ty>)).unwrap(); return format_type(&vec_ty, dependencies, generics); } From 6972225d4e1ae31a29842e5aa446d07263fdbf5e Mon Sep 17 00:00:00 2001 From: Gustavo Date: Tue, 12 Dec 2023 11:11:01 -0300 Subject: [PATCH 11/60] Bump version of macro crate dependecy --- ts-rs/Cargo.toml | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/ts-rs/Cargo.toml b/ts-rs/Cargo.toml index af1fc1b..ec614a8 100644 --- a/ts-rs/Cargo.toml +++ b/ts-rs/Cargo.toml @@ -8,7 +8,12 @@ description = "generate typescript bindings from rust types" homepage = "https://github.com/Aleph-Alpha/ts-rs" repository = "https://github.com/Aleph-Alpha/ts-rs" keywords = ["typescript", "ts", "bindings", "ts-rs", "wasm"] -categories = ["development-tools::ffi", "development-tools::build-utils", "wasm", "web-programming"] +categories = [ + "development-tools::ffi", + "development-tools::build-utils", + "wasm", + "web-programming", +] readme = "../README.md" [features] @@ -31,10 +36,12 @@ chrono = { version = "0.4", features = ["serde"] } [dependencies] heapless = { version = "0.7", optional = true } -ts-rs-macros = { version = "7.0.0", path = "../macros" } +ts-rs-macros = { version = "7.1.0", path = "../macros" } dprint-plugin-typescript = { version = "0.85.1", optional = true } chrono = { version = "0.4", optional = true } -bigdecimal = { version = ">=0.0.13, < 0.4.0", features = ["serde"], optional = true } +bigdecimal = { version = ">=0.0.13, < 0.4.0", features = [ + "serde", +], optional = true } uuid = { version = "1.1.2", optional = true } bson = { version = "2.2.0", optional = true } bytes = { version = "1.0", optional = true } From e86be7a2c209f73ffe36a26da9759e15697376c6 Mon Sep 17 00:00:00 2001 From: Gustavo Date: Tue, 12 Dec 2023 11:21:13 -0300 Subject: [PATCH 12/60] Add tests --- ts-rs/tests/slices.rs | 52 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 ts-rs/tests/slices.rs diff --git a/ts-rs/tests/slices.rs b/ts-rs/tests/slices.rs new file mode 100644 index 0000000..14e0e9d --- /dev/null +++ b/ts-rs/tests/slices.rs @@ -0,0 +1,52 @@ +use ts_rs::TS; + +#[test] +fn free() { + assert_eq!(<[String]>::inline(), "Array") +} + +#[test] +fn interface() { + #[derive(TS)] + struct Interface { + #[allow(dead_code)] + a: [i32], + } + + assert_eq!(Interface::inline(), "{ a: Array, }") +} + +#[test] +fn newtype() { + #[derive(TS)] + struct Newtype(#[allow(dead_code)] [i32]); + + assert_eq!(Newtype::inline(), "Array") +} + +// Since slices usually need to be wrapped in a `Box` or other container, +// these tests should to check for that + +#[test] +fn boxed_free() { + assert_eq!(>::inline(), "Array") +} + +#[test] +fn boxed_interface() { + #[derive(TS)] + struct Interface { + #[allow(dead_code)] + a: Box<[i32]>, + } + + assert_eq!(Interface::inline(), "{ a: Array, }") +} + +#[test] +fn boxed_newtype() { + #[derive(TS)] + struct Newtype(#[allow(dead_code)] Box<[i32]>); + + assert_eq!(Newtype::inline(), "Array") +} From 7cd77183a2aa6a8bfd2c3ec55591e2d8797629b1 Mon Sep 17 00:00:00 2001 From: Gustavo Date: Tue, 12 Dec 2023 11:29:10 -0300 Subject: [PATCH 13/60] Revert version bump --- macros/Cargo.toml | 2 +- ts-rs/Cargo.toml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/macros/Cargo.toml b/macros/Cargo.toml index 71555a2..8517120 100644 --- a/macros/Cargo.toml +++ b/macros/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ts-rs-macros" -version = "7.1.0" +version = "7.0.0" authors = ["Moritz Bischof "] edition = "2021" description = "derive macro for ts-rs" diff --git a/ts-rs/Cargo.toml b/ts-rs/Cargo.toml index ec614a8..7dc5784 100644 --- a/ts-rs/Cargo.toml +++ b/ts-rs/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ts-rs" -version = "7.1.0" +version = "7.0.0" authors = ["Moritz Bischof "] edition = "2021" license = "MIT" @@ -36,7 +36,7 @@ chrono = { version = "0.4", features = ["serde"] } [dependencies] heapless = { version = "0.7", optional = true } -ts-rs-macros = { version = "7.1.0", path = "../macros" } +ts-rs-macros = { version = "7.0.0", path = "../macros" } dprint-plugin-typescript = { version = "0.85.1", optional = true } chrono = { version = "0.4", optional = true } bigdecimal = { version = ">=0.0.13, < 0.4.0", features = [ From 230ab6bb06bb82cec27a3b10266b6ef4b33f06bd Mon Sep 17 00:00:00 2001 From: Gustavo Date: Tue, 12 Dec 2023 11:43:27 -0300 Subject: [PATCH 14/60] Accidentally removed TypeReference from use I have no idea how the Rust compiler didn't warn me about this --- macros/src/types/generics.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/macros/src/types/generics.rs b/macros/src/types/generics.rs index 2e4acbb..6f987dc 100644 --- a/macros/src/types/generics.rs +++ b/macros/src/types/generics.rs @@ -2,7 +2,7 @@ use proc_macro2::TokenStream; use quote::{format_ident, quote}; use syn::{ GenericArgument, GenericParam, Generics, ItemStruct, PathArguments, Type, TypeArray, TypeGroup, - TypeSlice, TypeTuple, + TypeReference, TypeSlice, TypeTuple, }; use crate::{attr::StructAttr, deps::Dependencies}; From 778f4d035108755eb6b6dcd1c50b117eef94c96c Mon Sep 17 00:00:00 2001 From: Gustavo Date: Thu, 21 Dec 2023 15:38:44 -0300 Subject: [PATCH 15/60] Make clippy happy --- ts-rs/tests/generics.rs | 1 + ts-rs/tests/union_with_internal_tag.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/ts-rs/tests/generics.rs b/ts-rs/tests/generics.rs index c7ce9b6..5dad985 100644 --- a/ts-rs/tests/generics.rs +++ b/ts-rs/tests/generics.rs @@ -1,3 +1,4 @@ +#![allow(clippy::box_collection)] #![allow(dead_code)] use std::{ diff --git a/ts-rs/tests/union_with_internal_tag.rs b/ts-rs/tests/union_with_internal_tag.rs index e0fc0b7..e7382ee 100644 --- a/ts-rs/tests/union_with_internal_tag.rs +++ b/ts-rs/tests/union_with_internal_tag.rs @@ -1,4 +1,4 @@ -#![allow(dead_code, clippy::blacklisted_name)] +#![allow(dead_code, clippy::disallowed_names)] use serde::Serialize; use ts_rs::TS; From 96ebbb4cd5add28c73777a4384fc3a2be135cef2 Mon Sep 17 00:00:00 2001 From: Gustavo Date: Thu, 21 Dec 2023 15:39:09 -0300 Subject: [PATCH 16/60] Make PascalCase and camelCase behave like in serde --- macros/src/attr/mod.rs | 24 ++++++++++++++++++++++-- ts-rs/tests/struct_rename.rs | 24 ++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/macros/src/attr/mod.rs b/macros/src/attr/mod.rs index dc566ff..b9575c1 100644 --- a/macros/src/attr/mod.rs +++ b/macros/src/attr/mod.rs @@ -32,9 +32,29 @@ impl Inflection { match self { Inflection::Lower => string.to_lowercase(), Inflection::Upper => string.to_uppercase(), - Inflection::Camel => string.to_camel_case(), + Inflection::Camel => { + let pascal = Inflection::apply(Inflection::Pascal, string); + pascal[..1].to_ascii_lowercase() + &pascal[1..] + } Inflection::Snake => string.to_snake_case(), - Inflection::Pascal => string.to_pascal_case(), + Inflection::Pascal => { + let mut s = String::with_capacity(string.len()); + + let mut capitalize = true; + for c in string.chars() { + if c == '_' { + capitalize = true; + continue; + } else if capitalize { + s.push(c.to_ascii_uppercase()); + capitalize = false; + } else { + s.push(c.to_ascii_lowercase()) + } + } + + s + } Inflection::ScreamingSnake => string.to_screaming_snake_case(), Inflection::Kebab => string.to_kebab_case(), } diff --git a/ts-rs/tests/struct_rename.rs b/ts-rs/tests/struct_rename.rs index 12039d0..e242c5b 100644 --- a/ts-rs/tests/struct_rename.rs +++ b/ts-rs/tests/struct_rename.rs @@ -14,6 +14,30 @@ fn rename_all() { assert_eq!(Rename::inline(), "{ A: number, B: number, }"); } +#[test] +fn rename_all_camel_case() { + #[derive(TS)] + #[ts(rename_all = "camelCase")] + struct Rename { + crc32c_hash: i32, + b: i32, + } + + assert_eq!(Rename::inline(), "{ crc32cHash: number, b: number, }"); +} + +#[test] +fn rename_all_pascal_case() { + #[derive(TS)] + #[ts(rename_all = "PascalCase")] + struct Rename { + crc32c_hash: i32, + b: i32, + } + + assert_eq!(Rename::inline(), "{ Crc32cHash: number, B: number, }"); +} + #[cfg(feature = "serde-compat")] #[test] fn serde_rename_special_char() { From 835a2cbbedb51f335ee7b690ed14ed3724cec91e Mon Sep 17 00:00:00 2001 From: Gustavo Date: Thu, 21 Dec 2023 16:16:59 -0300 Subject: [PATCH 17/60] Add `quiet-serde`feature --- macros/Cargo.toml | 1 + ts-rs/Cargo.toml | 1 + 2 files changed, 2 insertions(+) diff --git a/macros/Cargo.toml b/macros/Cargo.toml index 71555a2..8336b34 100644 --- a/macros/Cargo.toml +++ b/macros/Cargo.toml @@ -10,6 +10,7 @@ repository = "https://github.com/Aleph-Alpha/ts-rs" [features] serde-compat = ["termcolor"] +quiet-serde = [] [lib] proc-macro = true diff --git a/ts-rs/Cargo.toml b/ts-rs/Cargo.toml index af1fc1b..8686916 100644 --- a/ts-rs/Cargo.toml +++ b/ts-rs/Cargo.toml @@ -24,6 +24,7 @@ default = ["serde-compat"] indexmap-impl = ["indexmap"] ordered-float-impl = ["ordered-float"] heapless-impl = ["heapless"] +quiet-serde = ["ts-rs-macros/quiet-serde"] [dev-dependencies] serde = { version = "1.0", features = ["derive"] } From 9563d5dfe7838f357674e346d735f5e46e29e3db Mon Sep 17 00:00:00 2001 From: Gustavo Date: Thu, 21 Dec 2023 16:17:52 -0300 Subject: [PATCH 18/60] Prevent warnings from `parse_serde_attrs` when using `quiet-serde` feature --- macros/src/utils.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/macros/src/utils.rs b/macros/src/utils.rs index 3b6f1fe..fbcf062 100644 --- a/macros/src/utils.rs +++ b/macros/src/utils.rs @@ -99,7 +99,10 @@ pub fn parse_serde_attrs<'a, A: TryFrom<&'a Attribute, Error = Error>>( .flat_map(|attr| match A::try_from(attr) { Ok(attr) => Some(attr), Err(_) => { + #[cfg(not(feature = "quiet-serde"))] use quote::ToTokens; + + #[cfg(not(feature = "quiet-serde"))] warning::print_warning( "failed to parse serde attribute", format!("{}", attr.to_token_stream()), From 71783fdfa73502222f4c88e15cacfbeff6270259 Mon Sep 17 00:00:00 2001 From: Gustavo Date: Thu, 21 Dec 2023 16:19:07 -0300 Subject: [PATCH 19/60] Allow `print_warning` to be unused as the `#![deny(unused)]` attribute in lib.rs was causing a compile error when using `quiet_serde` --- macros/src/utils.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/macros/src/utils.rs b/macros/src/utils.rs index fbcf062..96946bf 100644 --- a/macros/src/utils.rs +++ b/macros/src/utils.rs @@ -124,6 +124,7 @@ mod warning { // Sadly, it is impossible to raise a warning in a proc macro. // This function prints a message which looks like a compiler warning. + #[allow(unused)] pub fn print_warning( title: impl Display, content: impl Display, From 3a79cea8c3f4fc53e98dce74c02019270a320947 Mon Sep 17 00:00:00 2001 From: Moritz Bischof Date: Thu, 11 Jan 2024 04:38:15 +0100 Subject: [PATCH 20/60] rename quit-serde to no-serde-warnings, add docs --- README.md | 7 ++++++- macros/Cargo.toml | 2 +- ts-rs/Cargo.toml | 2 +- ts-rs/src/lib.rs | 7 ++++++- 4 files changed, 14 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ee26579..09e29b8 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,11 @@ When running `cargo test`, the TypeScript bindings will be exported to the file Implement `TS` for `Vec` from heapless +- `no-serde-warnings` + + When `serde-compat` is enabled, warnings are printed during build if unsupported serde + attributes are encountered. Enabling this feature silences these warnings. + If there's a type you're dealing with which doesn't implement `TS`, use `#[ts(type = "..")]` or open a PR. @@ -127,7 +132,7 @@ Supported serde attributes: - `flatten` - `default` -When ts-rs encounters an unsupported serde attribute, a warning is emitted. +When ts-rs encounters an unsupported serde attribute, a warning is emitted, unless the feature `no-serde-warnings` is enabled. ### contributing Contributions are always welcome! diff --git a/macros/Cargo.toml b/macros/Cargo.toml index 609f865..ce884bb 100644 --- a/macros/Cargo.toml +++ b/macros/Cargo.toml @@ -10,7 +10,7 @@ repository = "https://github.com/Aleph-Alpha/ts-rs" [features] serde-compat = ["termcolor"] -quiet-serde = [] +no-serde-warnings = [] [lib] proc-macro = true diff --git a/ts-rs/Cargo.toml b/ts-rs/Cargo.toml index 7c84214..0651a83 100644 --- a/ts-rs/Cargo.toml +++ b/ts-rs/Cargo.toml @@ -29,7 +29,7 @@ default = ["serde-compat"] indexmap-impl = ["indexmap"] ordered-float-impl = ["ordered-float"] heapless-impl = ["heapless"] -quiet-serde = ["ts-rs-macros/quiet-serde"] +no-serde-warnings = ["ts-rs-macros/no-serde-warnings"] [dev-dependencies] serde = { version = "1.0", features = ["derive"] } diff --git a/ts-rs/src/lib.rs b/ts-rs/src/lib.rs index 5706a4e..641f247 100644 --- a/ts-rs/src/lib.rs +++ b/ts-rs/src/lib.rs @@ -107,6 +107,11 @@ //! //! Implement `TS` for `Vec` from heapless //! +//! - `no-serde-warnings` +//! +//! When `serde-compat` is enabled, warnings are printed during build if unsupported serde +//! attributes are encountered. Enabling this feature silences these warnings. +//! //! //! If there's a type you're dealing with which doesn't implement `TS`, use `#[ts(type = "..")]` or open a PR. //! @@ -125,7 +130,7 @@ //! - `flatten` //! - `default` //! -//! When ts-rs encounters an unsupported serde attribute, a warning is emitted. +//! When ts-rs encounters an unsupported serde attribute, a warning is emitted, unless the feature `no-serde-warnings` is enabled. //! //! ## contributing //! Contributions are always welcome! From 89235eedc9aa18f8ccf73e027369068e93c2eeba Mon Sep 17 00:00:00 2001 From: Moritz Bischof Date: Thu, 11 Jan 2024 04:53:11 +0100 Subject: [PATCH 21/60] bump version to 7.1 --- README.md | 2 +- macros/Cargo.toml | 2 +- ts-rs/Cargo.toml | 4 ++-- ts-rs/src/lib.rs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 09e29b8..5d1386e 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ We recommend doing this in your tests. ### get started ```toml [dependencies] -ts-rs = "7.0" +ts-rs = "7.1" ``` ```rust diff --git a/macros/Cargo.toml b/macros/Cargo.toml index ce884bb..78a9550 100644 --- a/macros/Cargo.toml +++ b/macros/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ts-rs-macros" -version = "7.0.0" +version = "7.1.0" authors = ["Moritz Bischof "] edition = "2021" description = "derive macro for ts-rs" diff --git a/ts-rs/Cargo.toml b/ts-rs/Cargo.toml index 0651a83..f40c45e 100644 --- a/ts-rs/Cargo.toml +++ b/ts-rs/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ts-rs" -version = "7.0.0" +version = "7.1.0" authors = ["Moritz Bischof "] edition = "2021" license = "MIT" @@ -37,7 +37,7 @@ chrono = { version = "0.4", features = ["serde"] } [dependencies] heapless = { version = "0.7", optional = true } -ts-rs-macros = { version = "7.0.0", path = "../macros" } +ts-rs-macros = { version = "7.1.0", path = "../macros" } dprint-plugin-typescript = { version = "0.85.1", optional = true } chrono = { version = "0.4", optional = true } bigdecimal = { version = ">=0.0.13, < 0.4.0", features = [ diff --git a/ts-rs/src/lib.rs b/ts-rs/src/lib.rs index 14477d2..ff4e8f4 100644 --- a/ts-rs/src/lib.rs +++ b/ts-rs/src/lib.rs @@ -40,7 +40,7 @@ //! ## get started //! ```toml //! [dependencies] -//! ts-rs = "7.0" +//! ts-rs = "7.1" //! ``` //! //! ```rust From e545a3a11ecefaaf0d0d29e230c461b9da4aafeb Mon Sep 17 00:00:00 2001 From: Moritz Bischof Date: Thu, 11 Jan 2024 05:15:27 +0100 Subject: [PATCH 22/60] do not parse serde attributes when #[ts(skip)] is present --- macros/src/attr/field.rs | 5 ++++- macros/src/attr/variant.rs | 5 ++++- ts-rs/tests/serde-skip-with-default.rs | 27 ++++++++++++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 ts-rs/tests/serde-skip-with-default.rs diff --git a/macros/src/attr/field.rs b/macros/src/attr/field.rs index 13daef5..0c91b1c 100644 --- a/macros/src/attr/field.rs +++ b/macros/src/attr/field.rs @@ -22,7 +22,10 @@ impl FieldAttr { let mut result = Self::default(); parse_attrs(attrs)?.for_each(|a| result.merge(a)); #[cfg(feature = "serde-compat")] - crate::utils::parse_serde_attrs::(attrs).for_each(|a| result.merge(a.0)); + if !result.skip { + crate::utils::parse_serde_attrs::(attrs) + .for_each(|a| result.merge(a.0)); + } Ok(result) } diff --git a/macros/src/attr/variant.rs b/macros/src/attr/variant.rs index 0f67f1e..1f490db 100644 --- a/macros/src/attr/variant.rs +++ b/macros/src/attr/variant.rs @@ -22,7 +22,10 @@ impl VariantAttr { let mut result = Self::default(); parse_attrs(attrs)?.for_each(|a| result.merge(a)); #[cfg(feature = "serde-compat")] - crate::utils::parse_serde_attrs::(attrs).for_each(|a| result.merge(a.0)); + if !result.skip { + crate::utils::parse_serde_attrs::(attrs) + .for_each(|a| result.merge(a.0)); + } Ok(result) } diff --git a/ts-rs/tests/serde-skip-with-default.rs b/ts-rs/tests/serde-skip-with-default.rs new file mode 100644 index 0000000..6287f36 --- /dev/null +++ b/ts-rs/tests/serde-skip-with-default.rs @@ -0,0 +1,27 @@ +#![allow(dead_code)] + +// from issue #107. This does now no longer generate a warning. + +use serde::{Deserialize, Serialize}; +use ts_rs::TS; + +fn default_http_version() -> String { + "2".to_owned() +} + +#[derive(Debug, Clone, Deserialize, Serialize, TS)] +#[ts(export)] +pub struct Foobar { + #[ts(skip)] + #[serde(skip, default = "default_http_version")] + pub http_version: String, + pub something_else: i32, +} + +#[test] +fn serde_skip_with_default() { + assert_eq!( + Foobar::decl(), + "interface Foobar { something_else: number, }" + ); +} From 4df0ffbd1b1ef542526ee9f8972260fabfc09ee5 Mon Sep 17 00:00:00 2001 From: Moritz Bischof Date: Thu, 11 Jan 2024 05:17:34 +0100 Subject: [PATCH 23/60] format, fix linter warnings --- ts-rs/src/lib.rs | 26 +++++++++++++++----------- ts-rs/tests/issue-80.rs | 6 +++--- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/ts-rs/src/lib.rs b/ts-rs/src/lib.rs index ff4e8f4..49391ab 100644 --- a/ts-rs/src/lib.rs +++ b/ts-rs/src/lib.rs @@ -104,7 +104,7 @@ //! Implement `TS` for `OrderedFloat` from ordered_float //! //! - `heapless-impl` -//! +//! //! Implement `TS` for `Vec` from heapless //! //! - `no-serde-warnings` @@ -464,21 +464,25 @@ impl TS for Option { } } -impl TS for Result{ - fn name() -> String{ +impl TS for Result { + fn name() -> String { unreachable!(); } - fn transparent() -> bool { - return true; - } - fn dependencies() -> Vec - where - Self: 'static { - [Dependency::from_ty::(), Dependency::from_ty::()].into_iter().flatten().collect() - } fn inline() -> String { format!("{{ Ok : {} }} | {{ Err : {} }}", T::inline(), E::inline()) } + fn dependencies() -> Vec + where + Self: 'static, + { + [Dependency::from_ty::(), Dependency::from_ty::()] + .into_iter() + .flatten() + .collect() + } + fn transparent() -> bool { + true + } } impl TS for Vec { diff --git a/ts-rs/tests/issue-80.rs b/ts-rs/tests/issue-80.rs index 8b0ce4b..20c4b07 100644 --- a/ts-rs/tests/issue-80.rs +++ b/ts-rs/tests/issue-80.rs @@ -1,5 +1,5 @@ -use ts_rs::TS; use serde::Serialize; +use ts_rs::TS; #[derive(TS, Serialize)] #[ts(export)] @@ -9,11 +9,11 @@ pub enum SomeTypeList { #[ts(skip)] skip_this: String, }, - Value2 + Value2, } #[test] fn issue_80() { let ty = SomeTypeList::inline(); assert_eq!(ty, r#"{ "Value1": { } } | "Value2""#); -} \ No newline at end of file +} From a60de918fcde2b4f24790c5c220720eea76d6ce7 Mon Sep 17 00:00:00 2001 From: Sammy Harris Date: Thu, 18 Jan 2024 19:43:06 -0500 Subject: [PATCH 24/60] fix: rename remaining quiet-serde references --- macros/src/utils.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/macros/src/utils.rs b/macros/src/utils.rs index 96946bf..ad7f063 100644 --- a/macros/src/utils.rs +++ b/macros/src/utils.rs @@ -99,10 +99,10 @@ pub fn parse_serde_attrs<'a, A: TryFrom<&'a Attribute, Error = Error>>( .flat_map(|attr| match A::try_from(attr) { Ok(attr) => Some(attr), Err(_) => { - #[cfg(not(feature = "quiet-serde"))] + #[cfg(not(feature = "no-serde-warnings"))] use quote::ToTokens; - #[cfg(not(feature = "quiet-serde"))] + #[cfg(not(feature = "no-serde-warnings"))] warning::print_warning( "failed to parse serde attribute", format!("{}", attr.to_token_stream()), From 7402826ff25723096790e4fb65cefe61e961c9b5 Mon Sep 17 00:00:00 2001 From: Moritz Bischof Date: Fri, 19 Jan 2024 11:18:03 +0100 Subject: [PATCH 25/60] bump to 7.1.1 --- macros/Cargo.toml | 2 +- ts-rs/Cargo.toml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/macros/Cargo.toml b/macros/Cargo.toml index 78a9550..9897b67 100644 --- a/macros/Cargo.toml +++ b/macros/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ts-rs-macros" -version = "7.1.0" +version = "7.1.1" authors = ["Moritz Bischof "] edition = "2021" description = "derive macro for ts-rs" diff --git a/ts-rs/Cargo.toml b/ts-rs/Cargo.toml index f40c45e..12c6c04 100644 --- a/ts-rs/Cargo.toml +++ b/ts-rs/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ts-rs" -version = "7.1.0" +version = "7.1.1" authors = ["Moritz Bischof "] edition = "2021" license = "MIT" @@ -37,7 +37,7 @@ chrono = { version = "0.4", features = ["serde"] } [dependencies] heapless = { version = "0.7", optional = true } -ts-rs-macros = { version = "7.1.0", path = "../macros" } +ts-rs-macros = { version = "7.1.1", path = "../macros" } dprint-plugin-typescript = { version = "0.85.1", optional = true } chrono = { version = "0.4", optional = true } bigdecimal = { version = ">=0.0.13, < 0.4.0", features = [ From 0369890d69b3ebb444f922f915b9a89111c42f0d Mon Sep 17 00:00:00 2001 From: Gustavo Date: Mon, 22 Jan 2024 08:22:51 -0300 Subject: [PATCH 26/60] Add test for `rename_all` on enum struct variants --- ts-rs/tests/enum_struct_rename_all.rs | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 ts-rs/tests/enum_struct_rename_all.rs diff --git a/ts-rs/tests/enum_struct_rename_all.rs b/ts-rs/tests/enum_struct_rename_all.rs new file mode 100644 index 0000000..e69de29 From d8fa31d2cf73a52ce06c8596bdaad0928ec65b8b Mon Sep 17 00:00:00 2001 From: Gustavo Date: Mon, 22 Jan 2024 08:37:38 -0300 Subject: [PATCH 27/60] Fix bug introduced in #184 --- macros/src/attr/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/macros/src/attr/mod.rs b/macros/src/attr/mod.rs index b9575c1..6bb7b34 100644 --- a/macros/src/attr/mod.rs +++ b/macros/src/attr/mod.rs @@ -49,7 +49,7 @@ impl Inflection { s.push(c.to_ascii_uppercase()); capitalize = false; } else { - s.push(c.to_ascii_lowercase()) + s.push(c) } } From 7a963a870b0847c2e86d813e15feadd914b22592 Mon Sep 17 00:00:00 2001 From: Gustavo Date: Mon, 22 Jan 2024 08:43:48 -0300 Subject: [PATCH 28/60] Add test for already camelCase field --- ts-rs/tests/struct_rename.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ts-rs/tests/struct_rename.rs b/ts-rs/tests/struct_rename.rs index e242c5b..aa7d78d 100644 --- a/ts-rs/tests/struct_rename.rs +++ b/ts-rs/tests/struct_rename.rs @@ -18,12 +18,14 @@ fn rename_all() { fn rename_all_camel_case() { #[derive(TS)] #[ts(rename_all = "camelCase")] + #[allow(non_snake_case)] struct Rename { crc32c_hash: i32, b: i32, + alreadyCamelCase: i32, } - assert_eq!(Rename::inline(), "{ crc32cHash: number, b: number, }"); + assert_eq!(Rename::inline(), "{ crc32cHash: number, b: number, alreadyCamelCase: number, }"); } #[test] From 8d23fcd73ef8cffe4be31d53109a2401a13093ae Mon Sep 17 00:00:00 2001 From: Gustavo Date: Mon, 22 Jan 2024 09:46:32 -0300 Subject: [PATCH 29/60] Improve support for references --- macros/src/types/generics.rs | 3 +++ ts-rs/tests/references.rs | 15 +++++++++++++++ ts-rs/tests/slices.rs | 11 +++++++++++ 3 files changed, 29 insertions(+) create mode 100644 ts-rs/tests/references.rs diff --git a/macros/src/types/generics.rs b/macros/src/types/generics.rs index 6f987dc..4766de9 100644 --- a/macros/src/types/generics.rs +++ b/macros/src/types/generics.rs @@ -91,6 +91,9 @@ pub fn format_type(ty: &Type, dependencies: &mut Dependencies, generics: &Generi dependencies.append(tuple_struct.dependencies); return tuple_struct.inline; } + Type::Reference(syn::TypeReference { ref elem, .. }) => { + return format_type(elem, dependencies, generics) + } _ => (), }; diff --git a/ts-rs/tests/references.rs b/ts-rs/tests/references.rs new file mode 100644 index 0000000..1aee02b --- /dev/null +++ b/ts-rs/tests/references.rs @@ -0,0 +1,15 @@ +use ts_rs::TS; + +#[test] +fn references() { + #[derive(TS)] + #[allow(dead_code)] + struct FullOfRefs<'a> { + str_slice: &'a str, + ref_slice: &'a [&'a str], + num_ref: &'a i32, + } + + assert_eq!(FullOfRefs::inline(), "{ str_slice: string, ref_slice: Array, num_ref: number, }") +} + diff --git a/ts-rs/tests/slices.rs b/ts-rs/tests/slices.rs index 14e0e9d..268a090 100644 --- a/ts-rs/tests/slices.rs +++ b/ts-rs/tests/slices.rs @@ -16,6 +16,17 @@ fn interface() { assert_eq!(Interface::inline(), "{ a: Array, }") } +#[test] +fn slice_ref() { + #[derive(TS)] + struct Interface<'a> { + #[allow(dead_code)] + a: &'a [&'a str] + } + + assert_eq!(Interface::inline(), "{ a: Array, }") +} + #[test] fn newtype() { #[derive(TS)] From 46b91c56b48ce2af8457667cdb3c22483eeaadbc Mon Sep 17 00:00:00 2001 From: Gustavo Date: Mon, 22 Jan 2024 10:22:40 -0300 Subject: [PATCH 30/60] Actually add the test rather than an empty file --- ts-rs/tests/enum_struct_rename_all.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/ts-rs/tests/enum_struct_rename_all.rs b/ts-rs/tests/enum_struct_rename_all.rs index e69de29..1f46214 100644 --- a/ts-rs/tests/enum_struct_rename_all.rs +++ b/ts-rs/tests/enum_struct_rename_all.rs @@ -0,0 +1,22 @@ +use serde::{Serialize, Deserialize}; +use ts_rs::TS; + +#[derive(Serialize, Deserialize, TS, Clone)] +#[ts(export)] +#[cfg_attr(feature = "serde-compat", serde(rename_all = "camelCase"))] +#[cfg_attr(not(feature = "serde-compat"), ts(rename_all = "camelCase"))] +pub enum TaskStatus { + #[serde(rename_all = "camelCase")] + Running { started_time: String }, + #[serde(rename_all = "camelCase")] + Terminated { + status: i32, + stdout: String, + stderr: String, + }, +} + +#[test] +pub fn enum_struct_rename_all() { + assert_eq!(TaskStatus::inline(), r#"{ "running": { startedTime: string, } } | { "terminated": { status: number, stdout: string, stderr: string, } }"#) +} From 8284801b4f7280b9ef642b407b7d018700b70890 Mon Sep 17 00:00:00 2001 From: Gustavo Date: Mon, 22 Jan 2024 10:27:15 -0300 Subject: [PATCH 31/60] Fix test to work with and without `serde-compat` --- ts-rs/tests/enum_struct_rename_all.rs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/ts-rs/tests/enum_struct_rename_all.rs b/ts-rs/tests/enum_struct_rename_all.rs index 1f46214..b901a16 100644 --- a/ts-rs/tests/enum_struct_rename_all.rs +++ b/ts-rs/tests/enum_struct_rename_all.rs @@ -6,14 +6,17 @@ use ts_rs::TS; #[cfg_attr(feature = "serde-compat", serde(rename_all = "camelCase"))] #[cfg_attr(not(feature = "serde-compat"), ts(rename_all = "camelCase"))] pub enum TaskStatus { - #[serde(rename_all = "camelCase")] - Running { started_time: String }, - #[serde(rename_all = "camelCase")] - Terminated { - status: i32, - stdout: String, - stderr: String, - }, + #[cfg_attr(feature = "serde-compat", serde(rename_all = "camelCase"))] + #[cfg_attr(not(feature = "serde-compat"), ts(rename_all = "camelCase"))] + Running { started_time: String }, + + #[cfg_attr(feature = "serde-compat", serde(rename_all = "camelCase"))] + #[cfg_attr(not(feature = "serde-compat"), ts(rename_all = "camelCase"))] + Terminated { + status: i32, + stdout: String, + stderr: String, + }, } #[test] From f86ccb5773540579c6708a09c51012366b890de9 Mon Sep 17 00:00:00 2001 From: NyxCode Date: Mon, 22 Jan 2024 15:45:07 +0100 Subject: [PATCH 32/60] CI: Verify README is up to date (#200) CI: Verify README.md is up-to-date --- .github/workflows/test.yml | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index d980a12..3a2daab 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,6 +1,20 @@ on: [push, pull_request] name: Test jobs: + readme-up-to-date: + name: Check that README.md is up-to-date + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: actions-rs/toolchain@v1 + with: + toolchain: stable + - name: Check that README.md is up-to-date + working-directory: ts-rs + run: | + cargo install cargo-readme + diff -u ../README.md <(cargo readme) + test: name: Test ts-rs runs-on: ubuntu-latest @@ -16,4 +30,4 @@ jobs: - uses: actions-rs/cargo@v1 with: command: test - args: --all-features --manifest-path ts-rs/Cargo.toml + args: --all-features --manifest-path ts-rs/Cargo.toml \ No newline at end of file From 1c33a868738654e35fcdafcb2acce495a7ccffd0 Mon Sep 17 00:00:00 2001 From: escritorio-gustavo <131818645+escritorio-gustavo@users.noreply.github.com> Date: Mon, 22 Jan 2024 11:52:45 -0300 Subject: [PATCH 33/60] Add `import-esm` flag (#192) Add "import-esm" feature to make `import`s have a `.js` extension --- README.md | Bin 4181 -> 9130 bytes ts-rs/Cargo.toml | 1 + ts-rs/src/export.rs | 12 +++++++++--- ts-rs/src/lib.rs | 5 +++++ ts-rs/tests/imports.rs | 13 +++++++++++++ 5 files changed, 28 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5d1386e3c979b1adad92c6e9e9648d0da83f6a4c..09b2492e4c567db4efd22b80145da002e7beff0b 100644 GIT binary patch literal 9130 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 XaX;%8KiFwVM+Y{+&vmR*^T>Yz2xkM3 literal 4181 zcmbtXQE%M15q{^dm|Fvl4XmW3#r1$a+d-Q4QUkq9adw&q!>}lEBoU!Vg+qC*JM_O7 zLrS~r#4&v6i!E_E!(lSD4Bo{&;7y&( zvusZPLBhIkbLuo2MY(oG%Dvb+|EV!Wz^hqtB!CIHMrvBa`(C zigR%)q4U`6k*+!QcxHM^pe|SRRE+cfyJV5mUHeENB3{Sa)j=GE(s$=V9336Owwqpy zj~!a5Ms1i>AYqFY$YC(LjwK1&#(G?Xl0gCmKh|ONNYKeUgy5h;piX*JP+{02dz1Ai zvukj7m2md>$VFZ4LPV?kG!dqR!y*FOqd@W z@m7b9QISO0S7yo+c%9q6p8eqc;0OsMaEb;Yc&Wo0%B#yVhm^Mjgd@}ZM#5wek78_G6{NNhI(!VhTzo|ESi8RGn^A6e7uwFp zAO*_B^(C@r1iY6V+RgDIn@Kjlp_7$yRT9hDt{`6*MpwC~lUNAX?36jN_xON~MdDWx z=+;wlGNasLV1@Akl_<+HxZa3sg#%iJw$?~D^BtVQ>WBQ*iZ==V!x}0gO6+g5xw`yO zh@wus)-D=HQLTCO=Q5mA)sB{6}xjEc(zz0k@ORn zyz_w)%Tk)L8Xfeb33@OoS+*wh3YnaP47$=rhiQpc*K>=EQf73oL+YUi8=BbjSYfOS z3~Gv8f%8k$sNneM`@f!uEV|<^E1AnZ_h7b)3klTaNH{+F;pIs>INj+1{AG+eOEH&l ztgw-z2`54T{KLx1;A2_kz`U!_xNT&9?>tA_xLjmVHqQ4llD&5>8SRaom@n&;Z?E!cka&o&%=vKX~`?peGyMoG?Qf5eatqTv*fo_ku{ z%vRbeyzk}kq+xl%yMC5K8Rav*UScQ{#ETEX4xLx%QDu#BGCb||ecJjH@0?xD*0<3* z`s+{*2I=X{%Kujl{A_xH~x)LR>Vw=|UjZa@nX{{8DL z+lTrlXMOv~^9C#a7icZvAJ6QEYJx>v*0ZMrFnFx05C-W9RU~Mdlz1qcg+CXU58*tp z-*8=dtcDcDgENG$; z*Pt}jBN2>oc7CVBKgViWj1C{xR2<&kzW?Rw*NeY>xVre|UEZtxxb@5d?hE_5&jqJg z(68@r9u)1|l)=ae{rtOf^~e)#Y{&CjoW%B@z^Pa8Buo@18`eek9s3>^DtH_`(&A?M nJvKXC$5*%k<(PpUKabiYlrQ*WRM({t|I#&D!VUa(out: &mut String) -> Result<(), Ex fn import_path(from: &Path, import: &Path) -> String { let rel_path = diff_paths(import, from.parent().unwrap()).expect("failed to calculate import path"); - match rel_path.components().next() { + let path = match rel_path.components().next() { Some(Component::Normal(_)) => format!("./{}", rel_path.to_string_lossy()), _ => rel_path.to_string_lossy().into(), + }; + + let path_without_extension = path.trim_end_matches(".ts"); + + if cfg!(feature = "import-esm") { + format!("{}.js", path_without_extension) + } else { + path_without_extension.to_owned() } - .trim_end_matches(".ts") - .to_owned() } // Construct a relative path from a provided base directory path to the provided path. diff --git a/ts-rs/src/lib.rs b/ts-rs/src/lib.rs index 49391ab..c52eb95 100644 --- a/ts-rs/src/lib.rs +++ b/ts-rs/src/lib.rs @@ -64,6 +64,7 @@ //! - generate necessary imports when exporting to multiple files //! - serde compatibility //! - generic types +//! - support for ESM imports //! //! ## limitations //! - generic fields cannot be inlined or flattened (#56) @@ -112,6 +113,10 @@ //! When `serde-compat` is enabled, warnings are printed during build if unsupported serde //! attributes are encountered. Enabling this feature silences these warnings. //! +//! - `import-esm` +//! +//! `import` statements in the generated file will have the `.js` extension in the end of +//! the path to conform to the ES Modules spec. (e.g.: `import { MyStruct } from "./my_struct.js"`) //! //! If there's a type you're dealing with which doesn't implement `TS`, use `#[ts(type = "..")]` or open a PR. //! diff --git a/ts-rs/tests/imports.rs b/ts-rs/tests/imports.rs index 7674e09..bf1688b 100644 --- a/ts-rs/tests/imports.rs +++ b/ts-rs/tests/imports.rs @@ -31,6 +31,19 @@ fn test_def() { let text = std::fs::read_to_string(TestEnum::EXPORT_TO.unwrap()).unwrap(); // Checks to make sure imports are ordered and deduplicated + #[cfg(feature = "import-esm")] + assert_eq!(text, + concat!( + "// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.\n", + "import type { TestTypeA } from \"./ts_rs_test_type_a.js\";\n", + "import type { TestTypeB } from \"./ts_rs_test_type_b.js\";\n", + "\n", + "export type TestEnum = { \"C\": { value: TestTypeB } } | {\n", + " \"A1\": { value: TestTypeA };\n", + "} | { \"A2\": { value: TestTypeA } };\n" + ) + ); + #[cfg(not(feature = "import-esm"))] assert_eq!(text, concat!( "// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.\n", From 2da9e6ec04badd4b720c0965aa8135d332268461 Mon Sep 17 00:00:00 2001 From: Moritz Bischof Date: Mon, 22 Jan 2024 15:55:49 +0100 Subject: [PATCH 34/60] README.md - change to UTF-8 --- README.md | Bin 9130 -> 4409 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/README.md b/README.md index 09b2492e4c567db4efd22b80145da002e7beff0b..d1df8d5913ec97b88e7eb67158981581fbd5c761 100644 GIT binary patch literal 4409 zcmbtXZExH*68_F#F$-Pp55jW(cP0EN-u*`k+9Y1?GM^(%P( z6Liuy+Rn?xxj5Bb16!>^d$xG-!}I=b0p#nmMH@m-tD^97n>RYNLp2ck+S!0MH7@UMvjAzr*@BmBrt-zPNba5%?Td49+JE8lxoFU$mjNM+ zJyPv;A3$?B8(Cw)o1m~Z(#xQoCD?e^fgdO&0dZRN=R%w+efyQ_)9ZLK(nq?(6-k6$WyU-uuXWp(lODY59U*}P4$&Y4FLhW#dATlgNO4P0==Ci^Cu{Hak?XEE z*r5$6Gdpg8jq@qq7(gyATeN$zfiMX~Q=A)D1*t8B79Yx9E6$MgdTnu0Khr+H(ISg|MmN2+}UVP;l|1iSFjFV z+a~QB`PKFx(US-+KUmA@E^Fx<2b}0~`K^nBtu}@+l^jFGcgv~UXoFDBXeijvJWx61 zX@fGNQe=A&?Q7{9EoK7Iq0C^lv)?)&p(ZlW)@VDmG?4-KhJbcfSM2QG(`>OuBI!pi zdFKNql%+6ZH9F`96LfD`2ZP3<8Ot^$Q z%X#!Z(N>1kMYpGQ83*9l!Q+&{RK3StB<+Z}G%d9VW&RtLfOi2c53AgNd7Hbk+X#q@ zUWS%=zjl^kI=6r~Yk23>V32@%taCWVyvbLyEATtK8`p6_gFjL&Eb^ioZxYYvztN&R z5#nOQHatG#fhE2`MmIe3{1A~bC28Pkb=`t;NcLGcm{J(j%Q$|Nv42JdXRyfg#mRNa z^yzxEAmQJ?POa&X!{x-`A9<#V*|^V%^F!(12#@+(G&NABn4{xg%t#AT38{6D=Au$bN>KL5AZl$D(57EOWQ`g-YxhE%UF|UD@TGY8Xl~_6F(yw z*mxc--BchJG|_-dP@3w22!{ARc&o!dhicx83h&oc98h1s|K;-6i@$%ky!hp9-l_da z`NSdh3;C&I2dB6-UEN*ZE81!B03%2A)9=dF15fR7u$cDZw7Gxgr>@7-K2anBW_Z>e xJ2)3Ac&>eN`eQA3 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 XaX;%8KiFwVM+Y{+&vmR*^T>Yz2xkM3 From 4c5c194847d4800f5ed7c060a388c142b877bfd4 Mon Sep 17 00:00:00 2001 From: escritorio-gustavo <131818645+escritorio-gustavo@users.noreply.github.com> Date: Tue, 23 Jan 2024 12:17:52 -0300 Subject: [PATCH 35/60] Change CONTRIBUTING.md to avoid UTF-16 encoding issue (#201) --- CONTRIBUTING.md | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f1d62df..485516b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -3,8 +3,14 @@ If you are unsure what to work on or want to discuss your idea, feel free to ope ### Documentation After implementing a new feature, please document it in the doc comment on `TS` in `ts_rs/lib.rs`. -`README.md` is generated from the module doc comment in `ts_rs/lib.rs`. If you added/updated documentation there, run -`cargo readme > ../README.md` from the `ts-rs/` directory. +`README.md` is generated from the module doc comment in `ts_rs/lib.rs`. If you added/updated documentation there, go to the `ts-rs/` directory and run one of the following commands: + +On Windows: +`cargo readme -o ..\README.md` + +On other systems: +`cargo readme > ../README.md` + You can install `cargo readme` by running `cargo install cargo-readme`. @@ -16,4 +22,4 @@ There is nothing special going on here - just run `cargo build`. To run the test suite, just run `cargo test` in the root directory. ### Formatting -To ensure proper formatting, please run `cargo +nightly fmt`. \ No newline at end of file +To ensure proper formatting, please run `cargo +nightly fmt`. From a25875c6ee1c90e167dafcc74fa66be41ec580d2 Mon Sep 17 00:00:00 2001 From: Gustavo Date: Wed, 24 Jan 2024 17:24:30 -0300 Subject: [PATCH 36/60] Change declarations to use type instead of interface --- macros/src/types/named.rs | 2 +- ts-rs/tests/chrono.rs | 2 +- ts-rs/tests/export_manually.rs | 16 ++++------------ ts-rs/tests/generics.rs | 26 +++++++++++++------------- ts-rs/tests/indexmap.rs | 2 +- ts-rs/tests/lifetimes.rs | 4 ++-- ts-rs/tests/list.rs | 2 +- ts-rs/tests/ranges.rs | 2 +- ts-rs/tests/raw_idents.rs | 2 +- ts-rs/tests/serde-skip-with-default.rs | 2 +- ts-rs/tests/union_with_data.rs | 4 ++-- ts-rs/tests/unsized.rs | 2 +- 12 files changed, 29 insertions(+), 37 deletions(-) diff --git a/macros/src/types/named.rs b/macros/src/types/named.rs index 8786124..1a3249b 100644 --- a/macros/src/types/named.rs +++ b/macros/src/types/named.rs @@ -45,7 +45,7 @@ pub(crate) fn named( #fields, ) }, - decl: quote!(format!("interface {}{} {}", #name, #generic_args, Self::inline())), + decl: quote!(format!("type {}{} = {}", #name, #generic_args, Self::inline())), inline_flattened: Some(fields), name: name.to_owned(), dependencies, diff --git a/ts-rs/tests/chrono.rs b/ts-rs/tests/chrono.rs index cc52784..d9bc9ee 100644 --- a/ts-rs/tests/chrono.rs +++ b/ts-rs/tests/chrono.rs @@ -27,6 +27,6 @@ fn chrono() { assert_eq!( Chrono::decl(), - "interface Chrono { date: [string, string, string, string], time: string, date_time: [string, string, string, string], duration: string, month: string, weekday: string, }" + "type Chrono = { date: [string, string, string, string], time: string, date_time: [string, string, string, string], duration: string, month: string, weekday: string, }" ) } diff --git a/ts-rs/tests/export_manually.rs b/ts-rs/tests/export_manually.rs index aaae5cf..33a7af1 100644 --- a/ts-rs/tests/export_manually.rs +++ b/ts-rs/tests/export_manually.rs @@ -27,16 +27,12 @@ fn export_manually() { let expected_content = if cfg!(feature = "format") { concat!( "// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.\n\n", - "export interface User {\n", - " name: string;\n", - " age: number;\n", - " active: boolean;\n", - "}\n" + "export type User = { name: string; age: number; active: boolean };\n" ) } else { concat!( "// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.\n", - "\nexport interface User { name: string, age: number, active: boolean, }" + "\nexport type User = { name: string, age: number, active: boolean, }" ) }; @@ -52,16 +48,12 @@ fn export_manually_dir() { let expected_content = if cfg!(feature = "format") { concat!( "// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.\n\n", - "export interface UserDir {\n", - " name: string;\n", - " age: number;\n", - " active: boolean;\n", - "}\n" + "export type UserDir = { name: string; age: number; active: boolean };\n" ) } else { concat!( "// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.\n", - "\nexport interface UserDir { name: string, age: number, active: boolean, }" + "\nexport type UserDir = { name: string, age: number, active: boolean, }" ) }; diff --git a/ts-rs/tests/generics.rs b/ts-rs/tests/generics.rs index 5dad985..cd8cd68 100644 --- a/ts-rs/tests/generics.rs +++ b/ts-rs/tests/generics.rs @@ -60,27 +60,27 @@ declare! { fn test() { assert_eq!( TypeGroup::decl(), - "interface TypeGroup { foo: Array, }", + "type TypeGroup = { foo: Array, }", ); assert_eq!( Generic::<()>::decl(), - "interface Generic { value: T, values: Array, }" + "type Generic = { value: T, values: Array, }" ); assert_eq!( GenericAutoBound::<()>::decl(), - "interface GenericAutoBound { value: T, values: Array, }" + "type GenericAutoBound = { value: T, values: Array, }" ); assert_eq!( GenericAutoBound2::<()>::decl(), - "interface GenericAutoBound2 { value: T, values: Array, }" + "type GenericAutoBound2 = { value: T, values: Array, }" ); assert_eq!( Container::decl(), - "interface Container { foo: Generic, bar: Array>, baz: Record>, }" + "type Container = { foo: Generic, bar: Array>, baz: Record>, }" ); } @@ -142,7 +142,7 @@ fn generic_struct() { assert_eq!( Struct::<()>::decl(), - "interface Struct { a: T, b: [T, T], c: [T, [T, T]], d: Array, e: Array<[T, T]>, f: Array, g: Array>, h: Array>, }" + "type Struct = { a: T, b: [T, T], c: [T, [T, T]], d: Array, e: Array<[T, T]>, f: Array, g: Array>, h: Array>, }" ) } @@ -164,10 +164,10 @@ fn inline() { t: Generic, } - assert_eq!(Generic::<()>::decl(), "interface Generic { t: T, }"); + assert_eq!(Generic::<()>::decl(), "type Generic = { t: T, }"); assert_eq!( Container::decl(), - "interface Container { g: Generic, gi: { t: string }, t: string, }" + "type Container = { g: Generic, gi: { t: string }, t: string, }" ); } @@ -177,7 +177,7 @@ fn default() { struct A { t: T, } - assert_eq!(A::<()>::decl(), "interface A { t: T, }"); + assert_eq!(A::<()>::decl(), "type A = { t: T, }"); #[derive(TS)] struct B>> { @@ -185,7 +185,7 @@ fn default() { } assert_eq!( B::<()>::decl(), - "interface B | null> { u: U, }" + "type B | null> = { u: U, }" ); assert!(B::<()>::dependencies().iter().any(|dep| dep.ts_name == "A")); @@ -200,7 +200,7 @@ fn default() { // #[ts(inline)] // xi2: X } - assert_eq!(Y::decl(), "interface Y { a1: A, a2: A, }") + assert_eq!(Y::decl(), "type Y = { a1: A, a2: A, }") } #[test] @@ -209,7 +209,7 @@ fn trait_bounds() { struct A { t: T, } - assert_eq!(A::::decl(), "interface A { t: T, }"); + assert_eq!(A::::decl(), "type A = { t: T, }"); #[derive(TS)] struct B(T); @@ -232,5 +232,5 @@ fn trait_bounds() { t: [T; N], } - assert_eq!(D::<&str, 41>::decl(), "interface D { t: Array, }") + assert_eq!(D::<&str, 41>::decl(), "type D = { t: Array, }") } diff --git a/ts-rs/tests/indexmap.rs b/ts-rs/tests/indexmap.rs index 8b7b05e..7c8eb20 100644 --- a/ts-rs/tests/indexmap.rs +++ b/ts-rs/tests/indexmap.rs @@ -14,6 +14,6 @@ fn indexmap() { assert_eq!( Indexes::decl(), - "interface Indexes { map: Record, set: Array, }" + "type Indexes = { map: Record, set: Array, }" ) } diff --git a/ts-rs/tests/lifetimes.rs b/ts-rs/tests/lifetimes.rs index 835610e..10abf37 100644 --- a/ts-rs/tests/lifetimes.rs +++ b/ts-rs/tests/lifetimes.rs @@ -8,7 +8,7 @@ fn contains_borrow() { s: &'a str, } - assert_eq!(S::decl(), "interface S { s: string, }") + assert_eq!(S::decl(), "type S = { s: string, }") } #[test] @@ -29,6 +29,6 @@ fn contains_borrow_type_args() { assert_eq!( A::decl(), - "interface A { a: Array, b: Array>, c: Record, }" + "type A = { a: Array, b: Array>, c: Record, }" ); } diff --git a/ts-rs/tests/list.rs b/ts-rs/tests/list.rs index 65aaa00..dfa3126 100644 --- a/ts-rs/tests/list.rs +++ b/ts-rs/tests/list.rs @@ -10,6 +10,6 @@ fn list() { assert_eq!( List::decl(), - "interface List { data: Array | null, }" + "type List = { data: Array | null, }" ); } diff --git a/ts-rs/tests/ranges.rs b/ts-rs/tests/ranges.rs index ac99070..10cdcd6 100644 --- a/ts-rs/tests/ranges.rs +++ b/ts-rs/tests/ranges.rs @@ -19,7 +19,7 @@ struct RangeTest { fn range() { assert_eq!( RangeTest::decl(), - "interface RangeTest { a: { start: number, end: number, }, b: { start: string, end: string, }, c: { start: { start: number, end: number, }, end: { start: number, end: number, }, }, d: { start: number, end: number, }, e: { start: Inner, end: Inner, }, }" + "type RangeTest = { a: { start: number, end: number, }, b: { start: string, end: string, }, c: { start: { start: number, end: number, }, end: { start: number, end: number, }, }, d: { start: number, end: number, }, e: { start: Inner, end: Inner, }, }" ); assert_eq!( RangeTest::dependencies(), diff --git a/ts-rs/tests/raw_idents.rs b/ts-rs/tests/raw_idents.rs index 51ee787..9fae879 100644 --- a/ts-rs/tests/raw_idents.rs +++ b/ts-rs/tests/raw_idents.rs @@ -15,6 +15,6 @@ fn raw_idents() { let out = ::decl(); assert_eq!( out, - "interface enum { type: number, use: number, struct: number, let: number, enum: number, }" + "type enum = { type: number, use: number, struct: number, let: number, enum: number, }" ); } diff --git a/ts-rs/tests/serde-skip-with-default.rs b/ts-rs/tests/serde-skip-with-default.rs index 6287f36..5f970af 100644 --- a/ts-rs/tests/serde-skip-with-default.rs +++ b/ts-rs/tests/serde-skip-with-default.rs @@ -22,6 +22,6 @@ pub struct Foobar { fn serde_skip_with_default() { assert_eq!( Foobar::decl(), - "interface Foobar { something_else: number, }" + "type Foobar = { something_else: number, }" ); } diff --git a/ts-rs/tests/union_with_data.rs b/ts-rs/tests/union_with_data.rs index 2c69739..b35f368 100644 --- a/ts-rs/tests/union_with_data.rs +++ b/ts-rs/tests/union_with_data.rs @@ -24,10 +24,10 @@ enum SimpleEnum { #[test] fn test_stateful_enum() { - assert_eq!(Bar::decl(), r#"interface Bar { field: number, }"#); + assert_eq!(Bar::decl(), r#"type Bar = { field: number, }"#); assert_eq!(Bar::dependencies(), vec![]); - assert_eq!(Foo::decl(), r#"interface Foo { bar: Bar, }"#); + assert_eq!(Foo::decl(), r#"type Foo = { bar: Bar, }"#); assert_eq!( Foo::dependencies(), vec![Dependency::from_ty::().unwrap()] diff --git a/ts-rs/tests/unsized.rs b/ts-rs/tests/unsized.rs index 61c0a26..bfddf75 100644 --- a/ts-rs/tests/unsized.rs +++ b/ts-rs/tests/unsized.rs @@ -15,6 +15,6 @@ fn contains_str() { assert_eq!( S::decl(), - "interface S { b: string, c: string, r: string, a: string, }" + "type S = { b: string, c: string, r: string, a: string, }" ) } From 4b26418400cc21e2b0ca050664270ea654fba022 Mon Sep 17 00:00:00 2001 From: Gustavo Date: Thu, 25 Jan 2024 08:56:57 -0300 Subject: [PATCH 37/60] Reimplementation of enum flattening --- macros/src/types/enum.rs | 8 ++- macros/src/types/named.rs | 19 +++--- ts-rs/tests/enum_flattening.rs | 104 +++++++++++++++++++++++++++++++++ ts-rs/tests/flatten.rs | 2 +- 4 files changed, 123 insertions(+), 10 deletions(-) create mode 100644 ts-rs/tests/enum_flattening.rs diff --git a/macros/src/types/enum.rs b/macros/src/types/enum.rs index 4c73b75..1076f76 100644 --- a/macros/src/types/enum.rs +++ b/macros/src/types/enum.rs @@ -50,7 +50,11 @@ pub(crate) fn r#enum_def(s: &ItemEnum) -> syn::Result { Ok(DerivedTS { inline: quote!([#(#formatted_variants),*].join(" | ")), decl: quote!(format!("type {}{} = {};", #name, #generic_args, Self::inline())), - inline_flattened: None, + inline_flattened: Some( + quote!( + format!("({})", [#(#formatted_variants),*].join(" | ")) + ) + ), dependencies, name, export: enum_attr.export, @@ -130,7 +134,7 @@ fn format_variant( "{{ \"{}\": \"{}\", {} }}", #tag, #name, - #inline_flattened + #inline_flattened.trim_matches(&['{', '}', ' ']) ) }, None => match &variant.fields { diff --git a/macros/src/types/named.rs b/macros/src/types/named.rs index 1a3249b..4f9c923 100644 --- a/macros/src/types/named.rs +++ b/macros/src/types/named.rs @@ -17,6 +17,7 @@ pub(crate) fn named( generics: &Generics, ) -> Result { let mut formatted_fields = Vec::new(); + let mut flattened_fields = Vec::new(); let mut dependencies = Dependencies::default(); if let Some(tag) = &attr.tag { let formatted = format!("{}: \"{}\",", tag, name); @@ -28,6 +29,7 @@ pub(crate) fn named( for field in &fields.named { format_field( &mut formatted_fields, + &mut flattened_fields, &mut dependencies, field, &attr.rename_all, @@ -36,17 +38,19 @@ pub(crate) fn named( } let fields = quote!(<[String]>::join(&[#(#formatted_fields),*], " ")); + let flattened = quote!(<[String]>::join(&[#(#flattened_fields),*], " & ")); let generic_args = format_generics(&mut dependencies, generics); Ok(DerivedTS { - inline: quote! { - format!( - "{{ {} }}", - #fields, - ) + inline: match (formatted_fields.len(), flattened_fields.len()) { + (0, 0) => quote!("{ }".to_owned()), + (_, 0) => quote!(format!("{{ {} }}", #fields)), + (0, 1) => quote!(#flattened.trim_matches(|c| c == '(' || c == ')').to_owned()), + (0, _) => quote!(#flattened), + (_, _) => quote!(format!("{{ {} }} & {}", #fields, #flattened)), }, decl: quote!(format!("type {}{} = {}", #name, #generic_args, Self::inline())), - inline_flattened: Some(fields), + inline_flattened: Some(quote!(format!("{{ {} }}", #fields))), name: name.to_owned(), dependencies, export: attr.export, @@ -57,6 +61,7 @@ pub(crate) fn named( // build an expresion which expands to a string, representing a single field of a struct. fn format_field( formatted_fields: &mut Vec, + flattened_fields: &mut Vec, dependencies: &mut Dependencies, field: &Field, rename_all: &Option, @@ -88,7 +93,7 @@ fn format_field( _ => {} } - formatted_fields.push(quote!(<#ty as ts_rs::TS>::inline_flattened())); + flattened_fields.push(quote!(<#ty as ts_rs::TS>::inline_flattened())); dependencies.append_from(ty); return Ok(()); } diff --git a/ts-rs/tests/enum_flattening.rs b/ts-rs/tests/enum_flattening.rs new file mode 100644 index 0000000..1055329 --- /dev/null +++ b/ts-rs/tests/enum_flattening.rs @@ -0,0 +1,104 @@ +use serde::Serialize; +use ts_rs::TS; + +#[test] +#[cfg(feature = "serde-compat")] +fn externally_tagged() { + #[derive(Serialize, TS)] + struct Foo { + qux: i32, + #[serde(flatten)] + baz: Bar, + biz: Option, + } + + #[derive(Serialize, TS)] + #[allow(dead_code)] + enum Bar { + Baz { a: i32, a2: String }, + Biz { b: bool }, + Buz { c: String, d: Option }, + } + + assert_eq!( + Foo::inline(), + r#"{ qux: number, biz: string | null, } & ({ "Baz": { a: number, a2: string, } } | { "Biz": { b: boolean, } } | { "Buz": { c: string, d: number | null, } })"# + ) +} + +#[test] +#[cfg(feature = "serde-compat")] +fn adjacently_tagged() { + #[derive(Serialize, TS)] + struct Foo { + one: i32, + #[serde(flatten)] + baz: Bar, + qux: Option, + } + + #[derive(Serialize, TS)] + #[allow(dead_code)] + #[serde(tag = "type", content = "stuff")] + enum Bar { + Baz { a: i32, a2: String }, + Biz { b: bool }, + Buz { c: String, d: Option }, + } + + assert_eq!( + Foo::inline(), + r#"{ one: number, qux: string | null, } & ({ "type": "Baz", "stuff": { a: number, a2: string, } } | { "type": "Biz", "stuff": { b: boolean, } } | { "type": "Buz", "stuff": { c: string, d: number | null, } })"# + ) +} + +#[test] +#[cfg(feature = "serde-compat")] +fn internally_tagged() { + #[derive(Serialize, TS)] + struct Foo { + qux: Option, + + #[serde(flatten)] + baz: Bar, + } + + #[derive(Serialize, TS)] + #[allow(dead_code)] + #[serde(tag = "type")] + enum Bar { + Baz { a: i32, a2: String }, + Biz { b: bool }, + Buz { c: String, d: Option }, + } + + assert_eq!( + Foo::inline(), + r#"{ qux: string | null, } & ({ "type": "Baz", a: number, a2: string, } | { "type": "Biz", b: boolean, } | { "type": "Buz", c: string, d: number | null, })"# + ) +} + +#[test] +#[cfg(feature = "serde-compat")] +fn untagged() { + #[derive(Serialize, TS)] + struct Foo { + #[serde(flatten)] + baz: Bar, + } + + #[derive(Serialize, TS)] + #[allow(dead_code)] + #[serde(untagged)] + enum Bar { + Baz { a: i32, a2: String }, + Biz { b: bool }, + Buz { c: String }, + } + + assert_eq!( + Foo::inline(), + r#"{ a: number, a2: string, } | { b: boolean, } | { c: string, }"# + ) +} + diff --git a/ts-rs/tests/flatten.rs b/ts-rs/tests/flatten.rs index 837c9b6..343e3f0 100644 --- a/ts-rs/tests/flatten.rs +++ b/ts-rs/tests/flatten.rs @@ -26,6 +26,6 @@ struct C { fn test_def() { assert_eq!( C::inline(), - "{ b: { a: number, b: number, c: number, }, d: number, }" + "{ b: { c: number, } & { a: number, b: number, }, d: number, }" ); } From e5929a84883627fadcf19c1b7f54cb01f8268fc3 Mon Sep 17 00:00:00 2001 From: Gustavo Date: Thu, 25 Jan 2024 10:29:26 -0300 Subject: [PATCH 38/60] Simplify flattening of named structs --- macros/src/types/named.rs | 16 +++++++++------- ts-rs/tests/flatten.rs | 2 +- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/macros/src/types/named.rs b/macros/src/types/named.rs index 4f9c923..987bb37 100644 --- a/macros/src/types/named.rs +++ b/macros/src/types/named.rs @@ -41,14 +41,16 @@ pub(crate) fn named( let flattened = quote!(<[String]>::join(&[#(#flattened_fields),*], " & ")); let generic_args = format_generics(&mut dependencies, generics); + let inline = match (formatted_fields.len(), flattened_fields.len()) { + (0, 0) => quote!("{ }".to_owned()), + (_, 0) => quote!(format!("{{ {} }}", #fields)), + (0, 1) => quote!(#flattened.trim_matches(|c| c == '(' || c == ')').to_owned()), + (0, _) => quote!(#flattened), + (_, _) => quote!(format!("{{ {} }} & {}", #fields, #flattened)), + }; + Ok(DerivedTS { - inline: match (formatted_fields.len(), flattened_fields.len()) { - (0, 0) => quote!("{ }".to_owned()), - (_, 0) => quote!(format!("{{ {} }}", #fields)), - (0, 1) => quote!(#flattened.trim_matches(|c| c == '(' || c == ')').to_owned()), - (0, _) => quote!(#flattened), - (_, _) => quote!(format!("{{ {} }} & {}", #fields, #flattened)), - }, + inline: quote!(#inline.replace(" } & { ", " ")), decl: quote!(format!("type {}{} = {}", #name, #generic_args, Self::inline())), inline_flattened: Some(quote!(format!("{{ {} }}", #fields))), name: name.to_owned(), diff --git a/ts-rs/tests/flatten.rs b/ts-rs/tests/flatten.rs index 343e3f0..5621249 100644 --- a/ts-rs/tests/flatten.rs +++ b/ts-rs/tests/flatten.rs @@ -26,6 +26,6 @@ struct C { fn test_def() { assert_eq!( C::inline(), - "{ b: { c: number, } & { a: number, b: number, }, d: number, }" + "{ b: { c: number, a: number, b: number, }, d: number, }" ); } From d2ad614f3aadc80f8240738bd0370885916c6450 Mon Sep 17 00:00:00 2001 From: escritorio-gustavo <131818645+escritorio-gustavo@users.noreply.github.com> Date: Thu, 25 Jan 2024 12:44:29 -0300 Subject: [PATCH 39/60] Fix CI badge --- ts-rs/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ts-rs/src/lib.rs b/ts-rs/src/lib.rs index c52eb95..90ecc14 100644 --- a/ts-rs/src/lib.rs +++ b/ts-rs/src/lib.rs @@ -9,7 +9,7 @@ //! //!
//! -//! actions status +//! actions status //! //! Crates.io version From deb51947dc04d108e669de656b3ed0e11f3d0f89 Mon Sep 17 00:00:00 2001 From: escritorio-gustavo <131818645+escritorio-gustavo@users.noreply.github.com> Date: Thu, 25 Jan 2024 12:46:41 -0300 Subject: [PATCH 40/60] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d1df8d5..af2291e 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ generate typescript interface/type declarations from rust types
-actions status +actions status Crates.io version From d6b862f9ee60811218a5d331244b14b62fed23d3 Mon Sep 17 00:00:00 2001 From: Trangar Date: Thu, 25 Jan 2024 16:58:01 +0100 Subject: [PATCH 41/60] Made the TS implementation for hashmap and hashset generic over all hashers (#173) * Made the TS implementation for hashmap and hashset generic over all hashers * Added hashmap tests * Change tests to expect type instead of interface --------- Co-authored-by: Victor Koenders Co-authored-by: escritorio-gustavo <131818645+escritorio-gustavo@users.noreply.github.com> --- ts-rs/src/lib.rs | 4 ++-- ts-rs/tests/hashmap.rs | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 ts-rs/tests/hashmap.rs diff --git a/ts-rs/src/lib.rs b/ts-rs/src/lib.rs index 90ecc14..464e44c 100644 --- a/ts-rs/src/lib.rs +++ b/ts-rs/src/lib.rs @@ -521,7 +521,7 @@ impl TS for Vec { } } -impl TS for HashMap { +impl TS for HashMap { fn name() -> String { "Record".to_owned() } @@ -610,7 +610,7 @@ impl TS for RangeInclusive { } impl_shadow!(as T: impl<'a, T: TS + ?Sized> TS for &T); -impl_shadow!(as Vec: impl TS for HashSet); +impl_shadow!(as Vec: impl TS for HashSet); impl_shadow!(as Vec: impl TS for BTreeSet); impl_shadow!(as HashMap: impl TS for BTreeMap); impl_shadow!(as Vec: impl TS for [T; N]); diff --git a/ts-rs/tests/hashmap.rs b/ts-rs/tests/hashmap.rs new file mode 100644 index 0000000..a588e9c --- /dev/null +++ b/ts-rs/tests/hashmap.rs @@ -0,0 +1,37 @@ +use std::collections::{HashMap, HashSet}; +use ts_rs::TS; + +#[test] +fn hashmap() { + #[derive(TS)] + #[allow(dead_code)] + struct Hashes { + map: HashMap, + set: HashSet, + } + + assert_eq!( + Hashes::decl(), + "type Hashes = { map: Record, set: Array, }" + ) +} + +#[test] +fn hashmap_with_custom_hasher() { + struct CustomHasher {} + + type CustomHashMap = HashMap; + type CustomHashSet = HashSet; + + #[derive(TS)] + #[allow(dead_code)] + struct Hashes { + map: CustomHashMap, + set: CustomHashSet, + } + + assert_eq!( + Hashes::decl(), + "type Hashes = { map: Record, set: Array, }" + ) +} From a3e0f211694df59ddaf3c2645a0ce93f700c13c8 Mon Sep 17 00:00:00 2001 From: NyxCode Date: Thu, 25 Jan 2024 17:41:56 +0100 Subject: [PATCH 42/60] Remove support for "skip_serializing", "skip_deserializing" and "skip_serializing_if" (#204) * remove support for "skip_serializing", "skip_deserializing" and "skip_serializing_if" * add changelog * fix typo --- CHANGELOG.md | 5 +++++ README.md | 6 +++--- example/src/lib.rs | 2 +- macros/src/attr/field.rs | 3 --- macros/src/attr/variant.rs | 2 -- ts-rs/src/lib.rs | 6 +++--- ts-rs/tests/optional_field.rs | 6 +----- 7 files changed, 13 insertions(+), 17 deletions(-) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..fce6d7a --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,5 @@ +# master + +- Remove support for "skip_serializing", "skip_serializing_if" and "skip_deserializing". + - Initially supporting these by skipping a field was a mistake. If a user wishes to skip a field, they can still + annotate it with `#[ts(skip)]` \ No newline at end of file diff --git a/README.md b/README.md index af2291e..158a86c 100644 --- a/README.md +++ b/README.md @@ -131,12 +131,12 @@ Supported serde attributes: - `content` - `untagged` - `skip` -- `skip_serializing` -- `skip_deserializing` -- `skip_serializing_if = "Option::is_none"` - `flatten` - `default` +Note: `skip_serializing` and `skip_deserializing` are ignored. If you wish to exclude a field +from the generated type, but cannot use `#[serde(skip)]`, use `#[ts(skip)]` instead. + When ts-rs encounters an unsupported serde attribute, a warning is emitted, unless the feature `no-serde-warnings` is enabled. ### contributing diff --git a/example/src/lib.rs b/example/src/lib.rs index dfdbd81..81e847a 100644 --- a/example/src/lib.rs +++ b/example/src/lib.rs @@ -102,6 +102,6 @@ enum InlineComplexEnum { #[serde(rename_all = "camelCase")] #[ts(export)] struct ComplexStruct { - #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde(default)] pub string_tree: Option>>, } diff --git a/macros/src/attr/field.rs b/macros/src/attr/field.rs index 0c91b1c..aab124a 100644 --- a/macros/src/attr/field.rs +++ b/macros/src/attr/field.rs @@ -65,9 +65,6 @@ impl_parse! { SerdeFieldAttr(input, out) { "rename" => out.0.rename = Some(parse_assign_str(input)?), "skip" => out.0.skip = true, - "skip_serializing" => out.0.skip = true, - "skip_deserializing" => out.0.skip = true, - "skip_serializing_if" => out.0.optional = parse_assign_str(input)? == *"Option::is_none", "flatten" => out.0.flatten = true, // parse #[serde(default)] to not emit a warning "default" => { diff --git a/macros/src/attr/variant.rs b/macros/src/attr/variant.rs index 1f490db..74a3c28 100644 --- a/macros/src/attr/variant.rs +++ b/macros/src/attr/variant.rs @@ -60,7 +60,5 @@ impl_parse! { "rename" => out.0.rename = Some(parse_assign_str(input)?), "rename_all" => out.0.rename_all = Some(parse_assign_inflection(input)?), "skip" => out.0.skip = true, - "skip_serializing" => out.0.skip = true, - "skip_deserializing" => out.0.skip = true, } } diff --git a/ts-rs/src/lib.rs b/ts-rs/src/lib.rs index 464e44c..66dd451 100644 --- a/ts-rs/src/lib.rs +++ b/ts-rs/src/lib.rs @@ -129,12 +129,12 @@ //! - `content` //! - `untagged` //! - `skip` -//! - `skip_serializing` -//! - `skip_deserializing` -//! - `skip_serializing_if = "Option::is_none"` //! - `flatten` //! - `default` //! +//! Note: `skip_serializing` and `skip_deserializing` are ignored. If you wish to exclude a field +//! from the generated type, but cannot use `#[serde(skip)]`, use `#[ts(skip)]` instead. +//! //! When ts-rs encounters an unsupported serde attribute, a warning is emitted, unless the feature `no-serde-warnings` is enabled. //! //! ## contributing diff --git a/ts-rs/tests/optional_field.rs b/ts-rs/tests/optional_field.rs index 807e9da..4912584 100644 --- a/ts-rs/tests/optional_field.rs +++ b/ts-rs/tests/optional_field.rs @@ -7,14 +7,10 @@ use ts_rs::TS; struct Optional { #[ts(optional)] a: Option, - #[serde(skip_serializing_if = "Option::is_none")] - b: Option, + b: Option } #[test] fn test() { - #[cfg(not(feature = "serde-compat"))] assert_eq!(Optional::inline(), "{ a?: number, b: string | null, }"); - #[cfg(feature = "serde-compat")] - assert_eq!(Optional::inline(), "{ a?: number, b?: string, }") } From c96b999f85f4a55290adcbea65272ca803147102 Mon Sep 17 00:00:00 2001 From: Gustavo Date: Thu, 25 Jan 2024 13:46:46 -0300 Subject: [PATCH 43/60] Fix tests to remove warning and test for `serde-compat` being off --- ts-rs/tests/enum_flattening.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ts-rs/tests/enum_flattening.rs b/ts-rs/tests/enum_flattening.rs index 1055329..4e4ef30 100644 --- a/ts-rs/tests/enum_flattening.rs +++ b/ts-rs/tests/enum_flattening.rs @@ -2,9 +2,8 @@ use serde::Serialize; use ts_rs::TS; #[test] -#[cfg(feature = "serde-compat")] fn externally_tagged() { - #[derive(Serialize, TS)] + #[cfg_attr(feature = "serde-compat", derive(Serialize, TS))] struct Foo { qux: i32, #[serde(flatten)] From fa682c364bc87ddff639864d94c03e0b270cdbfc Mon Sep 17 00:00:00 2001 From: Gustavo Date: Thu, 25 Jan 2024 13:49:00 -0300 Subject: [PATCH 44/60] Fix test --- ts-rs/tests/enum_flattening.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/ts-rs/tests/enum_flattening.rs b/ts-rs/tests/enum_flattening.rs index 4e4ef30..5f19e95 100644 --- a/ts-rs/tests/enum_flattening.rs +++ b/ts-rs/tests/enum_flattening.rs @@ -1,17 +1,21 @@ +#[cfg(feature = "serde-compat")] use serde::Serialize; use ts_rs::TS; #[test] fn externally_tagged() { #[cfg_attr(feature = "serde-compat", derive(Serialize, TS))] + #[cfg_attr(not(feature = "serde-compat"), derive(TS))] struct Foo { qux: i32, - #[serde(flatten)] + #[cfg_attr(feature = "serde-compat", serde(flatten))] + #[cfg_attr(not(feature = "serde-compat"), ts(flatten))] baz: Bar, biz: Option, } - #[derive(Serialize, TS)] + #[cfg_attr(feature = "serde-compat", derive(Serialize, TS))] + #[cfg_attr(not(feature = "serde-compat"), derive(TS))] #[allow(dead_code)] enum Bar { Baz { a: i32, a2: String }, From 7eefc38f6fd0b774621d8e6d34832e3582d394d6 Mon Sep 17 00:00:00 2001 From: Gustavo Date: Thu, 25 Jan 2024 14:03:35 -0300 Subject: [PATCH 45/60] Clarify the need for .trim_matches() --- macros/src/types/enum.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/macros/src/types/enum.rs b/macros/src/types/enum.rs index 1076f76..f5ccf63 100644 --- a/macros/src/types/enum.rs +++ b/macros/src/types/enum.rs @@ -134,6 +134,14 @@ fn format_variant( "{{ \"{}\": \"{}\", {} }}", #tag, #name, + // At this point inline_flattened looks like + // { /* ...data */ } + // + // To be flattened, an internally tagged enum must not be + // surrounded by braces, otherwise each variant will look like + // { "tag": "name", { /* ...data */ } } + // + // which is invalid since there is no key before the brackets #inline_flattened.trim_matches(&['{', '}', ' ']) ) }, From f4d4d0065679bfe9674e8fddfe52e7195515b14f Mon Sep 17 00:00:00 2001 From: Gustavo Date: Thu, 25 Jan 2024 14:09:43 -0300 Subject: [PATCH 46/60] Clarify format_field parameters --- macros/src/types/named.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/macros/src/types/named.rs b/macros/src/types/named.rs index 987bb37..3ec97d0 100644 --- a/macros/src/types/named.rs +++ b/macros/src/types/named.rs @@ -61,6 +61,15 @@ pub(crate) fn named( } // build an expresion which expands to a string, representing a single field of a struct. +// +// formatted_fields will contain all the fields that do not contain the flatten +// attribute, in the format +// key: type, +// +// flattened_fields will contain all the fields that contain the flatten attribute +// in their respective formats, which for a named struct is the same as formatted_fields, +// but for enums is +// ({ /* variant data */ } | { /* variant data */ }) fn format_field( formatted_fields: &mut Vec, flattened_fields: &mut Vec, From 5258e30617696adf2738ce1cb1a267484913a1ff Mon Sep 17 00:00:00 2001 From: Gustavo Date: Thu, 25 Jan 2024 14:13:18 -0300 Subject: [PATCH 47/60] Silence warning --- ts-rs/tests/enum_flattening.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/ts-rs/tests/enum_flattening.rs b/ts-rs/tests/enum_flattening.rs index 5f19e95..c26ef05 100644 --- a/ts-rs/tests/enum_flattening.rs +++ b/ts-rs/tests/enum_flattening.rs @@ -4,6 +4,7 @@ use ts_rs::TS; #[test] fn externally_tagged() { + #[allow(dead_code)] #[cfg_attr(feature = "serde-compat", derive(Serialize, TS))] #[cfg_attr(not(feature = "serde-compat"), derive(TS))] struct Foo { From 708016f52ec6965761cfd6bf7252da6160cfe880 Mon Sep 17 00:00:00 2001 From: Gustavo Date: Thu, 25 Jan 2024 14:14:34 -0300 Subject: [PATCH 48/60] Make trim_matches comment more accurate --- macros/src/types/enum.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/macros/src/types/enum.rs b/macros/src/types/enum.rs index f5ccf63..0cfcfd9 100644 --- a/macros/src/types/enum.rs +++ b/macros/src/types/enum.rs @@ -140,8 +140,8 @@ fn format_variant( // To be flattened, an internally tagged enum must not be // surrounded by braces, otherwise each variant will look like // { "tag": "name", { /* ...data */ } } - // - // which is invalid since there is no key before the brackets + // when we want it to look like + // { "tag": "name", /* ...data */ } #inline_flattened.trim_matches(&['{', '}', ' ']) ) }, From 906497eb85b0034e9a540ee0ac3e9596a78f112e Mon Sep 17 00:00:00 2001 From: Tim Date: Fri, 26 Jan 2024 04:32:47 +0100 Subject: [PATCH 49/60] test: add semver --- ts-rs/tests/semver.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 ts-rs/tests/semver.rs diff --git a/ts-rs/tests/semver.rs b/ts-rs/tests/semver.rs new file mode 100644 index 0000000..1e3a983 --- /dev/null +++ b/ts-rs/tests/semver.rs @@ -0,0 +1,18 @@ +#![allow(deprecated)] +#![cfg(feature = "chrono-impl")] + +use semver::Version; +use ts_rs::TS; + +#[test] +fn semver() { + #[derive(TS)] + struct Semver { + version: Version, + } + + assert_eq!( + Semver::decl(), + "type Semver = { version: string, }" + ) +} From bc2ea6dde60764f42c1fa17fa003b55710ea8ea3 Mon Sep 17 00:00:00 2001 From: Tim Date: Fri, 26 Jan 2024 04:34:37 +0100 Subject: [PATCH 50/60] test(semver): allow dead code --- ts-rs/tests/semver.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/ts-rs/tests/semver.rs b/ts-rs/tests/semver.rs index 1e3a983..03d1b5f 100644 --- a/ts-rs/tests/semver.rs +++ b/ts-rs/tests/semver.rs @@ -8,6 +8,7 @@ use ts_rs::TS; fn semver() { #[derive(TS)] struct Semver { + #[allow(dead_code)] version: Version, } From 0d1a0803e15e650496bbb8fb208d10eb84a3902f Mon Sep 17 00:00:00 2001 From: Tim Date: Fri, 26 Jan 2024 04:37:30 +0100 Subject: [PATCH 51/60] fix: semver dependency --- ts-rs/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ts-rs/Cargo.toml b/ts-rs/Cargo.toml index e9c39b6..89c8e3e 100644 --- a/ts-rs/Cargo.toml +++ b/ts-rs/Cargo.toml @@ -49,7 +49,7 @@ uuid = { version = "1.1.2", optional = true } bson = { version = "2.2.0", optional = true } bytes = { version = "1.0", optional = true } url = { version = "2.3", optional = true } -semver = { semver = "3.0.0", optional = true } +semver = { version = "1.0.21", optional = true } thiserror = "1" indexmap = { version = "2.0.0", optional = true } ordered-float = { version = "3.0.0", optional = true } From 8f2000f8bf26d5b47b6b8281d783a07156a935ad Mon Sep 17 00:00:00 2001 From: Tim Date: Fri, 26 Jan 2024 12:19:20 +0100 Subject: [PATCH 52/60] test(semver): wrong feature derive --- ts-rs/tests/semver.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ts-rs/tests/semver.rs b/ts-rs/tests/semver.rs index 03d1b5f..5e6ebb8 100644 --- a/ts-rs/tests/semver.rs +++ b/ts-rs/tests/semver.rs @@ -1,5 +1,4 @@ -#![allow(deprecated)] -#![cfg(feature = "chrono-impl")] +#![cfg(feature = "semver-impl")] use semver::Version; use ts_rs::TS; From 60737cbcbdb00c23f9a1ae8b06bb4c72bea717ea Mon Sep 17 00:00:00 2001 From: escritorio-gustavo <131818645+escritorio-gustavo@users.noreply.github.com> Date: Fri, 26 Jan 2024 09:30:38 -0300 Subject: [PATCH 53/60] Update lib.rs doc comment This was fixed in #128 and improved upon in #181 and #199 --- ts-rs/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ts-rs/src/lib.rs b/ts-rs/src/lib.rs index 6fddf47..0df2bc5 100644 --- a/ts-rs/src/lib.rs +++ b/ts-rs/src/lib.rs @@ -151,7 +151,7 @@ //! - [x] use typescript types across files //! - [x] more enum representations //! - [x] generics -//! - [ ] don't require `'static` +//! - [x] don't require `'static` use std::{ any::TypeId, From aa3d8f8efe9d99a5a1e97479d3f653fbc50f0363 Mon Sep 17 00:00:00 2001 From: escritorio-gustavo <131818645+escritorio-gustavo@users.noreply.github.com> Date: Fri, 26 Jan 2024 09:31:31 -0300 Subject: [PATCH 54/60] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9c745da..03b41ea 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,6 @@ Feel free to open an issue, discuss using GitHub discussions or open a PR. - [x] use typescript types across files - [x] more enum representations - [x] generics -- [ ] don't require `'static` +- [x] don't require `'static` License: MIT From 6ccbcce516863ddf47b8a4db94c90e844ee5c639 Mon Sep 17 00:00:00 2001 From: escritorio-gustavo <131818645+escritorio-gustavo@users.noreply.github.com> Date: Fri, 26 Jan 2024 09:32:22 -0300 Subject: [PATCH 55/60] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9c745da..03b41ea 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,6 @@ Feel free to open an issue, discuss using GitHub discussions or open a PR. - [x] use typescript types across files - [x] more enum representations - [x] generics -- [ ] don't require `'static` +- [x] don't require `'static` License: MIT From a3ac452e44872a9e350d718927d18f9da1a8134d Mon Sep 17 00:00:00 2001 From: Gustavo Date: Fri, 26 Jan 2024 10:37:51 -0300 Subject: [PATCH 56/60] Run cargo fmt --- macros/src/types/enum.rs | 10 ++++------ ts-rs/src/lib.rs | 2 +- ts-rs/tests/enum_flattening.rs | 1 - ts-rs/tests/enum_struct_rename_all.rs | 7 +++++-- ts-rs/tests/generics.rs | 5 +---- ts-rs/tests/list.rs | 5 +---- ts-rs/tests/optional_field.rs | 2 +- ts-rs/tests/references.rs | 6 ++++-- ts-rs/tests/semver.rs | 5 +---- ts-rs/tests/serde-skip-with-default.rs | 5 +---- ts-rs/tests/slices.rs | 2 +- ts-rs/tests/struct_rename.rs | 5 ++++- 12 files changed, 24 insertions(+), 31 deletions(-) diff --git a/macros/src/types/enum.rs b/macros/src/types/enum.rs index 0cfcfd9..5c0e056 100644 --- a/macros/src/types/enum.rs +++ b/macros/src/types/enum.rs @@ -50,11 +50,9 @@ pub(crate) fn r#enum_def(s: &ItemEnum) -> syn::Result { Ok(DerivedTS { inline: quote!([#(#formatted_variants),*].join(" | ")), decl: quote!(format!("type {}{} = {};", #name, #generic_args, Self::inline())), - inline_flattened: Some( - quote!( - format!("({})", [#(#formatted_variants),*].join(" | ")) - ) - ), + inline_flattened: Some(quote!( + format!("({})", [#(#formatted_variants),*].join(" | ")) + )), dependencies, name, export: enum_attr.export, @@ -136,7 +134,7 @@ fn format_variant( #name, // At this point inline_flattened looks like // { /* ...data */ } - // + // // To be flattened, an internally tagged enum must not be // surrounded by braces, otherwise each variant will look like // { "tag": "name", { /* ...data */ } } diff --git a/ts-rs/src/lib.rs b/ts-rs/src/lib.rs index 0df2bc5..a7d4a89 100644 --- a/ts-rs/src/lib.rs +++ b/ts-rs/src/lib.rs @@ -107,7 +107,7 @@ //! - `heapless-impl` //! //! Implement `TS` for `Vec` from heapless -//! +//! //! - `semver-impl` //! Implement `TS` for `Version` from semver //! diff --git a/ts-rs/tests/enum_flattening.rs b/ts-rs/tests/enum_flattening.rs index c26ef05..5d4f9f5 100644 --- a/ts-rs/tests/enum_flattening.rs +++ b/ts-rs/tests/enum_flattening.rs @@ -105,4 +105,3 @@ fn untagged() { r#"{ a: number, a2: string, } | { b: boolean, } | { c: string, }"# ) } - diff --git a/ts-rs/tests/enum_struct_rename_all.rs b/ts-rs/tests/enum_struct_rename_all.rs index b901a16..d681d33 100644 --- a/ts-rs/tests/enum_struct_rename_all.rs +++ b/ts-rs/tests/enum_struct_rename_all.rs @@ -1,4 +1,4 @@ -use serde::{Serialize, Deserialize}; +use serde::{Deserialize, Serialize}; use ts_rs::TS; #[derive(Serialize, Deserialize, TS, Clone)] @@ -21,5 +21,8 @@ pub enum TaskStatus { #[test] pub fn enum_struct_rename_all() { - assert_eq!(TaskStatus::inline(), r#"{ "running": { startedTime: string, } } | { "terminated": { status: number, stdout: string, stderr: string, } }"#) + assert_eq!( + TaskStatus::inline(), + r#"{ "running": { startedTime: string, } } | { "terminated": { status: number, stdout: string, stderr: string, } }"# + ) } diff --git a/ts-rs/tests/generics.rs b/ts-rs/tests/generics.rs index cd8cd68..b4f8183 100644 --- a/ts-rs/tests/generics.rs +++ b/ts-rs/tests/generics.rs @@ -183,10 +183,7 @@ fn default() { struct B>> { u: U, } - assert_eq!( - B::<()>::decl(), - "type B | null> = { u: U, }" - ); + assert_eq!(B::<()>::decl(), "type B | null> = { u: U, }"); assert!(B::<()>::dependencies().iter().any(|dep| dep.ts_name == "A")); #[derive(TS)] diff --git a/ts-rs/tests/list.rs b/ts-rs/tests/list.rs index dfa3126..92f6f2e 100644 --- a/ts-rs/tests/list.rs +++ b/ts-rs/tests/list.rs @@ -8,8 +8,5 @@ fn list() { data: Option>, } - assert_eq!( - List::decl(), - "type List = { data: Array | null, }" - ); + assert_eq!(List::decl(), "type List = { data: Array | null, }"); } diff --git a/ts-rs/tests/optional_field.rs b/ts-rs/tests/optional_field.rs index 4912584..b7c1f20 100644 --- a/ts-rs/tests/optional_field.rs +++ b/ts-rs/tests/optional_field.rs @@ -7,7 +7,7 @@ use ts_rs::TS; struct Optional { #[ts(optional)] a: Option, - b: Option + b: Option, } #[test] diff --git a/ts-rs/tests/references.rs b/ts-rs/tests/references.rs index 1aee02b..e9b2dbb 100644 --- a/ts-rs/tests/references.rs +++ b/ts-rs/tests/references.rs @@ -10,6 +10,8 @@ fn references() { num_ref: &'a i32, } - assert_eq!(FullOfRefs::inline(), "{ str_slice: string, ref_slice: Array, num_ref: number, }") + assert_eq!( + FullOfRefs::inline(), + "{ str_slice: string, ref_slice: Array, num_ref: number, }" + ) } - diff --git a/ts-rs/tests/semver.rs b/ts-rs/tests/semver.rs index 5e6ebb8..81d307c 100644 --- a/ts-rs/tests/semver.rs +++ b/ts-rs/tests/semver.rs @@ -11,8 +11,5 @@ fn semver() { version: Version, } - assert_eq!( - Semver::decl(), - "type Semver = { version: string, }" - ) + assert_eq!(Semver::decl(), "type Semver = { version: string, }") } diff --git a/ts-rs/tests/serde-skip-with-default.rs b/ts-rs/tests/serde-skip-with-default.rs index 5f970af..bcb523e 100644 --- a/ts-rs/tests/serde-skip-with-default.rs +++ b/ts-rs/tests/serde-skip-with-default.rs @@ -20,8 +20,5 @@ pub struct Foobar { #[test] fn serde_skip_with_default() { - assert_eq!( - Foobar::decl(), - "type Foobar = { something_else: number, }" - ); + assert_eq!(Foobar::decl(), "type Foobar = { something_else: number, }"); } diff --git a/ts-rs/tests/slices.rs b/ts-rs/tests/slices.rs index 268a090..0e396c5 100644 --- a/ts-rs/tests/slices.rs +++ b/ts-rs/tests/slices.rs @@ -21,7 +21,7 @@ fn slice_ref() { #[derive(TS)] struct Interface<'a> { #[allow(dead_code)] - a: &'a [&'a str] + a: &'a [&'a str], } assert_eq!(Interface::inline(), "{ a: Array, }") diff --git a/ts-rs/tests/struct_rename.rs b/ts-rs/tests/struct_rename.rs index aa7d78d..274b7a7 100644 --- a/ts-rs/tests/struct_rename.rs +++ b/ts-rs/tests/struct_rename.rs @@ -25,7 +25,10 @@ fn rename_all_camel_case() { alreadyCamelCase: i32, } - assert_eq!(Rename::inline(), "{ crc32cHash: number, b: number, alreadyCamelCase: number, }"); + assert_eq!( + Rename::inline(), + "{ crc32cHash: number, b: number, alreadyCamelCase: number, }" + ); } #[test] From 64544e05d6eb394de87f47c82da655b50cc70295 Mon Sep 17 00:00:00 2001 From: Gustavo Date: Fri, 26 Jan 2024 16:34:39 -0300 Subject: [PATCH 57/60] Implement inline generics --- macros/src/types/generics.rs | 17 ++++++++++++++--- ts-rs/tests/generics.rs | 4 ++-- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/macros/src/types/generics.rs b/macros/src/types/generics.rs index 4766de9..f808feb 100644 --- a/macros/src/types/generics.rs +++ b/macros/src/types/generics.rs @@ -40,7 +40,7 @@ pub fn format_generics(deps: &mut Dependencies, generics: &Generics) -> TokenStr pub fn format_type(ty: &Type, dependencies: &mut Dependencies, generics: &Generics) -> TokenStream { // If the type matches one of the generic parameters, just pass the identifier: - if let Some(generic_ident) = generics + if let Some(generic) = generics .params .iter() .filter_map(|param| match param { @@ -55,9 +55,20 @@ pub fn format_type(ty: &Type, dependencies: &mut Dependencies, generics: &Generi && type_path.path.is_ident(&type_param.ident) ) }) - .map(|type_param| type_param.ident.to_string()) { - return quote!(#generic_ident.to_owned()); + let generic_ident = generic.ident.clone(); + let generic_ident_str = generic_ident.to_string(); + + if !generic.bounds.is_empty() || generic.default.is_some() { + return quote!(#generic_ident_str.to_owned()); + } + + return quote!( + match <#generic_ident>::name().as_str() { + "null" => #generic_ident_str.to_owned(), + x => x.to_owned() + } + ); } // special treatment for arrays and tuples diff --git a/ts-rs/tests/generics.rs b/ts-rs/tests/generics.rs index b4f8183..11ec471 100644 --- a/ts-rs/tests/generics.rs +++ b/ts-rs/tests/generics.rs @@ -147,7 +147,7 @@ fn generic_struct() { } #[test] -#[ignore] +// #[ignore] // https://github.com/Aleph-Alpha/ts-rs/issues/56 TODO fn inline() { #[derive(TS)] @@ -167,7 +167,7 @@ fn inline() { assert_eq!(Generic::<()>::decl(), "type Generic = { t: T, }"); assert_eq!( Container::decl(), - "type Container = { g: Generic, gi: { t: string }, t: string, }" + "type Container = { g: Generic, gi: { t: string, }, t: string, }" ); } From 3667ef65fbad96d036f401f78ca1a68d98ec76d6 Mon Sep 17 00:00:00 2001 From: Gustavo Date: Mon, 29 Jan 2024 15:33:29 -0300 Subject: [PATCH 58/60] Add a comment explaining why check for "null" --- macros/src/types/generics.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/macros/src/types/generics.rs b/macros/src/types/generics.rs index f808feb..beacc29 100644 --- a/macros/src/types/generics.rs +++ b/macros/src/types/generics.rs @@ -65,7 +65,13 @@ pub fn format_type(ty: &Type, dependencies: &mut Dependencies, generics: &Generi return quote!( match <#generic_ident>::name().as_str() { + // When exporting a generic, the default type used is `()`, + // which gives "null" when calling `.name()`. In this case, we + // want to preserve the type param's identifier as the name used "null" => #generic_ident_str.to_owned(), + + // If name is not "null", a type has been provided, so we use its + // name instead x => x.to_owned() } ); From 9bc22995cc02fadab935c8c5a2ba2d80aeddce47 Mon Sep 17 00:00:00 2001 From: Gustavo Date: Mon, 29 Jan 2024 16:55:05 -0300 Subject: [PATCH 59/60] Add ignored tests for missing implementations --- ts-rs/tests/generics.rs | 52 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/ts-rs/tests/generics.rs b/ts-rs/tests/generics.rs index 11ec471..961fffc 100644 --- a/ts-rs/tests/generics.rs +++ b/ts-rs/tests/generics.rs @@ -147,8 +147,6 @@ fn generic_struct() { } #[test] -// #[ignore] -// https://github.com/Aleph-Alpha/ts-rs/issues/56 TODO fn inline() { #[derive(TS)] struct Generic { @@ -171,6 +169,56 @@ fn inline() { ); } +#[test] +#[ignore = "We haven't figured out how to inline generics with bounds yet"] +fn inline_with_bounds() { + #[derive(TS)] + struct Generic { + t: T, + } + + #[derive(TS)] + struct Container { + g: Generic, + #[ts(inline)] + gi: Generic, + #[ts(flatten)] + t: Generic, + } + + assert_eq!(Generic::<&'static str>::decl(), "type Generic = { t: T, }"); + assert_eq!( + Container::decl(), + "type Container = { g: Generic, gi: { t: string, }, t: number, }" + // Actual output: { g: Generic, gi: { t: T, }, t: T, } + ); +} + +#[test] +#[ignore = "We haven't figured out how to inline generics with defaults yet"] +fn inline_with_default() { + #[derive(TS)] + struct Generic { + t: T, + } + + #[derive(TS)] + struct Container { + g: Generic, + #[ts(inline)] + gi: Generic, + #[ts(flatten)] + t: Generic, + } + + assert_eq!(Generic::<&'static str>::decl(), "type Generic = { t: T, }"); + assert_eq!( + Container::decl(), + "type Container = { g: Generic, gi: { t: string, }, t: number, }" + // Actual output: { g: Generic, gi: { t: T, }, t: T, } + ); +} + #[test] fn default() { #[derive(TS)] From ef56d7a89ba11a786fc8ca5dd80e72e6a0e012c6 Mon Sep 17 00:00:00 2001 From: Gustavo Date: Mon, 29 Jan 2024 17:59:34 -0300 Subject: [PATCH 60/60] Use inline instead of name, Vec was turning into Array --- macros/src/types/generics.rs | 2 +- ts-rs/tests/generics.rs | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/macros/src/types/generics.rs b/macros/src/types/generics.rs index beacc29..5bf26ff 100644 --- a/macros/src/types/generics.rs +++ b/macros/src/types/generics.rs @@ -64,7 +64,7 @@ pub fn format_type(ty: &Type, dependencies: &mut Dependencies, generics: &Generi } return quote!( - match <#generic_ident>::name().as_str() { + match <#generic_ident>::inline().as_str() { // When exporting a generic, the default type used is `()`, // which gives "null" when calling `.name()`. In this case, we // want to preserve the type param's identifier as the name used diff --git a/ts-rs/tests/generics.rs b/ts-rs/tests/generics.rs index 961fffc..703868e 100644 --- a/ts-rs/tests/generics.rs +++ b/ts-rs/tests/generics.rs @@ -147,6 +147,7 @@ fn generic_struct() { } #[test] +// https://github.com/Aleph-Alpha/ts-rs/issues/56 TODO fn inline() { #[derive(TS)] struct Generic { @@ -159,13 +160,13 @@ fn inline() { #[ts(inline)] gi: Generic, #[ts(flatten)] - t: Generic, + t: Generic>, } assert_eq!(Generic::<()>::decl(), "type Generic = { t: T, }"); assert_eq!( Container::decl(), - "type Container = { g: Generic, gi: { t: string, }, t: string, }" + "type Container = { g: Generic, gi: { t: string, }, t: Array, }" ); }