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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
// Copyright 2019 Ian Castleden
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Exports serde-serializable structs and enums to Typescript definitions.
//!
//! Please see documentation at [crates.io](https://crates.io/crates/typescript-definitions)

extern crate proc_macro;

use proc_macro2::Ident;
use quote::quote;
use serde_derive_internals::{ast, Ctxt, Derive};
// use std::str::FromStr;
use syn::DeriveInput;

mod derive_enum;
mod derive_struct;
mod patch;
mod quotet;
mod utils;

use std::cell::Cell;
use utils::*;

use patch::patch;

// too many TokenStreams around! give it a different name
type QuoteT = proc_macro2::TokenStream;

type QuoteMaker = quotet::QuoteT<'static>;

type Bounds = Vec<TSType>;

/// derive proc_macro to expose Typescript definitions to `wasm-bindgen`.
///
/// Please see documentation at [crates.io](https://crates.io/crates/typescript-definitions).
///
#[proc_macro_derive(TypescriptDefinition)]
pub fn derive_typescript_definition(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    if cfg!(any(debug_assertions, feature = "export-typescript")) {
        let input = QuoteT::from(input);
        do_derive_typescript_definition(input).into()
    } else {
        proc_macro::TokenStream::new()
    }
}
/// derive proc_macro to expose Typescript definitions as a static function.
///
/// Please see documentation at [crates.io](https://crates.io/crates/typescript-definitions).
///
#[proc_macro_derive(TypeScriptify)]
pub fn derive_type_script_ify(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    if cfg!(any(debug_assertions, feature = "export-typescript")) {
        let input = QuoteT::from(input);
        do_derive_type_script_ify(input).into()
    } else {
        proc_macro::TokenStream::new()
    }
}

fn do_derive_typescript_definition(input: QuoteT) -> QuoteT {
    let parsed = Typescriptify::parse(false, input);
    let export_string = parsed.wasm_string();

    let export_ident = ident_from_str(&format!(
        "TS_EXPORT_{}",
        parsed.ident.to_string().to_uppercase()
    ));

    // eprintln!(
    //     "....[typescript] export type {}={};",
    //     parsed.ident, typescript_string
    // );
    let mut q = quote! {

        #[wasm_bindgen(typescript_custom_section)]
        pub const #export_ident : &'static str = #export_string;
    };

    // just to allow testing... only `--features=test` seems to work
    if cfg!(any(test, feature = "test")) {
        let typescript_ident =
            ident_from_str(&format!("{}___typescript_definition", &parsed.ident));

        q.extend(quote!(
            fn #typescript_ident ( ) -> &'static str {
                #export_string
            }

        ));
    }

    q
}

fn do_derive_type_script_ify(input: QuoteT) -> QuoteT {
    let parsed = Typescriptify::parse(true, input);
    let ts_ident = parsed.ts_ident_str();
    let fmt = if parsed.ctxt.is_enum.get() {
        "export enum {} {};"
    } else {
        "export type {} = {};"
    };
    let body = match &parsed.body {
        quotet::QuoteT::Builder(b) => {
            let b = b.build();
            quote!( let f = #b; format!(#fmt, #ts_ident, f) )
        }
        _ => {
            let b = parsed.body.to_string();
            let b = patch(&b);
            quote!(format!(#fmt, #ts_ident, #b))
        }
    };

    // let map = &parsed.map();

    let ident = &parsed.ident;

    let ret = if parsed.ts_generics.is_empty() {
        quote! {

            impl ::typescript_definitions::TypeScriptifyTrait for #ident {
                fn type_script_ify() ->  String {
                    #body
                }

                // fn type_script_fields() -> Option<Vec<&'static str>> {
                //     #map
                // }
            }
        }
    } else {
        let generics = parsed.generic_args_with_lifetimes();
        let rustg = &parsed.rust_generics;
        quote! {

            impl#rustg ::typescript_definitions::TypeScriptifyTrait for #ident<#(#generics),*> {
                fn type_script_ify() ->  String {
                    #body
                }

                // fn type_script_fields() -> Option<Vec<&'static str>> {
                //     #map
                // }
            }
        }
    };
    if let Some("1") = option_env!("TFY_SHOW_CODE") {
        eprintln!("{}", patch(&ret.to_string()));
    }

    ret
}
struct Typescriptify {
    ctxt: ParseContext<'static>,
    ident: syn::Ident,                         // name of enum struct
    ts_generics: Vec<Option<(Ident, Bounds)>>, // None means a lifetime parameter
    body: QuoteMaker,
    rust_generics: syn::Generics, // original rust generics
}
impl Typescriptify {
    fn wasm_string(&self) -> String {
        if self.ctxt.is_enum.get() {
            format!(
                "export enum {} {};",
                self.ts_ident_str(),
                self.ts_body_str()
            )
        } else {
            format!(
                "export type {} = {};",
                self.ts_ident_str(),
                self.ts_body_str()
            )
        }
    }

    fn ts_ident_str(&self) -> String {
        let ts_ident = self.ts_ident().to_string();
        patch(&ts_ident).into()
    }
    fn ts_body_str(&self) -> String {
        let ts = self.body.to_string();
        patch(&ts).into()
    }
    /// type name suitable for typescript i.e. *no* 'a lifetimes
    fn ts_ident(&self) -> QuoteT {
        let ident = &self.ident;

        // currently we ignore trait bounds
        let args_wo_lt: Vec<_> = self.ts_generic_args_wo_lifetimes(false).collect();
        if args_wo_lt.is_empty() {
            quote!(#ident)
        } else {
            quote!(#ident<#(#args_wo_lt),*>)
        }
    }

    fn ts_generic_args_wo_lifetimes(&self, with_bounds: bool) -> impl Iterator<Item = QuoteT> + '_ {
        self.ts_generics.iter().filter_map(move |g| match g {
            Some((ref ident, ref bounds)) => {
                // we ignore trait bounds for typescript
                if bounds.is_empty() || !with_bounds {
                    Some(quote! (#ident))
                } else {
                    let bounds = bounds.iter().map(|ts| &ts.ident);
                    Some(quote! { #ident extends #(#bounds)&* })
                }
            }

            _ => None,
        })
    }

    fn generic_args_with_lifetimes(&self) -> impl Iterator<Item = QuoteT> + '_ {
        // suitable for impl<...> Trait for T<#generic_args_with_lifetime> ...
        // we need to return quotes because '_ is not an Ident
        self.ts_generics.iter().map(|g| match g {
            Some((ref i, ref _bounds)) => quote!(#i),
            None => quote!('_), // only need '_
        })
    }

    #[allow(unused)]
    fn map(&self) -> QuoteT {
        match &self.body {
            quotet::QuoteT::Builder(b) => match b.map() {
                Some(t) => t,
                _ => quote!(None),
            },
            _ => quote!(None),
        }
    }

    fn parse(is_type_script_ify: bool, input: QuoteT) -> Self {
        let input: DeriveInput = syn::parse2(input).unwrap();

        let cx = Ctxt::new();
        let container = ast::Container::from_ast(&cx, &input, Derive::Serialize);

        let (typescript, ctxt) = {
            let pctxt = ParseContext::new(is_type_script_ify, &cx);

            let typescript = match container.data {
                ast::Data::Enum(ref variants) => pctxt.derive_enum(variants, &container),
                ast::Data::Struct(style, ref fields) => {
                    pctxt.derive_struct(style, fields, &container)
                }
            };
            // erase serde context
            (
                typescript,
                ParseContext {
                    ctxt: None,
                    ..pctxt
                },
            )
        };

        let ts_generics = ts_generics(container.generics);

        // consumes context panics with errors
        cx.check().unwrap();
        Self {
            ctxt,
            ident: container.ident,
            ts_generics,
            body: typescript,
            rust_generics: container.generics.clone(), // keep original type generics around for type_script_ify
        }
    }
}

fn ts_generics(g: &syn::Generics) -> Vec<Option<(Ident, Bounds)>> {
    // lifetime params are represented by None since we are only going
    // to translate them to '_

    // impl#generics TypeScriptTrait for A<... lifetimes to '_ and T without bounds>

    use syn::{ConstParam, GenericParam, LifetimeDef, TypeParam, TypeParamBound};
    g.params
        .iter()
        .map(|p| match p {
            GenericParam::Lifetime(LifetimeDef { /* lifetime,*/ .. }) => None,
            GenericParam::Type(TypeParam { ident, bounds, ..}) => {
                let bounds = bounds.iter()
                    .filter_map(|b| match b {
                        TypeParamBound::Trait(t) => Some(&t.path),
                        _ => None // skip lifetimes for bounds
                    })
                    .map(last_path_element)
                    .filter_map(|b| b)
                    .collect::<Vec<_>>();

                Some((ident.clone(), bounds))
            },
            GenericParam::Const(ConstParam { ident, ..}) => Some((ident.clone(), vec![])),

        })
        .collect()
}

fn return_type(rt: &syn::ReturnType) -> Option<syn::Type> {
    match rt {
        syn::ReturnType::Default => None, // e.g. undefined
        syn::ReturnType::Type(_, tp) => Some(*tp.clone()),
    }
}

// represents a typescript type T<A,B>
struct TSType {
    ident: syn::Ident,
    args: Vec<syn::Type>,
    return_type: Option<syn::Type>, // only if function
}
fn last_path_element(path: &syn::Path) -> Option<TSType> {
    match path.segments.last().map(|p| p.into_value()) {
        Some(t) => {
            let ident = t.ident.clone();
            let args = match &t.arguments {
                syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
                    args,
                    ..
                }) => args,
                // closures Fn(A,B) -> C
                syn::PathArguments::Parenthesized(syn::ParenthesizedGenericArguments {
                    output,
                    inputs,
                    ..
                }) => {
                    let args: Vec<_> = inputs.iter().cloned().collect();
                    let ret = return_type(output);
                    return Some(TSType {
                        ident,
                        args,
                        return_type: ret,
                    });
                }
                syn::PathArguments::None => {
                    return Some(TSType {
                        ident,
                        args: vec![],
                        return_type: None,
                    });
                }
            };
            // ignore lifetimes
            let args = args
                .iter()
                .filter_map(|p| match p {
                    syn::GenericArgument::Type(t) => Some(t),
                    _ => None, // bindings A=I, expr, constraints A : B ... skip!
                })
                .cloned()
                .collect::<Vec<_>>();

            Some(TSType {
                ident,
                args,
                return_type: None,
            })
        }
        None => None,
    }
}

struct ParseContext<'a> {
    ctxt: Option<&'a Ctxt>, // serde parse context for error reporting
    is_enum: Cell<bool>,

    #[allow(unused)]
    is_type_script_ify: bool,
}
impl<'a> ParseContext<'a> {
    fn new(is_type_script_ify: bool, ctxt: &'a Ctxt) -> ParseContext<'a> {
        ParseContext {
            is_enum: Cell::new(false),
            ctxt: Some(ctxt),
            is_type_script_ify,
        }
    }
    fn generic_to_ts(&self, ts: TSType, field: &'a ast::Field<'a>) -> QuoteT {
        let to_ts = |ty: &syn::Type| self.type_to_ts(ty, field);

        match ts.ident.to_string().as_ref() {
            "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "i8" | "i16" | "i32" | "i64"
            | "i128" | "isize" | "f64" | "f32" => quote! { number },
            "String" | "str" => quote! { string },
            "bool" => quote! { boolean },
            "Box" | "Cow" | "Rc" | "Arc" if ts.args.len() == 1 => to_ts(&ts.args[0]),

            // std::collections
            "Vec" | "VecDeque" | "LinkedList" if ts.args.len() == 1 => {
                self.type_to_array(&ts.args[0], field)
            }
            "HashMap" | "BTreeMap" if ts.args.len() == 2 => {
                let k = to_ts(&ts.args[0]);
                let v = to_ts(&ts.args[1]);
                // quote!(Map<#k,#v>)
                quote!( { [key: #k]:#v } )
            }
            "HashSet" | "BTreeSet" if ts.args.len() == 1 => {
                let k = to_ts(&ts.args[0]);
                //quote!(Set<#k>)
                quote! ( #k[] )
            }
            "Option" if ts.args.len() == 1 => {
                let k = to_ts(&ts.args[0]);
                quote!(  #k | null  )
            }
            "Result" if ts.args.len() == 2 => {
                let k = to_ts(&ts.args[0]);
                let v = to_ts(&ts.args[1]);
                // ugh!
                // see patch.rs...
                let vertical_bar = ident_from_str(patch::PATCH);
                quote!(  { Ok : #k } #vertical_bar { Err : #v }  )
            }
            "Fn" | "FnOnce" | "FnMut" => {
                let args = self.derive_syn_types(&ts.args, field);
                if let Some(ref rt) = ts.return_type {
                    let rt = to_ts(rt);
                    quote! { (#(#args),*) => #rt }
                } else {
                    quote! { (#(#args),*) => undefined }
                }
            }
            _ => {
                let ident = ts.ident;
                if !ts.args.is_empty() {
                    // let args = ts.args.iter().map(|ty| self.type_to_ts(ty));
                    let args = self.derive_syn_types(&ts.args, field);
                    quote! { #ident<#(#args),*> }
                } else {
                    quote! {#ident}
                }
            }
        }
    }

    fn get_path(&self, ty: &syn::Type) -> Option<TSType> {
        use syn::Type::Path;
        use syn::TypePath;
        match ty {
            Path(TypePath { path, .. }) => last_path_element(&path),
            _ => None,
        }
    }
    fn type_to_array(&self, elem: &syn::Type, field: &'a ast::Field<'a>) -> QuoteT {
        // check for [u8] or Vec<u8>

        if let Some(ty) = self.get_path(elem) {
            if ty.ident == "u8" && is_bytes(field) {
                return quote!(string);
            };
        };

        let tp = self.type_to_ts(elem, field);
        quote! { #tp[] }
    }
    /// # convert a `syn::Type` rust type to a
    /// `TokenStream` of typescript type: basically i32 => number etc.
    ///
    /// field is the current Field for which we are trying a conversion
    fn type_to_ts(&self, ty: &syn::Type, field: &'a ast::Field<'a>) -> QuoteT {
        // `type_to_ts` recursively calls itself occationally
        // finding a Path which it hands to last_path_element
        // which generates a "simplified" TSType struct which
        // is handed to `generic_to_ts` which possibly "bottoms out"
        // by generating tokens for typescript types.

        use syn::Type::*;
        use syn::{
            BareFnArgName, TypeArray, TypeBareFn, TypeGroup, TypeImplTrait, TypeParamBound,
            TypeParen, TypePath, TypePtr, TypeReference, TypeSlice, TypeTraitObject, TypeTuple,
        };
        match ty {
            Slice(TypeSlice { elem, .. })
            | Array(TypeArray { elem, .. })
            | Ptr(TypePtr { elem, .. }) => self.type_to_array(elem, field),
            Reference(TypeReference { elem, .. }) => self.type_to_ts(elem, field),
            // fn(a: A,b: B, c:C) -> D
            BareFn(TypeBareFn { output, inputs, .. }) => {
                let mut args: Vec<Ident> = Vec::with_capacity(inputs.len());
                let mut typs: Vec<&syn::Type> = Vec::with_capacity(inputs.len());

                for (idx, t) in inputs.iter().enumerate() {
                    let i = match t.name {
                        Some((ref n, _)) => match n {
                            BareFnArgName::Named(m) => m.clone(),
                            _ => ident_from_str("_"), // Wild token '_'
                        },
                        _ => ident_from_str(&format!("_dummy{}", idx)),
                    };
                    args.push(i);
                    typs.push(&t.ty); // TODO: check type is known
                }
                // typescript lambda (a: A, b:B) => C

                // let typs = typs.iter().map(|ty| self.type_to_ts(ty));
                let typs = self.derive_syn_types_ptr(&typs, field);
                if let Some(ref rt) = return_type(&output) {
                    let rt = self.type_to_ts(rt, field);
                    quote! { ( #(#args: #typs),* ) => #rt }
                } else {
                    quote! { ( #(#args: #typs),* ) => undefined}
                }
            }
            Never(..) => quote! { never },
            Tuple(TypeTuple { elems, .. }) => {
                let elems = elems.iter().map(|t| self.type_to_ts(t, field));
                quote!([ #(#elems),* ])
            }

            Path(TypePath { path, .. }) => match last_path_element(&path) {
                Some(ts) => self.generic_to_ts(ts, field),
                _ => quote! { any },
            },
            TraitObject(TypeTraitObject { bounds, .. })
            | ImplTrait(TypeImplTrait { bounds, .. }) => {
                let elems = bounds
                    .iter()
                    .filter_map(|t| match t {
                        TypeParamBound::Trait(t) => last_path_element(&t.path),
                        _ => None, // skip lifetime etc.
                    })
                    .map(|t| self.generic_to_ts(t, field));

                // TODO check for zero length?
                // A + B + C => A & B & C
                quote!(#(#elems)&*)
            }
            Paren(TypeParen { elem, .. }) | Group(TypeGroup { elem, .. }) => {
                let tp = self.type_to_ts(elem, field);
                quote! { ( #tp ) }
            }
            Infer(..) | Macro(..) | Verbatim(..) => quote! { any },
        }
    }

    // Some helpers

    fn field_to_ts(&self, field: &ast::Field<'a>) -> QuoteT {
        self.type_to_ts(&field.ty, field)
    }

    fn derive_field(&self, field: &ast::Field<'a>) -> QuoteT {
        let field_name = field.attrs.name().serialize_name(); // use serde name instead of field.member
        let field_name = ident_from_str(&field_name);

        let ty = self.field_to_ts(&field);

        quote! {
            #field_name: #ty
        }
    }
    fn derive_fields(
        &'a self,
        fields: &'a [&'a ast::Field<'a>],
    ) -> impl Iterator<Item = QuoteT> + 'a {
        fields.iter().map(move |f| self.derive_field(f))
    }
    fn derive_field_types(
        &'a self,
        fields: &'a [&'a ast::Field<'a>],
    ) -> impl Iterator<Item = QuoteT> + 'a {
        fields.iter().map(move |f| self.field_to_ts(f))
    }
    fn derive_syn_types_ptr(
        &'a self,
        types: &'a [&'a syn::Type],
        field: &'a ast::Field<'a>,
    ) -> impl Iterator<Item = QuoteT> + 'a {
        types.iter().map(move |ty| self.type_to_ts(ty, field))
    }
    fn derive_syn_types(
        &'a self,
        types: &'a [syn::Type],
        field: &'a ast::Field<'a>,
    ) -> impl Iterator<Item = QuoteT> + 'a {
        types.iter().map(move |ty| self.type_to_ts(ty, field))
    }

    fn check_flatten(&self, fields: &[&'a ast::Field<'a>], ast_container: &ast::Container) -> bool {
        let has_flatten = fields.iter().any(|f| f.attrs.flatten()); // .any(|f| f);
        if has_flatten {
            if let Some(ref ct) = self.ctxt {
                ct.error(format!(
                    "{}: #[serde(flatten)] does not work for typescript-definitions currently",
                    ast_container.ident.to_string()
                ));
            }
        };
        has_flatten
    }
}

#[cfg(test)]
mod macro_test {
    use super::quote;
    use super::Typescriptify;
    use insta::assert_debug_snapshot_matches;
    #[test]
    // #[should_panic]
    fn tag_clash_in_enum() {
        let tokens = quote!(
            #[derive(Serialize)]
            #[serde(tag = "kind")]
            enum A {
                Unit,
                B { kind: i32, b: String },
            }
        );

        let result = std::panic::catch_unwind(move || Typescriptify::parse(true, tokens));
        match result {
            Ok(_x) => assert!(false, "expecting panic!"),
            Err(ref msg) => assert_debug_snapshot_matches!( msg.downcast_ref::<String>().unwrap(),
            @r###""called `Result::unwrap()` on an `Err` value: \"2 errors:\\n\\t# variant field name `kind` conflicts with internal tag\\n\\t# clash with field in \\\"A::B\\\". Maybe use a #[serde(content=\\\"...\\\")] attribute.\"""###
            ),
        }
    }
    #[test]
    fn flatten_is_fail() {
        let tokens = quote!(
            #[derive(Serialize)]
            struct SSS {
                a: i32,
                b: f64,
                #[serde(flatten)]
                c: DDD,
            }
        );
        let result = std::panic::catch_unwind(move || Typescriptify::parse(true, tokens));
        match result {
            Ok(_x) => assert!(false, "expecting panic!"),
            Err(ref msg) => assert_debug_snapshot_matches!( msg.downcast_ref::<String>().unwrap(),
            @r###""called `Result::unwrap()` on an `Err` value: \"SSS: #[serde(flatten)] does not work for typescript-definitions currently\"""###
            ),
        }
    }

}