Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export type User = { user_id: number, first_name: string, last_name: string, };

### Features
- generate type declarations from rust structs
- generate union declarations from rust enums
- generate union declarations (and native typescript enums) from rust enums
- inline types
- flatten structs/types
- generate necessary imports when exporting to multiple files
Expand Down
35 changes: 35 additions & 0 deletions macros/src/attr/enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub struct EnumAttr {
crate_rename: Option<Path>,
pub type_as: Option<Type>,
pub type_override: Option<String>,
pub use_ts_enum: bool,
pub rename_all: Option<Inflection>,
pub rename_all_fields: Option<Inflection>,
pub rename: Option<Expr>,
Expand Down Expand Up @@ -75,6 +76,7 @@ impl Attr for EnumAttr {
crate_rename: self.crate_rename.or(other.crate_rename),
type_as: self.type_as.or(other.type_as),
type_override: self.type_override.or(other.type_override),
use_ts_enum: self.use_ts_enum || other.use_ts_enum,
rename: self.rename.or(other.rename),
rename_all: self.rename_all.or(other.rename_all),
rename_all_fields: self.rename_all_fields.or(other.rename_all_fields),
Expand All @@ -94,6 +96,38 @@ impl Attr for EnumAttr {
}

fn assert_validity(&self, item: &Self::Item) -> Result<()> {
if self.use_ts_enum {
if self.tag.is_some() {
syn_err_spanned!(
item;
"`tag` is not compatible with `use_ts_enum`"
);
}
if self.type_override.is_some() {
syn_err_spanned!(
item;
"`type_override` is not compatible with `use_ts_enum`"
);
}
if self.type_as.is_some() {
syn_err_spanned!(
item;
"`type_as` is not compatible with `use_ts_enum`"
);
}

match (&self.rename_all, &self.rename_all_fields) {
(Some(Inflection::Kebab | Inflection::ScreamingKebab), _) |
(_, Some(Inflection::Kebab | Inflection::ScreamingKebab)) => {
syn_err_spanned!(
item;
"`use_ts_enum` is not compatible with kebab case renaming"
);
},
_ => {},
}
}

if self.type_override.is_some() {
if self.type_as.is_some() {
syn_err_spanned!(
Expand Down Expand Up @@ -208,6 +242,7 @@ impl_parse! {
"crate" => out.crate_rename = Some(parse_assign_from_str(input)?),
"as" => out.type_as = Some(parse_assign_from_str(input)?),
"type" => out.type_override = Some(parse_assign_str(input)?),
"use_ts_enum" => out.use_ts_enum = true,
"rename" => out.rename = Some(parse_assign_expr(input)?),
"rename_all" => out.rename_all = Some(parse_assign_inflection(input)?),
"rename_all_fields" => out.rename_all_fields = Some(parse_assign_inflection(input)?),
Expand Down
29 changes: 25 additions & 4 deletions macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ struct DerivedTS {
dependencies: Dependencies,
concrete: HashMap<Ident, Type>,
bound: Option<Vec<WherePredicate>>,

is_ts_enum: bool,
export: bool,
export_to: Option<Expr>,
}
Expand Down Expand Up @@ -253,9 +253,17 @@ impl DerivedTS {
}
},
);
let inline = quote! {
fn inline() -> String {
#inline
let inline = if self.is_ts_enum {
quote! {
fn inline() -> String {
<Self as #crate_rename::TS>::inline_flattened()
}
}
} else {
quote! {
fn inline() -> String {
#inline
}
}
};
quote! {
Expand Down Expand Up @@ -295,6 +303,19 @@ impl DerivedTS {
// use instead. This might be something to change in the future.
G::Const(ConstParam { ident, .. }) => Some(quote!(#ident)),
});

if self.is_ts_enum {
let inline = &self.inline;
return quote! {
fn decl_concrete() -> String {
format!("enum {} {{ {} }}", #name, #inline)
}
fn decl() -> String {
<#rust_ty<#(#generic_idents,)*> as #crate_rename::TS>::decl_concrete()
}
};
}

quote! {
fn decl_concrete() -> String {
format!("type {} = {};", #name, <Self as #crate_rename::TS>::inline())
Expand Down
42 changes: 38 additions & 4 deletions macros/src/types/enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,20 +45,45 @@ pub(crate) fn r#enum_def(s: &ItemEnum) -> syn::Result<DerivedTS> {
variant,
)?;
}

let (inline, inline_flattened) = if enum_attr.use_ts_enum {
let pairs = formatted_variants
.iter()
.map(|name| quote!(format!("{} = \"{}\"", #name, #name)))
.collect::<Vec<_>>();
let strings = formatted_variants
.iter()
.map(|name| quote!(format!("\"{}\"", #name)))
.collect::<Vec<_>>();

(
quote!([#(#pairs),*].join(", ")),
Some(quote!(
format!("({})", [#(#strings),*].join(" | "))
)),
)
}
else {
(
quote!([#(#formatted_variants),*].join(" | ")),
Some(quote!(
format!("({})", [#(#formatted_variants),*].join(" | "))
)),
)
};

Ok(DerivedTS {
crate_rename,
inline: quote!([#(#formatted_variants),*].join(" | ")),
inline_flattened: Some(quote!(
format!("({})", [#(#formatted_variants),*].join(" | "))
)),
inline,
inline_flattened,
dependencies,
docs: enum_attr.docs,
export: enum_attr.export,
export_to: enum_attr.export_to,
ts_name: name,
concrete: enum_attr.concrete,
bound: enum_attr.bound,
is_ts_enum: enum_attr.use_ts_enum,
})
}

Expand Down Expand Up @@ -92,6 +117,14 @@ fn format_variant(
variant.ident.span(),
),
};

if enum_attr.use_ts_enum {
if !variant.fields.is_empty() {
syn_err_spanned!(variant; "`use_ts_enum` requires plain enum fields");
}
formatted_variants.push(quote!(#ts_name));
return Ok(());
}

let struct_attr = StructAttr::from_variant(enum_attr, &variant_attr, &variant.fields);
let variant_type = types::type_def(
Expand Down Expand Up @@ -213,5 +246,6 @@ fn empty_enum(ts_name: Expr, enum_attr: EnumAttr) -> DerivedTS {
ts_name,
concrete: enum_attr.concrete,
bound: enum_attr.bound,
is_ts_enum: false,
}
}
1 change: 1 addition & 0 deletions macros/src/types/named.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ pub(crate) fn named(attr: &StructAttr, ts_name: Expr, fields: &FieldsNamed) -> R
ts_name,
concrete: attr.concrete.clone(),
bound: attr.bound.clone(),
is_ts_enum: false,
})
}

Expand Down
1 change: 1 addition & 0 deletions macros/src/types/newtype.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,6 @@ pub(crate) fn newtype(
ts_name,
concrete: attr.concrete.clone(),
bound: attr.bound.clone(),
is_ts_enum: false,
})
}
1 change: 1 addition & 0 deletions macros/src/types/tuple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ pub(crate) fn tuple(attr: &StructAttr, ts_name: Expr, fields: &FieldsUnnamed) ->
ts_name,
concrete: attr.concrete.clone(),
bound: attr.bound.clone(),
is_ts_enum: false,
})
}

Expand Down
2 changes: 2 additions & 0 deletions macros/src/types/type_as.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub(crate) fn type_as_struct(
ts_name,
concrete: attr.concrete.clone(),
bound: attr.bound.clone(),
is_ts_enum: false,
})
}

Expand All @@ -48,5 +49,6 @@ pub(crate) fn type_as_enum(attr: &EnumAttr, ts_name: Expr, type_as: &Type) -> Re
ts_name,
concrete: attr.concrete.clone(),
bound: attr.bound.clone(),
is_ts_enum: false,
})
}
2 changes: 2 additions & 0 deletions macros/src/types/type_override.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pub(crate) fn type_override_struct(
ts_name,
concrete: attr.concrete.clone(),
bound: attr.bound.clone(),
is_ts_enum: false,
})
}

Expand All @@ -46,5 +47,6 @@ pub(crate) fn type_override_enum(
ts_name,
concrete: attr.concrete.clone(),
bound: attr.bound.clone(),
is_ts_enum: false,
})
}
3 changes: 3 additions & 0 deletions macros/src/types/unit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pub(crate) fn empty_object(attr: &StructAttr, ts_name: Expr) -> DerivedTS {
ts_name,
concrete: attr.concrete.clone(),
bound: attr.bound.clone(),
is_ts_enum: false,
}
}

Expand All @@ -38,6 +39,7 @@ pub(crate) fn empty_array(attr: &StructAttr, ts_name: Expr) -> DerivedTS {
ts_name,
concrete: attr.concrete.clone(),
bound: attr.bound.clone(),
is_ts_enum: false,
}
}

Expand All @@ -55,5 +57,6 @@ pub(crate) fn null(attr: &StructAttr, ts_name: Expr) -> DerivedTS {
ts_name,
concrete: attr.concrete.clone(),
bound: attr.bound.clone(),
is_ts_enum: false,
}
}
7 changes: 6 additions & 1 deletion ts-rs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
//!
//! ## Features
//! - generate type declarations from rust structs
//! - generate union declarations from rust enums
//! - generate union declarations (and native typescript enums) from rust enums
//! - inline types
//! - flatten structs/types
//! - generate necessary imports when exporting to multiple files
Expand Down Expand Up @@ -364,6 +364,11 @@ mod tokio;
/// Valid values are `lowercase`, `UPPERCASE`, `camelCase`, `snake_case`, `PascalCase`, `SCREAMING_SNAKE_CASE`, "kebab-case" and "SCREAMING-KEBAB-CASE"
/// <br/><br/>
///
/// - **`#[ts(use_ts_enum)]`**
/// Exports a typescript enum with string values instead of a union type.
/// Typescript enums have simple names and values; and therefore cannot be used with `tag`, `type_override`, `type_as`, or kebab-case renaming on the same enum.
/// <br/><br/>
///
/// ### enum variant attributes
///
/// - **`#[ts(rename = "..")]`**
Expand Down
Loading
Loading