tako-rs-macros 2.0.0

Internal proc macros for tako-rs. Use the `tako-rs` umbrella crate instead.
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
//! Proc macros for the tako-rs framework.
//!
//! Provides [`route`], an attribute macro placed directly above an async
//! handler function. Given an HTTP method and a path with `{name: Type}`
//! placeholders, it generates a sibling `pub struct` whose fields exactly
//! mirror the placeholders, plus:
//!
//! - `pub const METHOD: tako::Method` and `pub const PATH: &'static str`
//! - an `impl TypedParamsStruct` that pulls each field from the request's
//!   `PathParams` extension and parses it via [`core::str::FromStr`]
//!
//! The struct name is auto-derived from the handler function's name
//! (`snake_case` → `PascalCase` + `Params`). For example, `get_user` produces
//! `GetUserParams`. Override the default with `name = "..."` if you need a
//! different identifier.
//!
//! Method-specific shortcuts ([`get`], [`post`], [`put`], [`delete`],
//! [`patch`]) take only the path and an optional `name = "..."`.
//!
//! Usage:
//!
//! ```ignore
//! use tako::{get, route};
//! use tako::extractors::typed_params::TypedParams;
//! use tako::responder::Responder;
//!
//! #[route(GET, "/users/{id: u64}/posts/{post_id: u64}")]
//! async fn get_user(TypedParams(p): TypedParams<GetUserParams>) -> impl Responder {
//!     format!("user {} post {}", p.id, p.post_id)
//! }
//!
//! #[get("/health")]
//! async fn health() -> impl Responder { "ok" }
//!
//! // …in build_router:
//! // router.route(GetUserParams::METHOD, GetUserParams::PATH, get_user);
//! // router.route(HealthParams::METHOD, HealthParams::PATH, health);
//! ```
//!
//! The macro must be attached to a free async fn at module scope — Rust
//! scopes structs declared inside fn bodies to that fn, so the generated
//! type wouldn't be reachable from the handler signature otherwise.

use proc_macro::TokenStream;
use proc_macro2::Span;
use proc_macro2::TokenStream as TokenStream2;
use quote::format_ident;
use quote::quote;
use syn::Ident;
use syn::ItemFn;
use syn::LitStr;
use syn::Token;
use syn::Type;
use syn::parse::Parse;
use syn::parse::ParseStream;
use syn::parse_macro_input;
use syn::parse_str;

struct RouteArgs {
  method: Ident,
  path: LitStr,
  name_override: Option<Ident>,
}

impl Parse for RouteArgs {
  fn parse(input: ParseStream) -> syn::Result<Self> {
    let method: Ident = input.parse()?;
    input.parse::<Token![,]>()?;
    let path: LitStr = input.parse()?;
    let name_override = parse_optional_name(input)?;
    Ok(Self {
      method,
      path,
      name_override,
    })
  }
}

struct ShortcutArgs {
  path: LitStr,
  name_override: Option<Ident>,
}

impl Parse for ShortcutArgs {
  fn parse(input: ParseStream) -> syn::Result<Self> {
    let path: LitStr = input.parse()?;
    let name_override = parse_optional_name(input)?;
    Ok(Self {
      path,
      name_override,
    })
  }
}

/// After the path literal there can optionally be `, name = "Foo"`. Returns
/// `Ok(None)` if the comma/keyword is absent, `Err` only on a malformed key.
fn parse_optional_name(input: ParseStream) -> syn::Result<Option<Ident>> {
  if input.is_empty() {
    return Ok(None);
  }
  input.parse::<Token![,]>()?;
  if input.is_empty() {
    return Ok(None);
  }
  let key: Ident = input.parse()?;
  if key != "name" {
    return Err(syn::Error::new(key.span(), "expected `name = \"...\"`"));
  }
  input.parse::<Token![=]>()?;
  let lit: LitStr = input.parse()?;
  let ident: Ident = parse_str(&lit.value())
    .map_err(|e| syn::Error::new(lit.span(), format!("invalid struct name: {e}")))?;
  Ok(Some(ident))
}

struct PathParam {
  name: Ident,
  ty: Type,
}

/// Parses path placeholders. Two syntaxes are accepted:
/// - typed: `{id: u64}` — emits a field on the generated `*Params` struct
/// - untyped: `{id}` — matchit/axum-style; passes through untouched and does
///   not contribute to the `*Params` struct
///
/// Returns the matchit-friendly stripped path (every placeholder reduced to
/// `{name}`) plus the list of typed `(name, type)` pairs only.
fn parse_path(path: &str, span: Span) -> syn::Result<(String, Vec<PathParam>)> {
  // Route paths are ASCII per RFC 3986 (`reserved` + `unreserved` are both
  // ASCII subsets). Reject anything else up front rather than mojibake the
  // byte stream into the stripped output: previously a multi-byte UTF-8
  // char like `é` (`0xC3 0xA9`) was pushed as two distinct `char` values,
  // both Latin-1 codepoints, breaking exact-path matching against the
  // matchit-compiled route.
  if !path.is_ascii() {
    return Err(syn::Error::new(
      span,
      "route path must be ASCII (RFC 3986); percent-encode any non-ASCII characters",
    ));
  }
  let mut stripped = String::with_capacity(path.len());
  let mut typed = Vec::new();
  let bytes = path.as_bytes();
  let mut i = 0;
  while i < bytes.len() {
    let c = bytes[i];
    if c == b'}' {
      // Stray `}` without a preceding `{` is a path-syntax mistake. Reject
      // explicitly so the error surfaces at macro-expansion time rather
      // than as a downstream matchit mismatch.
      return Err(syn::Error::new(
        span,
        "unexpected '}' in path (no matching '{')",
      ));
    }
    if c != b'{' {
      stripped.push(c as char);
      i += 1;
      continue;
    }
    let close = (i + 1..bytes.len())
      .find(|&j| bytes[j] == b'}')
      .ok_or_else(|| syn::Error::new(span, "unclosed '{' in path"))?;
    let inner = &path[i + 1..close];
    if let Some((name_str, ty_str)) = inner.split_once(':') {
      let name: Ident = parse_str(name_str.trim()).map_err(|e| {
        syn::Error::new(
          span,
          format!("invalid placeholder name '{}': {e}", name_str.trim()),
        )
      })?;
      let ty: Type = parse_str(ty_str.trim()).map_err(|e| {
        syn::Error::new(
          span,
          format!("invalid placeholder type '{}': {e}", ty_str.trim()),
        )
      })?;
      stripped.push('{');
      stripped.push_str(&name.to_string());
      stripped.push('}');
      typed.push(PathParam { name, ty });
    } else {
      let name: Ident = parse_str(inner.trim()).map_err(|e| {
        syn::Error::new(
          span,
          format!("invalid placeholder name '{}': {e}", inner.trim()),
        )
      })?;
      stripped.push('{');
      stripped.push_str(&name.to_string());
      stripped.push('}');
    }
    i = close + 1;
  }
  Ok((stripped, typed))
}

/// `snake_case` → `PascalCase`. `get_user` → `GetUser`. ASCII only, which is
/// fine for Rust identifiers.
fn pascal_case(s: &str) -> String {
  let mut out = String::with_capacity(s.len());
  let mut next_upper = true;
  for ch in s.chars() {
    if ch == '_' {
      next_upper = true;
    } else if next_upper {
      out.extend(ch.to_uppercase());
      next_upper = false;
    } else {
      out.push(ch);
    }
  }
  out
}

/// Shared expansion: given a method ident, a path literal, an optional struct
/// name override, and the handler fn, produce the generated tokens.
///
/// Only emits the `*Params` struct when the path contains at least one typed
/// placeholder (`{id: u64}`). Pure-static or untyped-only paths skip the
/// struct entirely and just register the route.
fn expand_route(
  method: Ident,
  path: LitStr,
  name_override: Option<Ident>,
  func: ItemFn,
) -> TokenStream {
  let span = path.span();
  let path_str = path.value();
  let (stripped, params) = match parse_path(&path_str, span) {
    Ok(v) => v,
    Err(e) => return e.to_compile_error().into(),
  };

  let fn_name = &func.sig.ident;
  // Append a short fingerprint of (method + path) so two handlers that
  // happen to share the same function identifier — common when several
  // modules each define an `fn handler` — generate distinct linkme
  // registrars. Without the suffix the second module's static silently
  // overwrote the first at link time.
  let registrar_suffix = {
    let key = format!("{method}_{path_str}");
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325; // FNV-1a 64-bit offset basis
    for byte in key.as_bytes() {
      hash ^= u64::from(*byte);
      hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
    }
    format!("{hash:016X}")
  };
  let registrar_ident = format_ident!(
    "__TAKO_REGISTER_{}_{}",
    fn_name.to_string().to_uppercase(),
    registrar_suffix,
    span = fn_name.span()
  );

  // No typed placeholders.
  if params.is_empty() {
    // Explicit `name = "..."` keeps emitting a unit marker struct so callers
    // can still reference `Name::METHOD` / `Name::PATH`. Without an override
    // we skip the struct entirely.
    if let Some(struct_name) = name_override {
      let expanded: TokenStream2 = quote! {
        pub struct #struct_name;

        impl #struct_name {
          pub const METHOD: ::tako::Method = ::tako::Method::#method;
          pub const PATH: &'static str = #stripped;
        }

        #[::tako::__private::linkme::distributed_slice(::tako::router::TAKO_ROUTES)]
        #[linkme(crate = ::tako::__private::linkme)]
        static #registrar_ident: fn(&mut ::tako::router::Router) = |__router| {
          __router.route(#struct_name::METHOD, #struct_name::PATH, #fn_name);
        };

        #func
      };
      return expanded.into();
    }

    let expanded: TokenStream2 = quote! {
      #[::tako::__private::linkme::distributed_slice(::tako::router::TAKO_ROUTES)]
      #[linkme(crate = ::tako::__private::linkme)]
      static #registrar_ident: fn(&mut ::tako::router::Router) = |__router| {
        __router.route(::tako::Method::#method, #stripped, #fn_name);
      };

      #func
    };
    return expanded.into();
  }

  let struct_name = name_override.unwrap_or_else(|| {
    format_ident!(
      "{}Params",
      pascal_case(&fn_name.to_string()),
      span = fn_name.span()
    )
  });

  let field_idents: Vec<&Ident> = params.iter().map(|p| &p.name).collect();
  let field_names_str: Vec<String> = params.iter().map(|p| p.name.to_string()).collect();
  let field_types: Vec<&Type> = params.iter().map(|p| &p.ty).collect();

  let expanded: TokenStream2 = quote! {
    pub struct #struct_name {
      #(pub #field_idents: #field_types,)*
    }

    impl #struct_name {
      pub const METHOD: ::tako::Method = ::tako::Method::#method;
      pub const PATH: &'static str = #stripped;
    }

    impl ::tako::extractors::typed_params::TypedParamsStruct for #struct_name {
      fn from_path_params(
        __pp: &::tako::extractors::params::PathParams,
      ) -> ::core::result::Result<Self, ::tako::extractors::typed_params::TypedParamsError> {
        ::core::result::Result::Ok(Self {
          #(
            #field_idents: {
              let __raw = __pp
                .0
                .iter()
                .find(|(__k, _)| __k.as_str() == #field_names_str)
                .map(|(_, __v)| __v.as_str())
                .ok_or(::tako::extractors::typed_params::TypedParamsError::MissingField(
                  #field_names_str,
                ))?;
              <#field_types as ::core::str::FromStr>::from_str(__raw).map_err(|__e| {
                ::tako::extractors::typed_params::TypedParamsError::Parse(
                  #field_names_str,
                  __e.to_string(),
                )
              })?
            },
          )*
        })
      }
    }

    #[::tako::__private::linkme::distributed_slice(::tako::router::TAKO_ROUTES)]
    #[linkme(crate = ::tako::__private::linkme)]
    static #registrar_ident: fn(&mut ::tako::router::Router) = |__router| {
      __router.route(#struct_name::METHOD, #struct_name::PATH, #fn_name);
    };

    #func
  };

  expanded.into()
}

/// Common driver for the method shortcuts (`#[get]`, `#[post]`, ...).
fn shortcut(method_name: &'static str, attr: TokenStream, item: TokenStream) -> TokenStream {
  let ShortcutArgs {
    path,
    name_override,
  } = parse_macro_input!(attr as ShortcutArgs);
  let func = parse_macro_input!(item as ItemFn);
  let method = Ident::new(method_name, Span::call_site());
  expand_route(method, path, name_override, func)
}

#[proc_macro_attribute]
pub fn route(attr: TokenStream, item: TokenStream) -> TokenStream {
  let RouteArgs {
    method,
    path,
    name_override,
  } = parse_macro_input!(attr as RouteArgs);
  let func = parse_macro_input!(item as ItemFn);
  expand_route(method, path, name_override, func)
}

/// `#[get("/path", [name = "Foo"])]` — shorthand for `#[route(GET, ...)]`.
#[proc_macro_attribute]
pub fn get(attr: TokenStream, item: TokenStream) -> TokenStream {
  shortcut("GET", attr, item)
}

/// `#[post("/path", [name = "Foo"])]` — shorthand for `#[route(POST, ...)]`.
#[proc_macro_attribute]
pub fn post(attr: TokenStream, item: TokenStream) -> TokenStream {
  shortcut("POST", attr, item)
}

/// `#[put("/path", [name = "Foo"])]` — shorthand for `#[route(PUT, ...)]`.
#[proc_macro_attribute]
pub fn put(attr: TokenStream, item: TokenStream) -> TokenStream {
  shortcut("PUT", attr, item)
}

/// `#[delete("/path", [name = "Foo"])]` — shorthand for `#[route(DELETE, ...)]`.
#[proc_macro_attribute]
pub fn delete(attr: TokenStream, item: TokenStream) -> TokenStream {
  shortcut("DELETE", attr, item)
}

/// `#[patch("/path", [name = "Foo"])]` — shorthand for `#[route(PATCH, ...)]`.
#[proc_macro_attribute]
pub fn patch(attr: TokenStream, item: TokenStream) -> TokenStream {
  shortcut("PATCH", attr, item)
}