hyperlane-macros 21.0.0

A comprehensive collection of procedural macros for building HTTP servers with enhanced functionality. This crate provides attribute macros that simplify HTTP request handling, protocol validation, response management, and request data extraction.
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
use crate::*;

/// Expands macro with code inserted before method body, providing both context and stream identifiers.
///
/// # Arguments
///
/// - `TokenStream` - The input token stream to process.
/// - `FnOnce(&Ident, &Ident) -> TokenStream2` - Function to generate code inserted before, receiving context and stream idents.
///
/// # Returns
///
/// - `TokenStream` - The expanded token stream with inserted code.
fn inject_at_start(
    input: TokenStream,
    before_fn: impl FnOnce(&Ident, &Ident) -> TokenStream2,
) -> TokenStream {
    let mut input_fn: ItemFn = parse_macro_input!(input as ItemFn);
    let vis: &Visibility = &input_fn.vis;
    let sig: &mut Signature = &mut input_fn.sig;
    let block: &Block = &input_fn.block;
    let attrs: &Vec<Attribute> = &input_fn.attrs;
    match parse_context_from_signature(sig) {
        Ok(context) => match parse_stream_from_signature(sig) {
            Ok(stream) => {
                let before_code: TokenStream2 = before_fn(&context, &stream);
                let stmts: &Vec<Stmt> = &block.stmts;
                let gen_code: TokenStream2 = quote! {
                    #(#attrs)*
                    #vis #sig {
                        #before_code
                        #(#stmts)*
                    }
                };
                gen_code.into()
            }
            Err(err) => err.to_compile_error().into(),
        },
        Err(err) => err.to_compile_error().into(),
    }
}

/// Expands macro with code inserted after method body, providing both context and stream identifiers.
///
/// # Arguments
///
/// - `TokenStream` - The input `TokenStream` to process.
/// - `FnOnce(&Ident, &Ident) -> TokenStream2` - A closure that takes context and stream identifiers and returns a `TokenStream` to be inserted at the end of the method.
fn inject_at_end(
    input: TokenStream,
    after_fn: impl FnOnce(&Ident, &Ident) -> TokenStream2,
) -> TokenStream {
    let mut input_fn: ItemFn = parse_macro_input!(input as ItemFn);
    let vis: &Visibility = &input_fn.vis;
    let sig: &mut Signature = &mut input_fn.sig;
    let block: &Block = &input_fn.block;
    let attrs: &Vec<Attribute> = &input_fn.attrs;
    match parse_context_from_signature(sig) {
        Ok(context) => match parse_stream_from_signature(sig) {
            Ok(stream) => {
                let after_code: TokenStream2 = after_fn(&context, &stream);
                let stmts: &Vec<Stmt> = &block.stmts;
                let (leading_stmts, tail_expr) = if let Some((last, leading)) = stmts.split_last() {
                    match last {
                        Stmt::Expr(expr, None) => (leading, Some(quote! { #expr })),
                        _ => (stmts.as_slice(), None),
                    }
                } else {
                    (stmts.as_slice(), None)
                };
                let normalized_leading: Vec<TokenStream2> = leading_stmts
                    .iter()
                    .map(|stmt| match stmt {
                        Stmt::Expr(expr, None) => quote! { #expr; },
                        _ => quote! { #stmt },
                    })
                    .collect();
                let gen_code: TokenStream2 = match tail_expr {
                    Some(expr) => quote! {
                        #(#attrs)*
                        #vis #sig {
                            #(#normalized_leading)*
                            #after_code
                            #expr
                        }
                    },
                    None => quote! {
                        #(#attrs)*
                        #vis #sig {
                            #(#normalized_leading)*
                            #after_code
                        }
                    },
                };
                gen_code.into()
            }
            Err(err) => err.to_compile_error().into(),
        },
        Err(err) => err.to_compile_error().into(),
    }
}

/// Injects code into a method at a specified position, providing both context and stream identifiers.
///
/// # Arguments
///
/// - `Position` - The position at which to inject the code (`Prologue` or `Epilogue`).
/// - `TokenStream` - The input `TokenStream` of the method to modify.
/// - `FnOnce(&Ident, &Ident) -> TokenStream2` - A closure that generates the code to be injected, based on the method's context and stream identifiers.
///
/// # Returns
///
/// - `TokenStream` - Returns the modified `TokenStream` with the injected code.
pub(crate) fn inject(
    position: Position,
    input: TokenStream,
    hook: impl FnOnce(&Ident, &Ident) -> TokenStream2,
) -> TokenStream {
    match position {
        Position::Prologue => inject_at_start(input, hook),
        Position::Epilogue => inject_at_end(input, hook),
    }
}

/// Parses context identifier from function signature.
///
/// # Arguments
///
/// - `&mut Signature` - The function signature to parse. Modified in place if anonymous `_` is found.
///
/// # Returns
///
/// - `syn::Result<Ident>` - Returns a `syn::Result` containing the context identifier if successful, or an error otherwise.
#[allow(dead_code, clippy::replace_box)]
pub(crate) fn parse_context_from_fn(sig: &mut Signature) -> syn::Result<Ident> {
    let default_ident: Ident = Ident::new("ctx", Span::call_site());
    match sig.inputs.first_mut() {
        Some(FnArg::Typed(pat_type)) => match &*pat_type.pat {
            Pat::Ident(pat_ident) => Ok(pat_ident.ident.clone()),
            Pat::Wild(_) => {
                pat_type.pat = Box::new(Pat::Ident(PatIdent {
                    attrs: Vec::new(),
                    by_ref: None,
                    mutability: None,
                    ident: default_ident.clone(),
                    subpat: None,
                }));
                Ok(default_ident)
            }
            _ => Err(syn::Error::new_spanned(
                &pat_type.pat,
                "expected identifier as first argument",
            )),
        },
        _ => Err(syn::Error::new_spanned(
            &sig.inputs,
            "expected at least one argument",
        )),
    }
}

/// Parses self from method signature and returns the context identifier (second parameter).
///
/// # Arguments
///
/// - `&mut Signature` - The method signature to parse. Modified in place if anonymous `_` is found.
///
/// # Returns
///
/// - `syn::Result<Ident>` - Returns the context identifier from the second parameter.
#[allow(dead_code, clippy::replace_box)]
pub(crate) fn parse_self_from_method(sig: &mut Signature) -> syn::Result<Ident> {
    let default_ident: Ident = Ident::new("ctx", Span::call_site());
    match sig.inputs.first() {
        Some(FnArg::Receiver(_)) => match sig.inputs.iter_mut().nth(1) {
            Some(FnArg::Typed(pat_type)) => match &*pat_type.pat {
                Pat::Ident(pat_ident) => Ok(pat_ident.ident.clone()),
                Pat::Wild(_) => {
                    pat_type.pat = Box::new(Pat::Ident(PatIdent {
                        attrs: Vec::new(),
                        by_ref: None,
                        mutability: None,
                        ident: default_ident.clone(),
                        subpat: None,
                    }));
                    Ok(default_ident)
                }
                _ => Err(syn::Error::new_spanned(
                    &pat_type.pat,
                    "expected identifier as second argument (context)",
                )),
            },
            _ => Err(syn::Error::new_spanned(
                &sig.inputs,
                "expected context as second argument",
            )),
        },
        _ => Err(syn::Error::new_spanned(
            &sig.inputs,
            "expected self as first argument for method",
        )),
    }
}

/// Checks if a type matches `::hyperlane::Context`.
///
/// This function checks if the given type is a reference to `::hyperlane::Context`.
///
/// # Arguments
///
/// - `&Type` - The type to check.
///
/// # Returns
///
/// - `bool` - Returns `true` if the type is `&::hyperlane::Context` or `&mut Context`, `false` otherwise.
fn is_context_type(ty: &Type) -> bool {
    if let Type::Reference(type_ref) = ty
        && let Type::Path(type_path) = &*type_ref.elem
    {
        let path: &Path = &type_path.path;
        if path.segments.len() >= 2 {
            let segments: Vec<_> = path.segments.iter().collect();
            if segments.len() >= 2 {
                let last_two: &[&PathSegment] = &segments[segments.len() - 2..];
                if last_two[0].ident == "hyperlane" && last_two[1].ident == "Context" {
                    return true;
                }
            }
        }
        if path.segments.len() == 1 && path.segments[0].ident == "Context" {
            return true;
        }
    }
    false
}

/// Checks if a type matches `::hyperlane::Stream`.
///
/// This function checks if the given type is a reference to `::hyperlane::Stream`.
///
/// # Arguments
///
/// - `&Type` - The type to check.
///
/// # Returns
///
/// - `bool` - Returns `true` if the type is `&::hyperlane::Stream` or `&mut Stream`, `false` otherwise.
fn is_stream_type(ty: &Type) -> bool {
    if let Type::Reference(type_ref) = ty
        && let Type::Path(type_path) = &*type_ref.elem
    {
        let path: &Path = &type_path.path;
        if path.segments.len() >= 2 {
            let segments: Vec<_> = path.segments.iter().collect();
            if segments.len() >= 2 {
                let last_two: &[&PathSegment] = &segments[segments.len() - 2..];
                if last_two[0].ident == "hyperlane" && last_two[1].ident == "Stream" {
                    return true;
                }
            }
        }
        if path.segments.len() == 1 && path.segments[0].ident == "Stream" {
            return true;
        }
    }
    false
}

/// Parses context identifier from function signature by searching all parameters.
///
/// This function iterates through all function parameters and returns the first one
/// that has type `::hyperlane::Context`. It supports:
/// 1. Methods with self: Searches from the second parameter onwards
/// 2. Functions without self: Searches from the first parameter onwards
/// 3. Context parameter can be at any position
/// 4. Anonymous `_` parameters are automatically renamed to `ctx`
///
/// # Arguments
///
/// - `&mut Signature` - The function signature to parse. Modified in place if anonymous `_` is found.
///
/// # Returns
///
/// - `syn::Result<Ident>` - Returns the context identifier.
#[allow(clippy::replace_box)]
pub(crate) fn parse_context_from_signature(sig: &mut Signature) -> syn::Result<Ident> {
    let default_ident: Ident = Ident::new("ctx", Span::call_site());
    for arg in sig.inputs.iter_mut() {
        if let FnArg::Typed(pat_type) = arg
            && is_context_type(&pat_type.ty)
        {
            match &*pat_type.pat {
                Pat::Ident(pat_ident) => return Ok(pat_ident.ident.clone()),
                Pat::Wild(_) => {
                    pat_type.pat = Box::new(Pat::Ident(PatIdent {
                        attrs: Vec::new(),
                        by_ref: None,
                        mutability: None,
                        ident: default_ident.clone(),
                        subpat: None,
                    }));
                    return Ok(default_ident);
                }
                _ => {
                    return Err(syn::Error::new_spanned(
                        &pat_type.pat,
                        "expected identifier for context parameter",
                    ));
                }
            }
        }
    }
    Err(syn::Error::new_spanned(
        &sig.inputs,
        "expected at least one parameter of type &::hyperlane::Context",
    ))
}

/// Parses stream identifier from function signature by searching all parameters.
///
/// This function iterates through all function parameters and returns the first one
/// that has type `::hyperlane::Stream`. It supports:
/// 1. Methods with self: Searches from the second parameter onwards
/// 2. Functions without self: Searches from the first parameter onwards
/// 3. Stream parameter can be at any position
/// 4. Anonymous `_` parameters are automatically renamed to `stream`
///
/// # Arguments
///
/// - `&mut Signature` - The function signature to parse. Modified in place if anonymous `_` is found.
///
/// # Returns
///
/// - `syn::Result<Ident>` - Returns the stream identifier.
#[allow(clippy::replace_box)]
pub(crate) fn parse_stream_from_signature(sig: &mut Signature) -> syn::Result<Ident> {
    let default_ident: Ident = Ident::new("stream", Span::call_site());
    for arg in sig.inputs.iter_mut() {
        if let FnArg::Typed(pat_type) = arg
            && is_stream_type(&pat_type.ty)
        {
            match &*pat_type.pat {
                Pat::Ident(pat_ident) => return Ok(pat_ident.ident.clone()),
                Pat::Wild(_) => {
                    pat_type.pat = Box::new(Pat::Ident(PatIdent {
                        attrs: Vec::new(),
                        by_ref: None,
                        mutability: None,
                        ident: default_ident.clone(),
                        subpat: None,
                    }));
                    return Ok(default_ident);
                }
                _ => {
                    return Err(syn::Error::new_spanned(
                        &pat_type.pat,
                        "expected identifier for stream parameter",
                    ));
                }
            }
        }
    }
    Err(syn::Error::new_spanned(
        &sig.inputs,
        "expected at least one parameter of type &::hyperlane::Stream",
    ))
}

/// Convert an optional expression into an `Option<isize>` token stream.
///
/// This function supports integer and string literals only:
/// - Integer literals are parsed and converted into `Some(isize)`.
/// - String literals are parsed into `isize` and wrapped in `Some(...)`.
/// - Any other expression types will result in `None`.
/// - If `opt_expr` is `None`, the result is also `None`.
///
/// # Arguments
///
/// - `&Option<Expr>` - An optional reference to the expression to convert.
///
/// # Returns
///
/// - `TokenStream` - A `TokenStream2` representing `Some(isize)` for supported literals, or `None` otherwise.
pub(crate) fn expr_to_isize(opt_expr: &Option<Expr>) -> TokenStream2 {
    match opt_expr {
        Some(expr) => match expr {
            Expr::Lit(ExprLit {
                lit: Lit::Int(lit_int),
                ..
            }) => {
                let value: isize = lit_int.base10_parse::<isize>().unwrap();
                quote! { Some(#value) }
            }
            Expr::Lit(ExprLit {
                lit: Lit::Str(lit_str),
                ..
            }) => {
                let value: isize = lit_str.value().parse().expect("Cannot parse to isize");
                quote! { Some(#value) }
            }
            _ => quote! { None },
        },
        None => quote! { None },
    }
}

/// Generates a token stream that calls `leak_mut()` method on the context identifier.
///
/// # Arguments
///
/// - `&Ident` - The context variable identifier.
///
/// # Returns
///
/// - `TokenStream2` - The token stream calling `#context.leak_mut()`.
pub(crate) fn leak_mut_context(context: &Ident) -> TokenStream2 {
    quote! {
        unsafe { #context.leak_mut() }
    }
}

/// Generates a token stream that calls `leak()` method on the context identifier.
///
/// # Arguments
///
/// - `&Ident` - The context variable identifier.
///
/// # Returns
///
/// - `TokenStream2` - The token stream calling `#context.leak()`.
pub(crate) fn leak_context(context: &Ident) -> TokenStream2 {
    quote! {
        unsafe { #context.leak() }
    }
}