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
extern crate proc_macro;

use std::mem;

use proc_macro::TokenStream;
use proc_macro2::{Ident, Punct, Spacing, Span};
use quote::{quote, ToTokens, TokenStreamExt};
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::token::Comma;

#[proc_macro_attribute]
pub fn handler(meta: TokenStream, item: TokenStream) -> TokenStream {
    let mut ast = syn::parse::<syn::ItemFn>(item).unwrap();

    let app_type = syn::parse::<AppType>(meta).unwrap().ty;
    let new = syn::parse::<MethodArgs>(quote!(cx: Context<#app_type>).into()).unwrap();
    let old = mem::replace(&mut ast.sig.inputs, new.args);

    let (mut app, mut req, mut rest, mut complete) = ("__app", "__req", vec![], false);
    for arg in old {
        if complete {
            panic!("more arguments after #[raw] not allowed");
        }

        let ty = match &arg {
            syn::FnArg::Typed(ty) => ty,
            _ => panic!("did not expect receiver argument in handler"),
        };

        if let Some(attr) = ty.attrs.first() {
            if attr.path.is_ident("raw") {
                complete = true;
                continue;
            }
        }

        use syn::Pat::*;
        match ty.pat.as_ref() {
            Ident(id) => {
                if id.ident == "app" {
                    app = "app";
                } else if id.ident == "application" {
                    app = "application";
                } else if id.ident == "req" {
                    req = "req";
                } else if id.ident == "request" {
                    req = "request";
                } else {
                    rest.push(arg);
                }
            }
            Wild(_) => continue,
            _ => {
                rest.push(arg);
            }
        }
    }

    let mut block = Vec::with_capacity(ast.block.stmts.len() + rest.len() + 6);
    block.push(Statement::get(
        quote!(
            let Context { app, req, path } = cx;
        )
        .into(),
    ));

    let app_name = Ident::new(app, Span::call_site());
    block.push(Statement::get(quote!(let #app_name = app;).into()));
    let req_name = Ident::new(req, Span::call_site());
    block.push(Statement::get(quote!(let #req_name = req;).into()));
    block.push(Statement::get(quote!(let mut __path = path;).into()));

    for arg in rest {
        let typed = match &arg {
            syn::FnArg::Typed(typed) => typed,
            _ => panic!("did not expect receiver argument in handler"),
        };

        let pat = &typed.pat;
        if let Some(attr) = typed.attrs.first() {
            if attr.path.is_ident("rest") {
                block.push(Statement::get(
                    quote!(
                        let #pat = __path.rest(&#req_name)
                            .ok_or(::mendes::ClientError::NotFound)?;
                    )
                    .into(),
                ));
                break;
            }
        }

        let ty = &typed.ty;
        // Handle &str arguments
        if let syn::Type::Reference(type_ref) = ty.as_ref() {
            if let syn::Type::Path(path) = type_ref.elem.as_ref() {
                if path.qself.is_none() && path.path.is_ident("str") {
                    block.push(Statement::get(
                        quote!(
                            let #pat: #ty = __path.next(&#req_name)
                                .ok_or(::mendes::ClientError::NotFound)?;
                        )
                        .into(),
                    ));
                    continue;
                }
            }
        }

        block.push(Statement::get(
            quote!(
                let #pat: #ty = __path.next(&#req_name)
                    .ok_or(::mendes::ClientError::NotFound)?
                    .parse()
                    .map_err(|_| ::mendes::ClientError::NotFound)?;
            )
            .into(),
        ));
    }

    let old = mem::replace(&mut ast.block.stmts, block);
    ast.block.stmts.extend(old);
    TokenStream::from(ast.to_token_stream())
}

struct MethodArgs {
    args: Punctuated<syn::FnArg, Comma>,
}

impl Parse for MethodArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        Ok(Self {
            args: Punctuated::parse_terminated(input)?,
        })
    }
}

struct AppType {
    ty: syn::Type,
}

impl Parse for AppType {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        Ok(Self { ty: input.parse()? })
    }
}

struct Statement {
    stmt: syn::Stmt,
}

impl Statement {
    fn get(tokens: TokenStream) -> syn::Stmt {
        syn::parse::<Statement>(tokens).unwrap().stmt
    }
}

impl Parse for Statement {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        Ok(Self {
            stmt: input.parse()?,
        })
    }
}

#[proc_macro_attribute]
pub fn dispatch(_: TokenStream, item: TokenStream) -> TokenStream {
    let mut ast: syn::ItemFn = syn::parse(item).unwrap();

    let (block, routes) = match ast.block.stmts.get_mut(0) {
        Some(syn::Stmt::Item(syn::Item::Macro(expr))) => {
            if !expr.mac.path.is_ident("path") {
                panic!("dispatch function does not call the path!() macro")
            } else {
                let map = expr.mac.parse_body::<Map>().unwrap();
                (&mut ast.block, map)
            }
        }
        Some(syn::Stmt::Item(syn::Item::Fn(inner))) => {
            if let Some(syn::Stmt::Item(syn::Item::Macro(expr))) = inner.block.stmts.get(0) {
                if !expr.mac.path.is_ident("path") {
                    panic!("dispatch function does not call the path!() macro")
                } else {
                    let map = expr.mac.parse_body::<Map>().unwrap();
                    (&mut inner.block, map)
                }
            } else {
                panic!("did not find expression statement in nested function block");
            }
        }
        _ => panic!("did not find expression statement in block"),
    };

    let new = quote!({
        let app = cx.app.clone();
        #routes
    });

    mem::replace(
        block,
        Box::new(syn::parse::<syn::Block>(new.into()).unwrap()),
    );
    TokenStream::from(ast.to_token_stream())
}

struct Map {
    routes: Vec<Route>,
}

impl Parse for Map {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut routes = vec![];
        while !input.is_empty() {
            if !routes.is_empty() {
                let _ = input.parse::<syn::Token![,]>();
                if input.is_empty() {
                    break;
                }
            }
            routes.push(Route::parse(input)?);
        }
        Ok(Map { routes })
    }
}

impl quote::ToTokens for Map {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let mut route_tokens = proc_macro2::TokenStream::new();
        let mut wildcard = false;
        for route in self.routes.iter() {
            let mut rewind = false;
            if let syn::Pat::Wild(_) = route.component {
                wildcard = true;
                rewind = true;
            }

            route.component.to_tokens(&mut route_tokens);
            route_tokens.append(Punct::new('=', Spacing::Joint));
            route_tokens.append(Punct::new('>', Spacing::Alone));

            let nested = match &route.target {
                Target::Direct(expr) => quote!(#expr(cx).await.unwrap_or_else(|e| app.error(e))),
                Target::Routes(routes) => quote!(#routes),
            };

            if rewind {
                route_tokens.append_all(quote!({ let mut cx = cx.rewind(); #nested }));
            } else {
                route_tokens.append_all(nested);
            }
            route_tokens.append(Punct::new(',', Spacing::Alone));
        }

        if !wildcard {
            route_tokens.extend(quote!(
                _ => app.error(::mendes::ClientError::NotFound.into()),
            ));
        }

        tokens.extend(quote!(match cx.path() {
            #route_tokens
        }));
    }
}

struct Route {
    component: syn::Pat,
    target: Target,
}

impl Parse for Route {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let component = input.parse()?;
        input.parse::<syn::Token![=>]>()?;
        let expr = input.parse::<syn::Expr>()?;
        let target = if let syn::Expr::Macro(mac) = &expr {
            if mac.mac.path.is_ident("path") {
                Target::Routes(mac.mac.parse_body().unwrap())
            } else {
                Target::Direct(expr)
            }
        } else {
            Target::Direct(expr)
        };

        Ok(Route { component, target })
    }
}

#[allow(clippy::large_enum_variant)]
enum Target {
    Direct(syn::Expr),
    Routes(Map),
}