elif-http-derive 0.2.11

Derive macros for elif-http declarative routing and controller system
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
//! HTTP method macros implementation
//!
//! Provides #[get], #[post], #[put], #[delete], #[patch], #[head], #[options] macros.

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, ItemFn};

use crate::params::BodyParamType;
use crate::utils::{
    extract_body_param_from_attrs, extract_param_types_from_attrs,
    extract_path_parameters, extract_request_param_name, has_body_attribute, has_request_attribute,
    validate_route_path,
};
use std::collections::HashMap;

/// Generate HTTP method macros with parameter extraction
pub fn http_method_macro_impl(method: &str, args: TokenStream, input: TokenStream) -> TokenStream {
    // Parse route path - can be empty for root routes
    let route_path = if args.is_empty() {
        "".to_string()
    } else {
        let path_lit = match syn::parse::<syn::LitStr>(args) {
            Ok(lit) => lit,
            Err(_) => {
                return syn::Error::new(
                    proc_macro2::Span::call_site(),
                    format!("Invalid path argument for {} macro. Hint: Use a string literal like #[{}(\"/users/{{id}}\")]", method, method.to_lowercase())
                )
                .to_compile_error()
                .into();
            }
        };
        let path = path_lit.value();

        // Validate path format
        if let Err(msg) = validate_route_path(&path) {
            return syn::Error::new_spanned(
                &path_lit,
                format!("Invalid route path '{}': {}. Hint: Use format like '/users/{{id}}' with proper parameter syntax.", path, msg)
            )
            .to_compile_error()
            .into();
        }

        path
    };
    let input_fn = parse_macro_input!(input as ItemFn);

    // Extract path parameters from the route and function signature
    let path_params = extract_path_parameters(&route_path);
    let param_types = extract_param_types_from_attrs(&input_fn.attrs);

    // Check if this method needs parameter injection
    // Apply injection if:
    // 1. Traditional: There are path parameters + #[param] annotations
    // 2. New: #[request] attribute is present (automatic ElifRequest injection)
    // 3. New: #[body] attribute is present (automatic body parameter injection)
    let has_self = input_fn
        .sig
        .inputs
        .iter()
        .any(|arg| matches!(arg, syn::FnArg::Receiver(_)));
    let has_param_annotations = !param_types.is_empty();
    let has_request_attr = has_request_attribute(&input_fn.attrs);
    let has_body_attr = has_body_attribute(&input_fn.attrs);
    let needs_validation = has_self && (
        (!path_params.is_empty() && has_param_annotations) || 
        has_body_attr || 
        has_request_attr
    );

    // Perform validation if we have path parameters, body attributes, or request attributes
    if needs_validation {
        let body_param = extract_body_param_from_attrs(&input_fn.attrs);

        if let Err(validation_error) = validate_method_consistency(
            &route_path,
            &path_params,
            &param_types,
            &input_fn.sig,
            &body_param,
            has_request_attr,
        ) {
            return syn::Error::new_spanned(&input_fn.sig, validation_error)
                .to_compile_error()
                .into();
        }
    }

    // All HTTP method attributed methods need wrapper methods for controller dispatch
    // Extract body parameter information
    let body_param = extract_body_param_from_attrs(&input_fn.attrs);

    // Generate wrapper method (with or without parameter injection)
    generate_injected_method(
        &input_fn,
        &path_params,
        &param_types,
        has_request_attr,
        body_param,
    )
}

/// GET method routing macro
pub fn get_impl(args: TokenStream, input: TokenStream) -> TokenStream {
    http_method_macro_impl("GET", args, input)
}

/// POST method routing macro
pub fn post_impl(args: TokenStream, input: TokenStream) -> TokenStream {
    http_method_macro_impl("POST", args, input)
}

/// PUT method routing macro
pub fn put_impl(args: TokenStream, input: TokenStream) -> TokenStream {
    http_method_macro_impl("PUT", args, input)
}

/// DELETE method routing macro
pub fn delete_impl(args: TokenStream, input: TokenStream) -> TokenStream {
    http_method_macro_impl("DELETE", args, input)
}

/// PATCH method routing macro
pub fn patch_impl(args: TokenStream, input: TokenStream) -> TokenStream {
    http_method_macro_impl("PATCH", args, input)
}

/// HEAD method routing macro
pub fn head_impl(args: TokenStream, input: TokenStream) -> TokenStream {
    http_method_macro_impl("HEAD", args, input)
}

/// OPTIONS method routing macro
pub fn options_impl(args: TokenStream, input: TokenStream) -> TokenStream {
    http_method_macro_impl("OPTIONS", args, input)
}


/// Generate a wrapper method that injects path parameters, body parameters, and/or request into the original method
fn generate_injected_method(
    input_fn: &ItemFn,
    path_params: &[String],
    param_types: &HashMap<String, String>,
    has_request_attr: bool,
    body_param: Option<(String, BodyParamType)>,
) -> TokenStream {
    let original_name = &input_fn.sig.ident;
    let original_fn_name = quote::format_ident!("{}_original", original_name);

    // Build parameter extraction and call arguments in order
    let mut param_extractions = Vec::new();
    let mut call_args = Vec::new();
    let mut modified_inputs = Vec::new();
    let request_param_name = if has_request_attr {
        extract_request_param_name(&input_fn.attrs)
    } else {
        "req".to_string()
    };

    // First, copy existing parameters and check for request parameter
    let mut has_existing_request_param = false;
    for input in &input_fn.sig.inputs {
        match input {
            syn::FnArg::Receiver(_) => {
                // Keep self parameter
                modified_inputs.push(input.clone());
            }
            syn::FnArg::Typed(pat_type) => {
                let param_type = &pat_type.ty;
                let param_type_str = quote! { #param_type }.to_string();

                match pat_type.pat.as_ref() {
                    syn::Pat::Ident(pat_ident) => {
                        let param_name = pat_ident.ident.to_string();

                        // Check parameter type and role
                        if param_type_str.contains("ElifRequest") {
                            // This is the request parameter - pass it through
                            call_args.push(quote! { request });
                            modified_inputs.push(input.clone());
                            has_existing_request_param = true;
                        } else if path_params.contains(&param_name) {
                            // This is a path parameter - generate extraction code
                            let param_ident = &pat_ident.ident;
                            let extraction_method =
                                get_extraction_method(&param_name, param_types, &param_type_str);

                            param_extractions.push(quote! {
                            let #param_ident = request.#extraction_method(#param_name)
                                .map_err(|e| ::elif_http::HttpError::bad_request(format!("Invalid parameter '{}': {:?}", #param_name, e)))?;
                        });
                            call_args.push(quote! { #param_ident });
                            modified_inputs.push(input.clone());
                        } else if let Some((body_param_name, _)) = &body_param {
                            if param_name == *body_param_name {
                                // This is a body parameter - will be handled below
                                let param_ident = &pat_ident.ident;
                                call_args.push(quote! { #param_ident });
                                modified_inputs.push(input.clone());
                            } else {
                                // Unsupported parameter type - generate compile-time error
                                return syn::Error::new_spanned(
                                pat_type,
                                format!(
                                    "Unsupported parameter '{}' of type '{}'. Only path parameters (specified in route), body parameters (annotated with #[body]), and ElifRequest are supported. \
                                    Hint: Remove this parameter, add it to the route path like '/users/{{{}}}' and annotate with #[param({}: type)], annotate with #[body({}: Type)], or use #[request] to enable automatic request injection.",
                                    param_name, param_type_str, param_name, param_name, param_name
                                )
                            )
                            .to_compile_error()
                            .into();
                            }
                        } else {
                            // Unsupported parameter type - generate compile-time error
                            // Any parameter that is not a path parameter or ElifRequest is not supported
                            return syn::Error::new_spanned(
                            pat_type,
                            format!(
                                "Unsupported parameter '{}' of type '{}'. Only path parameters (specified in route), body parameters (annotated with #[body]), and ElifRequest are supported. \
                                Hint: Remove this parameter, add it to the route path like '/users/{{{}}}' and annotate with #[param({}: type)], annotate with #[body({}: Type)], or use #[request] to enable automatic request injection.",
                                param_name, param_type_str, param_name, param_name, param_name
                            )
                        )
                        .to_compile_error()
                        .into();
                        }
                    }

                    // Wildcard patterns: `_: Type`
                    syn::Pat::Wild(_) => {
                        // Wildcards are acceptable - they're explicitly ignored parameters
                        modified_inputs.push(input.clone());
                        // Don't add to call_args since wildcards can't be referenced
                    }

                    // Other unsupported patterns
                    _ => {
                        return syn::Error::new_spanned(
                            pat_type,
                            format!(
                                "Unsupported parameter pattern: '{}'. \
                                Only simple identifiers (e.g., 'param: Type') and wildcards (e.g., '_: Type') are supported in controller methods. \
                                Hint: Use simple parameter names without destructuring or complex patterns.",
                                quote! { #pat_type.pat }
                            )
                        )
                        .to_compile_error()
                        .into();
                    }
                }
            }
        }
    }

    // If #[request] is present and method doesn't have ElifRequest parameter, add it to signature
    if has_request_attr && !has_existing_request_param {
        let req_ident = quote::format_ident!("{}", request_param_name);
        let request_param = syn::parse_quote! {
            #req_ident: ::elif_http::ElifRequest
        };
        modified_inputs.push(request_param);
        call_args.push(quote! { request });
    }

    // Validate that body parameter is not used with ElifRequest parameter
    if let Some((body_param_name, _)) = &body_param {
        if has_existing_request_param {
            return syn::Error::new_spanned(
                &input_fn.sig,
                format!(
                    "Conflicting parameter usage: #[body({})] cannot be used with ElifRequest parameter. \
                    The body extraction wrapper handles the request automatically. \
                    Hint: Remove the ElifRequest parameter from the function signature when using #[body].",
                    body_param_name
                )
            )
            .to_compile_error()
            .into();
        }
    }

    // Add body parameter extraction if present
    if let Some((body_param_name, body_param_type)) = &body_param {
        let body_param_ident = quote::format_ident!("{}", body_param_name);

        // Generate body parsing code based on the body parameter type
        let body_extraction = match body_param_type {
            BodyParamType::Custom(_) => {
                quote! {
                    let #body_param_ident = request.json()
                        .map_err(|e| ::elif_http::HttpError::bad_request(format!("Invalid JSON body: {:?}", e)))?;
                }
            }
            BodyParamType::Form => {
                quote! {
                    let #body_param_ident = request.form()
                        .map_err(|e| ::elif_http::HttpError::bad_request(format!("Invalid form data: {:?}", e)))?;
                }
            }
            BodyParamType::Bytes => {
                quote! {
                    let #body_param_ident = request.body_bytes()
                        .ok_or_else(|| ::elif_http::HttpError::bad_request("No request body".to_string()))?
                        .clone();
                }
            }
        };

        param_extractions.push(body_extraction);
    }

    // Get the original function's components
    let original_attrs = &input_fn
        .attrs
        .iter()
        .filter(|attr| {
            !attr.path().is_ident("get")
                && !attr.path().is_ident("post")
                && !attr.path().is_ident("put")
                && !attr.path().is_ident("delete")
                && !attr.path().is_ident("patch")
                && !attr.path().is_ident("head")
                && !attr.path().is_ident("options")
                && !attr.path().is_ident("param")
                && !attr.path().is_ident("request")
                && !attr.path().is_ident("body")
        })
        .collect::<Vec<_>>();
    let original_vis = &input_fn.vis;
    let original_block = &input_fn.block;
    let original_return = &input_fn.sig.output;
    let original_asyncness = &input_fn.sig.asyncness;

    // Generate the wrapper method's asyncness (always async for HTTP handlers)
    let wrapper_asyncness = quote! { async };

    // Generate the appropriate method call based on original async-ness
    // For async methods, immediately await to avoid self capture issues in generated code
    let method_call = if original_asyncness.is_some() {
        quote! {
            // Call async method immediately to avoid self capture in closures
            self.#original_fn_name(#(#call_args),*).await
        }
    } else {
        quote! {
            // Call sync method directly
            self.#original_fn_name(#(#call_args),*)
        }
    };

    // Analyze the return type to determine how to handle the response
    let return_category = analyze_return_type(original_return);

    // Generate appropriate response handling based on return type
    let response_handling = match return_category {
        ReturnTypeCategory::HttpResultElifResponse => {
            // Already returns HttpResult<ElifResponse> - pass through directly
            quote! { #method_call }
        }
        ReturnTypeCategory::ElifResponse => {
            // Returns ElifResponse - wrap in Ok()
            quote! { Ok(#method_call) }
        }
        ReturnTypeCategory::ResultType => {
            // Returns Result<T, E> - map the Ok case to JSON, pass through errors
            quote! {
                match #method_call {
                    Ok(result) => Ok(ElifResponse::ok().json(&result)?),
                    Err(e) => Err(::elif_http::HttpError::internal(format!("Handler error: {:?}", e)).into()),
                }
            }
        }
        ReturnTypeCategory::Unit => {
            // Returns () - return empty OK response
            quote! {
                #method_call;
                Ok(ElifResponse::ok())
            }
        }
        ReturnTypeCategory::SerializableType => {
            // Returns serializable type - wrap in JSON response
            quote! {
                let result = #method_call;
                Ok(ElifResponse::ok().json(&result)?)
            }
        }
    };

    let expanded = quote! {
        // Keep the original method with modified signature (includes injected request parameter)
        #(#original_attrs)*
        #original_vis #original_asyncness fn #original_fn_name(#(#modified_inputs),*) #original_return #original_block

        // Generate wrapper method that extracts parameters from request
        #original_vis #wrapper_asyncness fn #original_name(&self, request: ElifRequest) -> HttpResult<ElifResponse> {
            // Parameter extraction
            #(#param_extractions)*

            // Handle result based on original function's return type
            #response_handling
        }
    };

    TokenStream::from(expanded)
}

/// Determine how to handle the return value based on the original function's return type
fn analyze_return_type(return_type: &syn::ReturnType) -> ReturnTypeCategory {
    match return_type {
        syn::ReturnType::Default => ReturnTypeCategory::Unit,
        syn::ReturnType::Type(_, ty) => {
            let type_str = quote! { #ty }.to_string();

            // Check for HttpResult<ElifResponse>
            if type_str.contains("HttpResult") && type_str.contains("ElifResponse") {
                ReturnTypeCategory::HttpResultElifResponse
            }
            // Check for ElifResponse
            else if type_str.contains("ElifResponse") {
                ReturnTypeCategory::ElifResponse
            }
            // Check for Result types (including HttpResult<T> where T != ElifResponse)
            else if type_str.contains("Result") || type_str.contains("HttpResult") {
                ReturnTypeCategory::ResultType
            }
            // Everything else (serializable types)
            else {
                ReturnTypeCategory::SerializableType
            }
        }
    }
}

/// Categories of return types for response handling
#[derive(Debug, PartialEq)]
enum ReturnTypeCategory {
    Unit,                   // () - return empty response
    ElifResponse,           // ElifResponse - pass through
    HttpResultElifResponse, // HttpResult<ElifResponse> - pass through
    ResultType,             // Result<T, E> - handle error, serialize T
    SerializableType,       // T - serialize to JSON
}

/// Get the appropriate extraction method name based on parameter type
fn get_extraction_method(
    param_name: &str,
    param_types: &HashMap<String, String>,
    rust_type: &str,
) -> proc_macro2::Ident {
    // Check if we have explicit type information from #[param] attribute
    if let Some(param_type) = param_types.get(param_name) {
        return match param_type.as_str() {
            "Integer" => {
                // For Integer type, check the actual Rust type to determine extraction method
                if rust_type.contains("u32") {
                    quote::format_ident!("path_param_u32")
                } else if rust_type.contains("u64") {
                    quote::format_ident!("path_param_u64")
                } else if rust_type.contains("i64") {
                    quote::format_ident!("path_param_i64")
                } else {
                    quote::format_ident!("path_param_int") // default to i32
                }
            },
            "String" => quote::format_ident!("path_param_string"),
            "Uuid" => quote::format_ident!("path_param_uuid"),
            _ => quote::format_ident!("path_param_string"), // Default to string
        };
    }

    // Fall back to inferring from Rust type
    if rust_type.contains("i32") {
        quote::format_ident!("path_param_int")
    } else if rust_type.contains("u32") {
        quote::format_ident!("path_param_u32")
    } else if rust_type.contains("i64") {
        quote::format_ident!("path_param_i64")
    } else if rust_type.contains("u64") {
        quote::format_ident!("path_param_u64")
    } else {
        quote::format_ident!("path_param_string")
    }
}

/// Comprehensive validation of method consistency between route path, parameters, and function signature
fn validate_method_consistency(
    route_path: &str,
    path_params: &[String],
    param_types: &HashMap<String, String>,
    sig: &syn::Signature,
    body_param: &Option<(String, BodyParamType)>,
    has_request_attr: bool,
) -> Result<(), String> {
    use syn::{FnArg, Pat, PatIdent};

    // Collect function parameters (excluding self and ElifRequest)
    let mut fn_params = HashMap::new();
    let mut has_request_param = false;

    for input in &sig.inputs {
        match input {
            FnArg::Receiver(_) => {
                // Skip self parameter
            }
            FnArg::Typed(pat_type) => {
                let param_type_str = quote! { #pat_type.ty }.to_string().replace(" ", "");

                match pat_type.pat.as_ref() {
                    // Standard identifier: `param: Type` or underscore-prefixed: `_unused: Type`
                    Pat::Ident(PatIdent { ident, .. }) => {
                        let param_name = ident.to_string();

                        // Check for ElifRequest type regardless of underscore prefix
                        if param_type_str.contains("ElifRequest") {
                            has_request_param = true;
                        } else if param_name.starts_with('_') {
                            // These are explicitly marked as unused, don't add to fn_params
                            // but still check for type conflicts above
                        } else {
                            // Regular parameter processing
                            fn_params.insert(param_name, param_type_str);
                        }
                    }

                    // Wildcard patterns: `_: Type`
                    Pat::Wild(_) => {
                        // Wildcards are acceptable - they're explicitly ignored parameters
                        // Don't add to fn_params since they can't be referenced
                    }

                    // Tuple destructuring: `(a, b): (Type1, Type2)`
                    Pat::Tuple(_) => {
                        return Err("Unsupported tuple destructuring pattern in parameter. \
                            Hint: Use individual parameters instead of tuple destructuring. \
                            Example: Change '(a, b): (Type1, Type2)' to 'a: Type1, b: Type2'."
                            .to_string());
                    }

                    // Struct destructuring: `User { name, .. }: User`
                    Pat::Struct(_) => {
                        return Err(format!(
                            "Unsupported struct destructuring pattern in parameter: '{}'. \
                            Hint: Use the complete struct type as parameter. \
                            Example: Change 'User {{ name, .. }}: User' to 'user: User' and access 'user.name'.",
                            quote! { #pat_type.pat }
                        ));
                    }

                    // Reference patterns: `&name: &Type`
                    Pat::Reference(_) => {
                        return Err(format!(
                            "Unsupported reference pattern in parameter: '{}'. \
                            Hint: Remove the reference pattern and use the type directly. \
                            Example: Change '&name: &Type' to 'name: &Type'.",
                            quote! { #pat_type.pat }
                        ));
                    }

                    // Any other pattern
                    _ => {
                        return Err(format!(
                            "Unsupported parameter pattern: '{}'. \
                            Only simple identifiers (e.g., 'param: Type') and wildcards (e.g., '_: Type') are supported in controller methods. \
                            Hint: Use simple parameter names without destructuring or complex patterns.",
                            quote! { #pat_type.pat }
                        ));
                    }
                }
            }
        }
    }

    // Validation 1: Route path parameters must have corresponding #[param] declarations
    for path_param in path_params {
        if !param_types.contains_key(path_param) {
            return Err(format!(
                "Route parameter '{}' in path '{}' is missing #[param] declaration. \
                Hint: Add #[param({}: type)] above the function.",
                path_param, route_path, path_param
            ));
        }
    }

    // Validation 2: #[param] declarations must correspond to route path parameters
    for param_name in param_types.keys() {
        if !path_params.contains(param_name) {
            return Err(format!(
                "Parameter '{}' has #[param] declaration but is not present in route path '{}'. \
                Hint: Add '{{{}}}' to the route path or remove the #[param({})] declaration.",
                param_name, route_path, param_name, param_name
            ));
        }
    }

    // Validation 3: Function parameters must match route and #[param] declarations
    for path_param in path_params {
        if !fn_params.contains_key(path_param) {
            return Err(format!(
                "Route parameter '{}' is declared but missing from function signature. \
                Hint: Add '{}: SomeType' to the function parameters.",
                path_param, path_param
            ));
        }
    }

    // Validation 4: If #[request] is specified but ElifRequest is already in signature, warn about redundancy
    if has_request_attr && has_request_param {
        return Err("Redundant #[request] attribute: function already has ElifRequest parameter. \
            Hint: Remove either the #[request] attribute or the ElifRequest parameter from the function signature.".to_string());
    }

    // Validation 5: Body parameter validation
    if let Some((body_param_name, _)) = body_param {
        if !fn_params.contains_key(body_param_name) {
            return Err(format!(
                "Body parameter '{}' specified in #[body] but missing from function signature. \
                Hint: Add '{}: SomeType' to the function parameters.",
                body_param_name, body_param_name
            ));
        }
        
        // Validation 5a: Body parameter cannot coexist with ElifRequest parameter
        if has_request_param {
            return Err(format!(
                "Conflicting parameter usage: #[body({})] cannot be used with ElifRequest parameter. \
                The body extraction wrapper handles the request automatically. \
                Hint: Remove the ElifRequest parameter from the function signature when using #[body].",
                body_param_name
            ));
        }
    }

    // Validation 6: Check for unexpected parameters
    for fn_param_name in fn_params.keys() {
        let is_path_param = path_params.contains(fn_param_name);
        let is_body_param = body_param
            .as_ref()
            .is_some_and(|(name, _)| name == fn_param_name);

        if !is_path_param && !is_body_param {
            return Err(format!(
                "Function parameter '{}' is not handled by any route parameter, #[body], or ElifRequest. \
                Hint: Add '{{{}}}' to the route path and #[param({}: type)], or annotate with #[body({}: Type)].",
                fn_param_name, fn_param_name, fn_param_name, fn_param_name
            ));
        }
    }

    Ok(())
}