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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
use crate::typescript::convert_type;
use crate::{utils, BuildState};
use convert_case::{Case, Casing};
use syn::__private::ToTokens;

static RENAME_RULES: &[(&str, convert_case::Case)] = &[
    ("lowercase", Case::Lower),
    ("UPPERCASE", Case::Upper),
    ("PascalCase", Case::Pascal),
    ("camelCase", Case::Camel),
    ("snake_case", Case::Snake),
    ("SCREAMING_SNAKE_CASE", Case::ScreamingSnake),
    ("kebab-case", Case::Kebab),
    // ("SCREAMING-KEBAB-CASE", _), // not supported by convert_case
];

/// Conversion of Rust Enum to Typescript using external tagging as per https://serde.rs/enum-representations.html
/// however conversion will adhere to the `serde` `tag` such that enums are intenrally tagged
/// (while the other forms such as adjacent tagging aren't supported).
/// `rename_all` attributes for the name of the tag will also be adhered to.
impl super::ToTypescript for syn::ItemEnum {
    fn convert_to_ts(self, state: &mut BuildState, debug: bool, uses_typeinterface: bool) {
        // check we don't have any tuple structs that could mess things up.
        // if we do ignore this struct
        for variant in self.variants.iter() {
            // allow single-field tuple structs to pass through as newtype structs
            let mut is_newtype = false;
            for f in variant.fields.iter() {
                if f.ident.is_none() {
                    // If we already marked this variant as a newtype, we have a multi-field tuple struct
                    if is_newtype {
                        if debug {
                            println!("#[tsync] failed for enum {}", self.ident);
                        }
                        return;
                    } else {
                        is_newtype = true;
                    }
                }
            }
        }

        state.types.push('\n');

        let comments = utils::get_comments(self.clone().attrs);
        let casing = utils::get_attribute_arg("serde", "rename_all", &self.attrs);
        let casing = to_enum_case(casing);

        let is_single = !self.variants.iter().any(|x| !x.fields.is_empty());
        state.write_comments(&comments, 0);

        if is_single {
            if utils::has_attribute_arg("derive", "Serialize_repr", &self.attrs) {
                add_numeric_enum(self, state, casing, uses_typeinterface)
            } else {
                add_enum(self, state, casing, uses_typeinterface)
            }
        } else if let Some(tag_name) = utils::get_attribute_arg("serde", "tag", &self.attrs) {
            add_internally_tagged_enum(tag_name, self, state, casing, uses_typeinterface)
        } else {
            add_externally_tagged_enum(self, state, casing, uses_typeinterface)
        }
    }
}

/// This convert an all unit enums to a union of const strings in Typescript.
/// It will ignore any discriminants.  
fn add_enum(
    exported_struct: syn::ItemEnum,
    state: &mut BuildState,
    casing: Option<Case>,
    uses_typeinterface: bool,
) {
    let export = if uses_typeinterface { "" } else { "export " };
    state.types.push_str(&format!(
        "{export}type {interface_name} =\n{space}",
        interface_name = exported_struct.ident,
        space = utils::build_indentation(1)
    ));

    for variant in exported_struct.variants {
        let field_name = if let Some(casing) = casing {
            variant.ident.to_string().to_case(casing)
        } else {
            variant.ident.to_string()
        };
        state.types.push_str(&format!(" | \"{}\"", field_name));
    }

    state.types.push_str(";\n");
}

/// Numeric enums. These will be converted using enum syntax
/// ```ignore
/// enum Foo {
///     Bar,            // 0
///     Baz = 123,      // 123
///     Quux,           // 124
/// }
/// enum Animal {
///     Dog,
///     Cat,
/// }
/// ``` to the following
/// ```ignore
/// enum Foo {
///    Bar = 0,          
///    Baz = 123,     
///    Quux = 124,           
/// }
/// enum Animal {
///    Dog = 0,
///    Cat = 1,
/// }
/// ```
///
fn add_numeric_enum(
    exported_struct: syn::ItemEnum,
    state: &mut BuildState,
    casing: Option<Case>,
    uses_typeinterface: bool,
) {
    let declare = if uses_typeinterface {
        "declare "
    } else {
        "export "
    };
    state.types.push_str(&format!(
        "{declare}enum {interface_name} {{",
        interface_name = exported_struct.ident
    ));

    let mut num = 0;

    for variant in exported_struct.variants {
        state.types.push('\n');
        let field_name = if let Some(casing) = casing {
            variant.ident.to_string().to_case(casing)
        } else {
            variant.ident.to_string()
        };
        if let Some((_, disc)) = variant.discriminant {
            if let Ok(new_disc) = disc.to_token_stream().to_string().parse::<i32>() {
                num = new_disc;
            }
        }
        state
            .types
            .push_str(&format!("  {} = {},", field_name, num));
        num += 1;
    }

    state.types.push_str("\n}\n");
}

/// Conversion of Rust Enum to Typescript using internal tagging as per https://serde.rs/enum-representations.html
/// meaning tuple structs will not be support e.g.
/// ```ignore
/// #[derive(Serialize, Deserialize)]
/// #[serde(tag = "type")]
/// #[tsync]
/// enum Message {
///     Request { id: String, method: String, params: Params },
///     Response { id: String, result: Value },
/// }
/// ``` goes to `type Message = {"type": "REQUEST", "id": "...", "method": "...", "params": {...}} | {"type": "RESPONSE", "id": string, "result": "Value"}`
/// However there is an edge case: purely literal enums. These will be converted using enum syntax
/// ```ignore
/// enum Foo {
///     Bar,            // 0
///     Baz = 123,      // 123
///     Quux,           // 124
/// }
/// enum Animal {
///     Dog,
///     Cat,
/// }
/// ``` to the following
/// ```ignore
/// enum Foo {
///    Bar = 0,          
///    Baz = 123,     
///    Quux = 124,           
/// }
/// enum Animal {
///    Dog = 0,
///    Cat = 1,
/// }
/// ```
fn add_internally_tagged_enum(
    tag_name: String,
    exported_struct: syn::ItemEnum,
    state: &mut BuildState,
    casing: Option<Case>,
    uses_typeinterface: bool,
) {
    let export = if uses_typeinterface { "" } else { "export " };
    state.types.push_str(&format!(
        "{export}type {interface_name}{generics} =",
        interface_name = exported_struct.ident,
        generics = utils::extract_struct_generics(exported_struct.generics.clone())
    ));

    for variant in exported_struct.variants.iter() {
        // Assumes that non-newtype tuple variants have already been filtered out
        let is_newtype = variant
            .fields
            .iter()
            .fold(false, |state, v| state || v.ident.is_none());
        if is_newtype {
            // TODO: Generate newtype structure
            // This should contain the discriminant plus all fields of the inner structure as a flat structure
            // TODO: Check for case where discriminant name matches an inner structure field name
            // We should reject clashes
        } else {
            state.types.push('\n');
            state.types.push_str(&format!(
                "  | {interface_name}__{variant_name}",
                interface_name = exported_struct.ident,
                variant_name = variant.ident,
            ))
        }
    }

    state.types.push_str(";\n");

    for variant in exported_struct.variants {
        // Assumes that non-newtype tuple variants have already been filtered out
        let is_newtype = variant
            .fields
            .iter()
            .fold(false, |state, v| state || v.ident.is_none());
        if !is_newtype {
            state.types.push('\n');
            let comments = utils::get_comments(variant.attrs);
            state.write_comments(&comments, 0);
            state.types.push_str(&format!(
                "type {interface_name}__{variant_name} = ",
                interface_name = exported_struct.ident,
                variant_name = variant.ident,
            ));

            let field_name = if let Some(casing) = casing {
                variant.ident.to_string().to_case(casing)
            } else {
                variant.ident.to_string()
            };
            // add discriminant
            state.types.push_str(&format!(
                "{{\n{}{}: \"{}\";\n",
                utils::build_indentation(2),
                tag_name,
                field_name,
            ));
            super::structs::process_fields(variant.fields, state, 2);
            state.types.push_str("};");
        }
    }
    state.types.push_str("\n");
}

/// This follows serde's default approach of external tagging
fn add_externally_tagged_enum(
    exported_struct: syn::ItemEnum,
    state: &mut BuildState,
    casing: Option<Case>,
    uses_typeinterface: bool,
) {
    let export = if uses_typeinterface { "" } else { "export " };
    state.types.push_str(&format!(
        "{export}type {interface_name}{generics} =",
        interface_name = exported_struct.ident,
        generics = utils::extract_struct_generics(exported_struct.generics.clone())
    ));

    for variant in exported_struct.variants {
        state.types.push('\n');
        let comments = utils::get_comments(variant.attrs);
        state.write_comments(&comments, 2);
        let field_name = if let Some(casing) = casing {
            variant.ident.to_string().to_case(casing)
        } else {
            variant.ident.to_string()
        };
        // Assumes that non-newtype tuple variants have already been filtered out
        let is_newtype = variant
            .fields
            .iter()
            .fold(false, |state, v| state || v.ident.is_none());

        if is_newtype {
            // add discriminant
            state.types.push_str(&format!("  | {{ \"{}\":", field_name));
            for field in variant.fields {
                state
                    .types
                    .push_str(&format!(" {}", convert_type(&field.ty).ts_type,));
            }
            state.types.push_str(&format!(" }}"));
        } else {
            // add discriminant
            state.types.push_str(&format!(
                "  | {{\n{}\"{}\": {{",
                utils::build_indentation(6),
                field_name,
            ));
            let prepend;
            if variant.fields.is_empty() {
                prepend = "".into();
            } else {
                prepend = utils::build_indentation(6);
                state.types.push('\n');
                super::structs::process_fields(variant.fields, state, 8);
            }
            state
                .types
                .push_str(&format!("{}}}\n{}}}", prepend, utils::build_indentation(4)));
        }
    }
    state.types.push_str(";\n");
}

fn to_enum_case(val: impl Into<Option<String>>) -> Option<Case> {
    val.into().and_then(|x| {
        for (name, rule) in RENAME_RULES {
            if x == *name {
                return Some(*rule);
            }
        }
        None
    })
}