autumn-macros 0.9.0

Proc macros for the Autumn web framework
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
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
//! `#[endpoint]` — mark a typed handler as a service endpoint.
//!
//! The attribute reads the handler's own signature: the `Json<T>` parameter is
//! the request shape, the `Json<T>` in the return type is the response shape,
//! and the route attribute below it supplies the method and path. Nothing is
//! restated, so nothing can drift.
//!
//! It emits a marker type plus its [`Endpoint`] impl, and leaves the handler
//! untouched. The marker carries the real Rust types as associated types, which
//! is what lets a caller in another crate name them without knowing a module
//! path. It also writes the endpoint's JSON descriptor.
//!
//! `#[endpoint]` must sit **above** the route attribute. A route attribute
//! expands first when it is outermost and rewrites the signature, leaving
//! nothing to read; being outermost is what guarantees the pristine signature.

use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote};
use syn::{Ident, ItemFn, LitStr};

use crate::param_helpers::attr_or_cfg_attr_matches_any;
use crate::wire::ir::EndpointDescriptor;
use crate::wire::store;

/// The route attributes `#[endpoint]` can read a method and path from.
const ROUTE_ATTRS: [(&str, &str); 5] = [
    ("get", "GET"),
    ("post", "POST"),
    ("put", "PUT"),
    ("patch", "PATCH"),
    ("delete", "DELETE"),
];

/// Parsed `#[endpoint(...)]` arguments.
struct Args {
    service: String,
    name: Option<String>,
}

impl syn::parse::Parse for Args {
    fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
        let mut service = None;
        let mut name = None;
        while !input.is_empty() {
            let key: Ident = input.parse()?;
            input.parse::<syn::Token![=]>()?;
            let value: LitStr = input.parse()?;
            match key.to_string().as_str() {
                "service" => service = Some(value.value()),
                "name" => name = Some(value.value()),
                other => {
                    return Err(syn::Error::new_spanned(
                        &key,
                        format!(
                            "unknown #[endpoint] argument `{other}`; expected `service` or `name`"
                        ),
                    ));
                }
            }
            if input.peek(syn::Token![,]) {
                input.parse::<syn::Token![,]>()?;
            }
        }
        let service = service.ok_or_else(|| {
            syn::Error::new(
                Span::call_site(),
                "#[endpoint] needs a service name: #[endpoint(service = \"catalog\")]",
            )
        })?;
        // A service name reaches a descriptor's file name, so anything outside
        // this set could steer the write out of the contract directory.
        if service.is_empty() || !service.chars().all(is_name_char) {
            return Err(syn::Error::new(
                Span::call_site(),
                format!(
                    "#[endpoint] service must be a non-empty name of letters, digits, `_` or \
                     `-`, and is `{service}`"
                ),
            ));
        }
        // An endpoint name reaches the file name too, AND becomes the marker
        // type's identifier — so it has to be identifier-shaped, not merely
        // file-safe. A `-` or a leading digit would otherwise panic the macro.
        if let Some(name) = &name
            && !is_identifier(name)
        {
            return Err(syn::Error::new(
                Span::call_site(),
                format!(
                    "#[endpoint] name must be a Rust identifier — it becomes the `{name}_endpoint` \
                     marker type — and is `{name}`"
                ),
            ));
        }
        Ok(Self { service, name })
    }
}

/// Characters an endpoint's service and name may use — the set that is safe in
/// a file name on every platform the workspace builds on.
const fn is_name_char(ch: char) -> bool {
    ch.is_ascii_alphanumeric() || ch == '_' || ch == '-'
}

/// Whether `name` can be used as a Rust identifier.
fn is_identifier(name: &str) -> bool {
    let mut chars = name.chars();
    chars
        .next()
        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

pub fn endpoint_macro(attr: TokenStream, item: &TokenStream) -> TokenStream {
    match expand(attr, item) {
        Ok(ts) => ts,
        Err(err) => {
            let err = err.to_compile_error();
            quote! { #err #item }
        }
    }
}

fn expand(attr: TokenStream, item: &TokenStream) -> Result<TokenStream, syn::Error> {
    let args: Args = syn::parse2(attr)?;
    let func: ItemFn = syn::parse2(item.clone())?;

    let (method, path) = route_of(&func)?;
    let name = args.name.unwrap_or_else(|| func.sig.ident.to_string());
    let marker = format_ident!("{}_endpoint", name);

    let request_ty = func.sig.inputs.iter().find_map(|arg| match arg {
        syn::FnArg::Typed(pat) => crate::api_doc::unwrap_json_body(&pat.ty),
        syn::FnArg::Receiver(_) => None,
    });
    let response_ty = response_type(&func).ok_or_else(|| {
        syn::Error::new_spanned(
            &func.sig,
            "#[endpoint] needs a JSON response: the handler must return `Json<T>`, \
             `AutumnResult<Json<T>>`, or `(StatusCode, Json<T>)`",
        )
    })?;

    let has_body = request_ty.is_some();
    let request_tokens = request_ty.as_ref().map_or_else(
        || quote! { ::autumn_web::wire::NoBody },
        |ty| quote! { #ty },
    );

    write_descriptor(
        &args.service,
        &name,
        &marker,
        &method,
        &path,
        request_ty.as_ref(),
        &response_ty,
    );

    let doc = format!(
        "Wire contract for the `{}.{}` endpoint (`{method} {path}`).\n\n\
         Generated by `#[endpoint]`. Name it from `wire_client!` to call it.",
        args.service, name
    );
    let service = &args.service;

    Ok(quote! {
        #[doc = #doc]
        #[allow(non_camel_case_types)]
        #[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::marker::Copy)]
        pub struct #marker;

        impl ::autumn_web::wire::Endpoint for #marker {
            type Request = #request_tokens;
            type Response = #response_ty;
            const SERVICE: &'static str = #service;
            const NAME: &'static str = #name;
            const METHOD: &'static str = #method;
            const PATH: &'static str = #path;
            const HAS_BODY: bool = #has_body;
        }

        #item
    })
}

/// The `Json<T>` a handler returns, however it is wrapped.
fn response_type(func: &ItemFn) -> Option<syn::Type> {
    let ty = crate::api_doc::sig_output_type(func)?;
    let ty = crate::api_doc::unwrap_result_ok(&ty).unwrap_or(ty);
    crate::api_doc::find_json_in_type(&ty)
}

/// The method and path of the route attribute below `#[endpoint]`.
fn route_of(func: &ItemFn) -> Result<(String, String), syn::Error> {
    for attr in &func.attrs {
        let Some((_, method)) = ROUTE_ATTRS
            .iter()
            .find(|(name, _)| attr_or_cfg_attr_matches_any(attr, &[name]))
        else {
            continue;
        };
        // `#[cfg_attr(predicate, get("/items"))]` is a supported spelling
        // elsewhere, and its own argument list starts with the predicate — so
        // the route's tokens are nested one level down, not where a bare
        // `#[get(...)]` keeps them.
        let route_tokens = if attr.path().is_ident("cfg_attr") {
            let Some(tokens) = nested_route_tokens(attr) else {
                continue;
            };
            tokens
        } else {
            attr.parse_args_with(|input: syn::parse::ParseStream<'_>| input.parse::<TokenStream>())?
        };
        let path = syn::parse2::<RoutePath>(route_tokens)?.0;
        return Ok(((*method).to_owned(), path.value()));
    }
    Err(syn::Error::new_spanned(
        &func.sig,
        "#[endpoint] must sit directly above the route attribute (`#[get]`, `#[post]`, \
         `#[put]`, `#[patch]`, `#[delete]`): it reads the method and path from it, and \
         the handler's signature before the route macro rewrites it",
    ))
}

/// A route attribute's own argument list: a path literal, then anything else.
struct RoutePath(LitStr);

impl syn::parse::Parse for RoutePath {
    fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
        let path: LitStr = input.parse()?;
        // A route attribute carries more than a path (`seo(...)`, and so on).
        // Only the first literal is wanted here.
        input.parse::<TokenStream>()?;
        Ok(Self(path))
    }
}

/// The route attribute's own tokens from inside a `#[cfg_attr(pred, route(…))]`.
fn nested_route_tokens(attr: &syn::Attribute) -> Option<TokenStream> {
    let syn::Meta::List(list) = &attr.meta else {
        return None;
    };
    let nested = list
        .parse_args_with(syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated)
        .ok()?;
    nested.into_iter().find_map(|meta| match meta {
        syn::Meta::List(inner)
            if ROUTE_ATTRS
                .iter()
                .any(|(name, _)| inner.path.is_ident(name)) =>
        {
            Some(inner.tokens)
        }
        _ => None,
    })
}

/// Write this endpoint's JSON descriptor, if a contract directory resolves.
fn write_descriptor(
    service: &str,
    name: &str,
    marker: &Ident,
    method: &str,
    path: &str,
    request_ty: Option<&syn::Type>,
    response_ty: &syn::Type,
) {
    let Some(dir) = store::contract_dir() else {
        return;
    };
    let krate = std::env::var("CARGO_PKG_NAME").unwrap_or_default();
    store::write_endpoint(
        &dir,
        &EndpointDescriptor {
            service: service.to_owned(),
            name: name.to_owned(),
            endpoint_ident: marker.to_string(),
            krate,
            method: method.to_owned(),
            path: path.to_owned(),
            request_type: request_ty.map_or_else(
                || "NoBody".to_owned(),
                autumn_macros_support::schema::type_name_str,
            ),
            response_type: autumn_macros_support::schema::type_name_str(response_ty),
        },
    );
}

#[cfg(test)]
mod tests {
    use super::*;

    fn expand_str(attr: &str, item: &str) -> String {
        let attr: TokenStream = attr.parse().expect("attr parses");
        let item: TokenStream = item.parse().expect("item parses");
        endpoint_macro(attr, &item).to_string()
    }

    #[test]
    fn a_get_handler_gets_a_body_less_endpoint_impl() {
        let out = expand_str(
            "service = \"catalog\"",
            "#[get(\"/items/{id}\")] async fn get_item(id: Path<String>) -> AutumnResult<Json<Item>> { todo!() }",
        );
        assert!(out.contains("pub struct get_item_endpoint"), "{out}");
        assert!(
            out.contains("type Request = :: autumn_web :: wire :: NoBody"),
            "{out}"
        );
        assert!(out.contains("type Response = Item"), "{out}");
        assert!(
            out.contains("const METHOD : & 'static str = \"GET\""),
            "{out}"
        );
        assert!(
            out.contains("const PATH : & 'static str = \"/items/{id}\""),
            "{out}"
        );
        assert!(out.contains("const HAS_BODY : bool = false"), "{out}");
        assert!(
            out.contains("async fn get_item"),
            "the handler is re-emitted: {out}"
        );
    }

    #[test]
    fn a_post_handler_takes_its_json_parameter_as_the_request() {
        let out = expand_str(
            "service = \"catalog\"",
            "#[post(\"/items\")] async fn create(body: Json<NewItem>) -> AutumnResult<Json<Item>> { todo!() }",
        );
        assert!(out.contains("type Request = NewItem"), "{out}");
        assert!(out.contains("const HAS_BODY : bool = true"), "{out}");
        assert!(
            out.contains("const METHOD : & 'static str = \"POST\""),
            "{out}"
        );
    }

    #[test]
    fn a_validated_json_parameter_is_still_the_request() {
        let out = expand_str(
            "service = \"catalog\"",
            "#[post(\"/items\")] async fn create(body: Valid<Json<NewItem>>) -> Json<Item> { todo!() }",
        );
        assert!(out.contains("type Request = NewItem"), "{out}");
    }

    #[test]
    fn an_explicit_name_renames_the_endpoint_and_its_marker() {
        let out = expand_str(
            "service = \"catalog\", name = \"fetch\"",
            "#[get(\"/items\")] async fn get_item() -> Json<Item> { todo!() }",
        );
        assert!(out.contains("pub struct fetch_endpoint"), "{out}");
        assert!(
            out.contains("const NAME : & 'static str = \"fetch\""),
            "{out}"
        );
    }

    #[test]
    fn a_handler_with_no_route_attribute_is_refused() {
        let out = expand_str(
            "service = \"catalog\"",
            "async fn get_item() -> Json<Item> { todo!() }",
        );
        assert!(
            out.contains("must sit directly above the route attribute"),
            "{out}"
        );
    }

    #[test]
    fn a_handler_with_no_json_response_is_refused() {
        let out = expand_str(
            "service = \"catalog\"",
            "#[get(\"/items\")] async fn get_item() -> &'static str { todo!() }",
        );
        assert!(out.contains("must return `Json<T>`"), "{out}");
    }

    #[test]
    fn a_missing_service_name_is_refused() {
        let out = expand_str(
            "",
            "#[get(\"/items\")] async fn get_item() -> Json<Item> { todo!() }",
        );
        assert!(out.contains("needs a service name"), "{out}");
    }

    #[test]
    fn a_service_name_that_could_steer_a_file_write_is_refused() {
        for bad in ["../../etc/passwd", "cat/alog", "", "cat.alog"] {
            let out = expand_str(
                &format!("service = \"{bad}\""),
                "#[get(\"/items\")] async fn get_item() -> Json<Item> { todo!() }",
            );
            assert!(
                out.contains("must be a non-empty name") || out.contains("needs a service name"),
                "`{bad}` must be refused: {out}"
            );
        }
    }

    /// The name becomes a Rust identifier, so anything else would panic the
    /// macro rather than produce a diagnostic.
    #[test]
    fn an_endpoint_name_that_is_not_an_identifier_is_refused() {
        for bad in ["../oops", "get-item", "2fast", "", "get item"] {
            let out = expand_str(
                &format!("service = \"catalog\", name = \"{bad}\""),
                "#[get(\"/items\")] async fn get_item() -> Json<Item> { todo!() }",
            );
            assert!(
                out.contains("must be a Rust identifier"),
                "`{bad}` must be refused: {out}"
            );
        }
    }

    #[test]
    fn a_route_attribute_behind_cfg_attr_still_yields_its_method_and_path() {
        let out = expand_str(
            "service = \"catalog\"",
            "#[cfg_attr(feature = \"x\", get(\"/items/{id}\"))] async fn get_item(id: Path<String>) -> Json<Item> { todo!() }",
        );
        assert!(
            out.contains("const METHOD : & 'static str = \"GET\""),
            "{out}"
        );
        assert!(
            out.contains("const PATH : & 'static str = \"/items/{id}\""),
            "{out}"
        );
    }

    #[test]
    fn an_unknown_argument_is_refused_rather_than_ignored() {
        let out = expand_str(
            "service = \"catalog\", verison = \"2\"",
            "#[get(\"/items\")] async fn get_item() -> Json<Item> { todo!() }",
        );
        assert!(out.contains("unknown #[endpoint] argument"), "{out}");
    }

    #[test]
    fn a_route_attribute_with_extra_arguments_still_yields_its_path() {
        let out = expand_str(
            "service = \"catalog\"",
            "#[get(\"/items\", seo(title = \"Items\"))] async fn get_item() -> Json<Item> { todo!() }",
        );
        assert!(
            out.contains("const PATH : & 'static str = \"/items\""),
            "{out}"
        );
    }
}