export_type/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
use std::env;
use std::path::PathBuf;

use lang::TSExporter;
use parsers::handle_export_type_parsing;
use proc_macro::TokenStream;
use syn::{parse_macro_input, Attribute, DeriveInput};

mod case;
mod error;
mod exporter;
mod lang;
mod parsers;

use error::ToCompileError;

use case::*;
use error::*;
use exporter::*;

pub(crate) static DEFAULT_EXPORT_PATH: &str = "exports";

/// Derives the ExportType trait for a struct or enum, generating TypeScript type definitions.
///
/// # Examples
///
/// ```ignore
/// #[derive(ExportType)]
/// #[export_type(lang = "typescript", path = "types/generated")]
/// struct User {
///     id: i32,
///     name: String,
///     #[export_type(rename = "emailAddress")]
///     email: Option<String>,
/// }
///
/// #[derive(ExportType)]
/// enum Status {
///     Active,
///     Inactive,
///     Pending { reason: String },
/// }
/// ```
#[proc_macro_derive(ExportType, attributes(export_type))]
pub fn export_type(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    match handle_export_type(input.clone()) {
        Ok(_output) => {
            if let Ok(export_path) = get_export_path_from_attrs(&input.attrs) {
                // Generate in OUT_DIR during build
                if let Ok(out_dir) = env::var("OUT_DIR") {
                    let out_path = PathBuf::from(out_dir);
                    let _ = create_exporter_files(out_path.join("types"));

                    // Emit cargo instructions for build.rs
                    // println!("cargo:rerun-if-changed=src");
                    // println!("cargo:rustc-env=TYPES_OUT_DIR={}", out_path.display());
                }

                // During normal compilation, write to target path
                if env::var("CARGO_PUBLISH").is_err() {
                    let _ = create_exporter_files(export_path);
                }
            }
            quote::quote! {}.into()
        }
        Err(e) => e.to_compile_error().into(),
    }
}

fn handle_export_type(input: DeriveInput) -> TSTypeResult<proc_macro2::TokenStream> {
    let lang = get_lang_from_attrs(&input.attrs)?;
    let mut output = handle_export_type_parsing(&input, &lang)?;
    let name = input.ident.to_string();
    let generics = get_generics_from_attrs(&input.attrs)?;
    output.generics = generics;
    output.lang = lang;
    add_struct_or_enum(PathBuf::from(name.clone()), output)?;
    Ok(quote::quote! {})
}

fn get_exporter_from_lang(
    lang: &str,
    output: Output,
    generics: Vec<String>,
) -> TSTypeResult<Box<dyn ToOutput>> {
    match lang {
        "typescript" | "ts" => Ok(Box::new(TSExporter::new(output, None, generics))),
        lang => Err(TSTypeError::UnsupportedLanguage(lang.to_string())),
    }
}

fn get_generics_from_attrs(attrs: &[Attribute]) -> TSTypeResult<Vec<String>> {
    let mut generics = vec![];

    for attr in attrs {
        if attr.path().is_ident("export_type") {
            if let Ok(nested) = attr.parse_args_with(
                syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated,
            ) {
                for meta in nested {
                    if let syn::Meta::NameValue(nv) = meta {
                        if nv.path.is_ident("generics") {
                            if let syn::Expr::Lit(syn::ExprLit {
                                lit: syn::Lit::Str(lit_str),
                                ..
                            }) = nv.value
                            {
                                generics = lit_str
                                    .value()
                                    .split(',')
                                    .map(|s| s.trim().to_string())
                                    .collect();
                            }
                        }
                    }
                }
            }
        }
    }

    Ok(generics)
}

fn get_lang_from_attrs(attrs: &[Attribute]) -> TSTypeResult<String> {
    let mut lang = String::from("typescript");

    for attr in attrs {
        if attr.path().is_ident("export_type") {
            if let Ok(nested) = attr.parse_args_with(
                syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated,
            ) {
                for meta in nested {
                    if let syn::Meta::NameValue(nv) = meta {
                        if nv.path.is_ident("lang") {
                            if let syn::Expr::Lit(syn::ExprLit {
                                lit: syn::Lit::Str(lit_str),
                                ..
                            }) = nv.value
                            {
                                lang = lit_str.value();
                            }
                        }
                    }
                }
            }
        }
    }

    Ok(lang)
}

fn get_export_path_from_attrs(attrs: &[Attribute]) -> TSTypeResult<PathBuf> {
    let mut export_path = PathBuf::from(DEFAULT_EXPORT_PATH);

    for attr in attrs {
        if attr.path().is_ident("export_type") {
            if let Ok(nested) = attr.parse_args_with(
                syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated,
            ) {
                for meta in nested {
                    if let syn::Meta::NameValue(nv) = meta {
                        if nv.path.is_ident("path") {
                            if let syn::Expr::Lit(syn::ExprLit {
                                lit: syn::Lit::Str(lit_str),
                                ..
                            }) = nv.value
                            {
                                export_path = PathBuf::from(lit_str.value());
                            }
                        }
                    }
                }
            }
        }
    }

    Ok(export_path)
}

#[cfg(test)]
mod tests {
    use super::*;
    use syn::parse_quote;

    #[test]
    fn test_get_lang_from_attrs() {
        let attrs = vec![];
        assert_eq!(
            get_lang_from_attrs(&attrs).unwrap(),
            "typescript".to_string()
        );

        let attrs = vec![parse_quote! { #[export_type(lang = "typescript")] }];
        assert_eq!(
            get_lang_from_attrs(&attrs).unwrap(),
            "typescript".to_string()
        );

        let attrs = vec![parse_quote! { #[export_type(lang = "unsupported")] }];
        assert_eq!(
            get_lang_from_attrs(&attrs).unwrap(),
            "unsupported".to_string()
        );
    }

    #[test]
    fn test_get_export_path_from_attrs() {
        let attrs = vec![];
        assert_eq!(
            get_export_path_from_attrs(&attrs).unwrap(),
            PathBuf::from("exports")
        );

        let attrs = vec![parse_quote! { #[export_type(path = "test")] }];
        assert_eq!(
            get_export_path_from_attrs(&attrs).unwrap(),
            PathBuf::from("test")
        );
    }
}