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
#![feature(box_patterns)]
#![deny(unused_variables)]
#![recursion_limit = "4096"]

#[macro_use]
extern crate pmutil;
extern crate proc_macro;

use pmutil::{Quote, ToTokensExt};
use swc_macros_common::prelude::*;
use syn::{fold::Fold, ExprTryBlock, FnArg, Ident, ImplItem, ImplItemMethod, ItemImpl, Lifetime, ReturnType, Token, Type, TypeReference};

/// This macro converts
///
/// ```ignore
/// impl Foo {
///     #[extra_validator]
///     fn validate_foo(&mut self, arg: Arg1) -> Result<Ret, ()> {
///         // body
///         Err(err)?;
///     }
/// }
/// ```
///
/// to
///
///
/// ```ignore
/// impl Foo {
///     fn validate_foo(&mut self, arg: Arg1) -> Result<Ret, ()> {
///         let res: Result<Ret, Error> = try {
///             // body
///             Err(err)?
///         };
///
///         match res {
///             Ok(v) => Ok(v),
///             Err(err) => {
///                 self.info.errors.push(err);
///                 Err(())
///             }
///         }
///     }
/// }
/// ```
#[proc_macro_attribute]
pub fn extra_validator(_: proc_macro::TokenStream, item: proc_macro::TokenStream) -> proc_macro::TokenStream {
    fn expand_extra_validator(i: ImplItemMethod) -> ImplItemMethod {
        let should_return = !matches!(i.sig.output, ReturnType::Default);

        let try_block = ExprTryBlock {
            attrs: Default::default(),
            try_token: call_site(),
            block: i.block,
        };

        let block = if should_return {
            Quote::new_call_site()
                .quote_with(smart_quote!(Vars { try_block: &try_block }, {
                    {
                        let res: Result<_, stc_ts_errors::Error> = try_block;

                        match res {
                            Ok(v) => Ok(v),
                            Err(err) => {
                                self.storage.report(err);
                                Err(())
                            }
                        }
                    }
                }))
                .parse()
        } else {
            Quote::new_call_site()
                .quote_with(smart_quote!(Vars { try_block: &try_block }, {
                    {
                        let res: Result<_, stc_ts_errors::Error> = try_block;

                        match res {
                            Err(err) => {
                                self.storage.report(err);
                            }
                            _ => {}
                        }
                    }
                }))
                .parse()
        };

        ImplItemMethod { block, ..i }
    }

    let item = syn::parse(item).expect("failed to parse input as an item");
    let item = expand_extra_validator(item);
    print("extra_validator", item.dump())
}

/// This trait implements Validate with proper types.
#[proc_macro_attribute]
pub fn validator(_: proc_macro::TokenStream, item: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let impl_item: ItemImpl = syn::parse(item).expect("failed to parse input as an ItemImpl");
    let visitor_type = &*impl_item.self_ty;

    let mut tokens = q!({});
    for mtd in &impl_item.items {
        let mtd = match mtd {
            ImplItem::Method(m) => m,
            _ => unimplemented!("items other than method is not supported yet"),
        };
        let sig = &mtd.sig;
        assert_eq!(sig.ident, "validate", "#[validator] wants the name of method `validate`");

        // We want to implement Validate<'context, T> for Analyzer, so we need to find
        // `T`.
        let mut node_pat = None;
        let mut node_type = None;
        let mut context_types = Punctuated::<_, Token![,]>::default();
        let mut context_pats = Punctuated::<_, Token![,]>::default();
        for input in sig.inputs.pairs().skip(1) {
            match input.value() {
                FnArg::Receiver(_) => panic!("Expected type, not receiver"),
                FnArg::Typed(pat_ty) => {
                    let ty = &*pat_ty.ty;

                    // Find `T`
                    if node_type.is_none() {
                        match ty {
                            Type::Reference(ty) if ty.mutability.is_none() => {
                                node_type = Some(ty.elem.clone());
                            }
                            _ => unimplemented!("first argument should be self and second argument must be `&T`"),
                        }
                        node_pat = Some(pat_ty.pat.clone());
                        continue;
                    }

                    // Now we look for extra context args
                    // TODO(kdy1): Fix span
                    {
                        let mut ty = ty.clone();
                        ty = LifetimeReplacer.fold_type(ty);

                        context_types.push(ty);
                        context_pats.push(pat_ty.pat.clone());
                    }
                }
            }
        }

        let ret_ty = &mtd.sig.output;
        let default_ty;
        let ret_ty = match ret_ty {
            ReturnType::Type(_, ty) => &**ty,
            ReturnType::Default => {
                default_ty = q!((crate::VResult<()>)).parse();
                &default_ty
            }
        };

        let mut item = q!(
            Vars {
                VisitorType: visitor_type,
                NodeType: &node_type,
                ReturnType: &ret_ty,
                ContextType: &context_types,
                body: &mtd.block,
                node_pat: &node_pat.unwrap(),
                context_pats: &context_pats,
            },
            {
                impl<'context> crate::validator::Validate<'context, NodeType> for VisitorType {
                    type Context = (ContextType);
                    type Output = ReturnType;

                    fn validate(&mut self, node_pat: &NodeType, ctxt: Self::Context) -> Self::Output {
                        let (context_pats) = ctxt;

                        body
                    }
                }
            }
        )
        .parse::<ItemImpl>();
        item.attrs.extend(impl_item.attrs.clone());

        tokens.push_tokens(&item)
    }

    print("validator", tokens.dump())
}

struct LifetimeReplacer;

impl Fold for LifetimeReplacer {
    fn fold_type_reference(&mut self, mut i: TypeReference) -> TypeReference {
        i.lifetime = Some(Lifetime {
            apostrophe: call_site(),
            ident: Ident::new("context", call_site()),
        });
        i
    }
}