apigate-macros 0.2.2

Procedural macros for apigate — #[service], #[hook], #[map], and route attributes
Documentation
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
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::quote;
use syn::parse::{Parse, ParseStream};
use syn::{Attribute, Error, Ident, Item, ItemFn, LitStr, Path, Result, Token, Type};

use crate::codegen::generate_pipeline_wrapper;
use crate::parse::{parse_assigned, parse_bracketed_paths, set_once};
use crate::template::compile_rewrite_template;

// ---------------------------------------------------------------------------
// ExtractedRoute
// ---------------------------------------------------------------------------

/// Output of route expansion: the `RouteDef` token stream and any helper items
/// (before-wrappers, map-wrappers, rewrite template statics) to inject into the module.
pub(crate) struct ExtractedRoute {
    pub route_def: TokenStream2,
    pub generated_items: Vec<Item>,
}

// ---------------------------------------------------------------------------
// MethodKind
// ---------------------------------------------------------------------------

#[derive(Clone, Copy)]
enum MethodKind {
    Get,
    Post,
    Put,
    Delete,
    Patch,
    Head,
    Options,
}

impl MethodKind {
    /// Tries to recognize an apigate route attribute (e.g. `#[apigate::get]`).
    fn from_attr(attr: &Attribute) -> Option<Self> {
        let last = attr.path().segments.last()?.ident.to_string();

        match last.as_str() {
            "get" => Some(Self::Get),
            "post" => Some(Self::Post),
            "put" => Some(Self::Put),
            "delete" => Some(Self::Delete),
            "patch" => Some(Self::Patch),
            "head" => Some(Self::Head),
            "options" => Some(Self::Options),
            _ => None,
        }
    }

    /// Emits `apigate::Method::*` variant tokens.
    fn to_tokens(self, apigate_path: &TokenStream2) -> TokenStream2 {
        match self {
            Self::Get => quote!(#apigate_path::Method::Get),
            Self::Post => quote!(#apigate_path::Method::Post),
            Self::Put => quote!(#apigate_path::Method::Put),
            Self::Delete => quote!(#apigate_path::Method::Delete),
            Self::Patch => quote!(#apigate_path::Method::Patch),
            Self::Head => quote!(#apigate_path::Method::Head),
            Self::Options => quote!(#apigate_path::Method::Options),
        }
    }
}

// ---------------------------------------------------------------------------
// DataKind
// ---------------------------------------------------------------------------

/// Which request body extractor the route uses (if any).
#[derive(Clone)]
pub(crate) enum DataKind {
    None,
    Query(Type),
    Json(Type),
    Form(Type),
    Multipart,
}

impl Default for DataKind {
    fn default() -> Self {
        Self::None
    }
}

impl DataKind {
    fn allows_map(&self) -> bool {
        matches!(self, Self::Query(_) | Self::Json(_) | Self::Form(_))
    }

    /// Transitions to `next`, erroring if a data kind was already chosen.
    fn set(self, next: DataKind, span: Span) -> Result<DataKind> {
        match self {
            Self::None => Ok(next),
            _ => Err(Error::new(
                span,
                "only one of `query`, `json`, `form`, or `multipart` may be specified",
            )),
        }
    }
}

// ---------------------------------------------------------------------------
// RouteArgs
// ---------------------------------------------------------------------------

/// Parsed arguments of a route attribute (e.g. `#[apigate::get("/path", ...)]`).
pub(crate) struct RouteArgs {
    pub path: LitStr,
    pub to: Option<LitStr>,
    pub policy: Option<LitStr>,
    pub before: Vec<Path>,
    pub map: Option<Path>,
    pub data: DataKind,
    pub path_type: Option<Type>,
}

impl RouteArgs {
    /// Checks cross-field invariants (e.g. `map` requires a typed data kind).
    fn validate(&self) -> Result<()> {
        if self.map.is_some() && !self.data.allows_map() {
            match self.data {
                DataKind::Multipart => {
                    return Err(Error::new(
                        Span::call_site(),
                        "`map` is not supported together with `multipart`",
                    ));
                }
                DataKind::None => {
                    return Err(Error::new(
                        Span::call_site(),
                        "`map` requires one of `query = T`, `json = T`, or `form = T`",
                    ));
                }
                DataKind::Query(_) | DataKind::Json(_) | DataKind::Form(_) => {}
            }
        }

        Ok(())
    }
}

// ---------------------------------------------------------------------------
// RouteArgsBuilder
// ---------------------------------------------------------------------------

#[derive(Default)]
struct RouteArgsBuilder {
    to: Option<LitStr>,
    policy: Option<LitStr>,
    before: Option<Vec<Path>>,
    map: Option<Path>,
    data: DataKind,
    path_type: Option<Type>,
}

impl RouteArgsBuilder {
    fn apply(&mut self, arg: RouteArg) -> Result<()> {
        match arg {
            RouteArg::To(v) => set_once(&mut self.to, v.clone(), v.span(), "to")?,
            RouteArg::Policy(v) => set_once(&mut self.policy, v.clone(), v.span(), "policy")?,
            RouteArg::Before(v) => {
                set_once(&mut self.before, v, Span::call_site(), "before")?;
            }
            RouteArg::Map(v) => set_once(&mut self.map, v, Span::call_site(), "map")?,
            RouteArg::Query(v) => {
                self.data =
                    std::mem::take(&mut self.data).set(DataKind::Query(v), Span::call_site())?;
            }
            RouteArg::Json(v) => {
                self.data =
                    std::mem::take(&mut self.data).set(DataKind::Json(v), Span::call_site())?;
            }
            RouteArg::Form(v) => {
                self.data =
                    std::mem::take(&mut self.data).set(DataKind::Form(v), Span::call_site())?;
            }
            RouteArg::PathType(v) => {
                set_once(&mut self.path_type, v, Span::call_site(), "path")?;
            }
            RouteArg::Flag(RouteFlag::Multipart) => {
                self.data =
                    std::mem::take(&mut self.data).set(DataKind::Multipart, Span::call_site())?;
            }
        }

        Ok(())
    }

    fn build(self, path: LitStr) -> Result<RouteArgs> {
        let args = RouteArgs {
            path,
            to: self.to,
            policy: self.policy,
            before: self.before.unwrap_or_default(),
            map: self.map,
            data: self.data,
            path_type: self.path_type,
        };

        args.validate()?;
        Ok(args)
    }
}

// ---------------------------------------------------------------------------
// RouteArg / RouteFlag
// ---------------------------------------------------------------------------

enum RouteFlag {
    Multipart,
}

enum RouteArg {
    To(LitStr),
    Policy(LitStr),
    Before(Vec<Path>),
    Map(Path),
    Query(Type),
    Json(Type),
    Form(Type),
    PathType(Type),
    Flag(RouteFlag),
}

impl Parse for RouteArg {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let key: Ident = input.parse()?;

        if input.peek(Token![=]) {
            // TODO: Maybe match case?
            if key == "to" {
                Ok(Self::To(parse_assigned(input)?))
            } else if key == "policy" {
                Ok(Self::Policy(parse_assigned(input)?))
            } else if key == "before" {
                input.parse::<Token![=]>()?;
                Ok(Self::Before(parse_bracketed_paths(input)?))
            } else if key == "map" {
                Ok(Self::Map(parse_assigned(input)?))
            } else if key == "query" {
                Ok(Self::Query(parse_assigned(input)?))
            } else if key == "json" {
                Ok(Self::Json(parse_assigned(input)?))
            } else if key == "form" {
                Ok(Self::Form(parse_assigned(input)?))
            } else if key == "path" {
                Ok(Self::PathType(parse_assigned(input)?))
            } else {
                Err(Error::new(
                    key.span(),
                    "unknown route argument, expected one of: \
                     `to`, `policy`, `before`, `map`, `query`, `json`, `form`, `path`",
                ))
            }
        } else if key == "multipart" {
            Ok(Self::Flag(RouteFlag::Multipart))
        } else {
            Err(Error::new(
                key.span(),
                "expected a route path string literal, `key = value`, or a supported bare flag",
            ))
        }
    }
}

impl Parse for RouteArgs {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let path: LitStr = input.parse()?;

        let mut builder = RouteArgsBuilder::default();

        while input.peek(Token![,]) {
            input.parse::<Token![,]>()?;
            if input.is_empty() {
                break;
            }
            builder.apply(input.parse()?)?;
        }

        builder.build(path)
    }
}

// ---------------------------------------------------------------------------
// Route expansion (orchestration)
// ---------------------------------------------------------------------------

struct MatchedRouteAttr {
    idx: usize,
    kind: MethodKind,
    args: RouteArgs,
}

/// Expands a single function inside a `#[apigate::service]` module:
/// finds its route attribute, removes it, and generates a `RouteDef` plus
/// any helper items (before-wrappers, map-wrappers, rewrite statics).
pub(crate) fn expand_route_from_fn(
    apigate_path: &TokenStream2,
    f: &mut ItemFn,
) -> Result<Option<ExtractedRoute>> {
    let Some(matched) = find_route_attr(f)? else {
        return Ok(None);
    };

    f.attrs.remove(matched.idx);
    f.attrs.push(syn::parse_quote!(#[allow(dead_code)]));

    let mut generated_items = Vec::new();

    let rewrite_spec =
        build_rewrite_spec(apigate_path, &matched.args.path, matched.args.to.as_ref())?;

    let pipeline = generate_pipeline_wrapper(
        apigate_path,
        f,
        &matched.args.before,
        &matched.args.data,
        matched.args.map.as_ref(),
        matched.args.path_type.as_ref(),
        &mut generated_items,
    )?;

    let method = matched.kind.to_tokens(apigate_path);
    let path = &matched.args.path;

    let policy = match &matched.args.policy {
        None => quote!(None),
        Some(p) => quote!(Some(#p)),
    };

    let route_def = quote! {
        #apigate_path::RouteDef {
            method: #method,
            path: #path,
            rewrite: #rewrite_spec,
            policy: #policy,
            pipeline: #pipeline,
        }
    };

    Ok(Some(ExtractedRoute {
        route_def,
        generated_items,
    }))
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Scans function attributes for a single `#[apigate::<method>(...)]` and parses it.
/// Returns an error if multiple route attributes are found on the same function.
fn find_route_attr(f: &ItemFn) -> Result<Option<MatchedRouteAttr>> {
    let mut found: Option<MatchedRouteAttr> = None;

    for (idx, attr) in f.attrs.iter().enumerate() {
        let Some(kind) = MethodKind::from_attr(attr) else {
            continue;
        };

        let args: RouteArgs = attr.parse_args()?;

        if found.is_some() {
            return Err(Error::new_spanned(
                attr,
                "multiple apigate route attributes on one function are not supported",
            ));
        }

        found = Some(MatchedRouteAttr { idx, kind, args });
    }

    Ok(found)
}

/// Generates a `RewriteSpec` token stream based on the `to` attribute:
/// - `None` → `StripPrefix`
/// - static string → `Static`
/// - string with `{param}` → inlines a `RewriteTemplate` (const-promoted to `'static`)
fn build_rewrite_spec(
    apigate_path: &TokenStream2,
    path: &LitStr,
    to: Option<&LitStr>,
) -> Result<TokenStream2> {
    match to {
        None => Ok(quote!(#apigate_path::RewriteSpec::StripPrefix)),

        Some(t) if !t.value().contains('{') => Ok(quote!(#apigate_path::RewriteSpec::Static(#t))),

        Some(t) => {
            let compiled = compile_rewrite_template(apigate_path, &path.value(), &t.value())
                .map_err(|msg| Error::new_spanned(t, msg))?;

            let src_tokens = &compiled.src_tokens;
            let dst_tokens = &compiled.dst_tokens;
            let static_len = compiled.static_len;

            Ok(
                quote!(#apigate_path::RewriteSpec::Template(&#apigate_path::RewriteTemplate {
                    src: &[#(#src_tokens),*],
                    dst: &[#(#dst_tokens),*],
                    static_len: #static_len,
                })),
            )
        }
    }
}