Skip to main content

askama_derive/
filter_fn.rs

1//! askama::filter_fn - Proc macro implementation
2//! This parses an annotated freestanding function annotated with the `filter_fn` attribute
3//! into an internal intermediate representation (the `FilterSignature` struct).
4//! Then, the output code is generated from said struct.
5
6use std::ops::ControlFlow;
7
8use proc_macro2::{Ident, Span, TokenStream, TokenTree};
9use quote::{ToTokens, format_ident, quote, quote_spanned};
10use syn::punctuated::Punctuated;
11use syn::spanned::Spanned;
12use syn::token::Mut;
13use syn::{
14    Block, Expr, FnArg, GenericParam, ItemFn, Lifetime, Pat, PatType, ReturnType, Signature, Token,
15    Type, TypeParamBound, Visibility, WhereClause,
16};
17
18use crate::{CompileError, HashMap, HashSet, parse_ts_or_compile_error};
19
20pub fn derive_filter_fn(
21    attr: TokenStream,
22    item: TokenStream,
23    import_askama: fn() -> TokenStream,
24) -> TokenStream {
25    let ffn: ItemFn = match parse_ts_or_compile_error(item, import_askama) {
26        ControlFlow::Continue(ffn) => ffn,
27        ControlFlow::Break(err) => return err,
28    };
29    match filter_fn_impl(attr, &ffn) {
30        Ok(tt) => tt,
31        Err(CompileError { msg, span }) => {
32            let import_askama = import_askama();
33            quote_spanned! {
34                span.unwrap_or_else(|| ffn.sig.ident.span()) =>
35                const _: () = {
36                    #import_askama
37                    askama::helpers::core::compile_error!(#msg);
38                };
39            }
40        }
41    }
42}
43
44/// Helper macro to produce proc macro compiler error messages with a given span
45/// if a given condition is not met.
46macro_rules! p_assert {
47    ($cond:expr, $span:expr => $msg:literal $(,)?) => {
48        match $cond {
49            true => Ok(()),
50            false => p_err!($span => $msg)
51        }
52    };
53}
54
55macro_rules! p_err {
56    ($span:expr => $msg:literal $(,)?) => {
57        Err(CompileError::new_with_span_stable($msg, None, Some($span)))
58    };
59}
60
61// ##############################################################################################
62
63/// Internal representation for custom required filter arguments
64struct FilterArgumentRequired {
65    idx: usize,
66    ident: Ident,
67    mutability: Option<Mut>,
68    ty: Type,
69    generics: HashSet<Ident>,
70}
71
72/// Internal representation for custom optional filter arguments.
73/// These are arguments for which an optional value was supplied using `#[optional(...)]`
74struct FilterArgumentOptional {
75    idx: usize,
76    ident: Ident,
77    mutability: Option<Mut>,
78    ty: Type,
79    default: Expr,
80}
81
82/// Internal representation for a filter function's lifetime.
83#[derive(Clone)]
84struct FilterLifetime {
85    lifetime: Lifetime,
86    bounds: Punctuated<Lifetime, Token![+]>,
87    used_by_extra_args: bool,
88}
89
90/// Internal representation for a filter function's generic argument.
91#[derive(Clone)]
92struct FilterArgumentGeneric {
93    ident: Ident,
94    bounds: Punctuated<TypeParamBound, Token![+]>,
95}
96
97fn get_lifetimes(stream: TokenStream, lifetimes: &mut HashSet<Ident>) {
98    let mut iterator = stream.into_iter().peekable();
99    while let Some(token) = iterator.next() {
100        match token {
101            TokenTree::Group(g) => get_lifetimes(g.stream(), lifetimes),
102            TokenTree::Punct(p) if p.as_char() == '\'' => {
103                // Lifetimes are represented as `[Punct('), Ident("a")]` in the `TokenStream`.
104                if let Some(TokenTree::Ident(i)) = iterator.peek() {
105                    lifetimes.insert(i.clone());
106                }
107            }
108            TokenTree::Punct(_) | TokenTree::Ident(_) | TokenTree::Literal(_) => continue,
109        }
110    }
111}
112
113/// A freestanding method annotated with `askama::filter_fn` is parsed into an instance of this
114/// struct, and then the resulting code is generated from there.
115/// This struct serves as an intermediate representation after some preprocessing on the raw AST.
116struct FilterSignature {
117    /// Name of the annotated freestanding filter function
118    ident: Ident,
119    /// Lifetime bounds.
120    lifetimes: Vec<FilterLifetime>,
121    /// Name of the input variable
122    arg_input: FilterArgumentRequired,
123    /// Name of the askama environment variable
124    arg_env: FilterArgumentRequired,
125    /// Generic parameters required for the filter's input argument
126    arg_input_generics: Vec<FilterArgumentGeneric>,
127    /// Required filter arguments
128    args_required: Vec<FilterArgumentRequired>,
129    /// Optional filter arguments - each of which has a default value
130    args_optional: Vec<FilterArgumentOptional>,
131    /// Generic parameters in use by the required filter arguments
132    args_required_generics: HashMap<Ident, FilterArgumentGeneric>,
133    /// The `where` clause of the source function
134    where_clause: Option<WhereClause>,
135    /// Filter function result type
136    result_ty: ReturnType,
137}
138
139// ##############################################################################################
140// parsing
141// ##############################################################################################
142impl FilterSignature {
143    /// Parse the annotated function's signature and do some preprocessing to produce an instance
144    /// of the `FilterSignature` struct.
145    fn try_from_signature(sig: &Signature) -> Result<FilterSignature, CompileError> {
146        // preliminary validation
147        p_assert!(!sig.inputs.is_empty(), sig.paren_token.span.open() =>
148            "Filter function missing required input and environment arguments. Example: \
149            `fn filter0(_: &dyn std::fmt::Display, _: &dyn askama::Values) -> askama::Result<String>`"
150        )?;
151        p_assert!(sig.inputs.len() >= 2, sig.paren_token.span.open() =>
152            "Filter function missing required environment argument. Example: \
153            `fn filter0(_: &dyn std::fmt::Display, _: &dyn askama::Values) -> askama::Result<String>`"
154        )?;
155        if let Some(gc_arg) = sig.generics.const_params().next() {
156            p_err!(gc_arg.span() => "Const generics are currently not supported for filters")?;
157        }
158        p_assert!(
159            matches!(sig.output, ReturnType::Type(_, _)),
160            sig.paren_token.span.close() => "Filter function is missing return type"
161        )?;
162
163        // ########################################
164        // generics
165        let mut generics = HashMap::default();
166        for gp in sig.generics.type_params() {
167            if let Some((_, default)) = &gp.default {
168                p_err!(default.span() => "Filter functions don't support generic parameter defaults")?;
169            }
170
171            let ident = gp.ident.clone();
172            let bounds = gp.bounds.clone();
173            generics.insert(ident.clone(), FilterArgumentGeneric { ident, bounds });
174        }
175
176        // ########################################
177        // fixed arguments (input & env)
178        let arg_input = Self::try_get_fixed_arg(&sig.inputs[0], &generics)?;
179        let arg_input_generics: Vec<_> = arg_input
180            .generics
181            .iter()
182            .map(|i| generics[i].clone())
183            .collect();
184        let arg_env = Self::try_get_fixed_arg(&sig.inputs[1], &generics)?;
185
186        // ########################################
187        // user arguments
188        let mut args_required = vec![];
189        let mut args_optional = vec![];
190        let mut args_required_generics = HashMap::default();
191        let mut lifetimes_used_in_non_required = HashSet::default();
192        for (arg_idx, arg) in sig.inputs.iter().skip(2).enumerate() {
193            let FnArg::Typed(arg) = arg else {
194                continue;
195            };
196            let Pat::Ident(arg_pat) = &*arg.pat else {
197                p_err!(arg.pat.span() => "Only conventional function arguments are supported")?
198            };
199            p_assert!(
200                !matches!(*arg.ty, Type::ImplTrait(_)),
201                arg.ty.span() => "Impl generics are currently not supported for filters"
202            )?;
203            get_lifetimes(arg.to_token_stream(), &mut lifetimes_used_in_non_required);
204
205            // reference-parameters without explicit lifetime, inherit the 'filter lifetime
206            let arg_type = patch_ref_with_lifetime(&arg.ty, &format_ident!("filter"));
207
208            match Self::get_optional_arg_attr(arg)? {
209                // required argument (= has no default value)
210                None => {
211                    // required argument
212                    p_assert!(args_optional.is_empty(), arg.span() => "All required arguments must appear before any optional ones")?;
213                    // determine all generic parameters used by this argument
214                    let used_generics: HashSet<_> = generics
215                        .keys()
216                        .filter(|i| type_contains_ident(&arg.ty, i).is_some())
217                        .cloned()
218                        .collect();
219                    // mark the used generic parameters
220                    used_generics.iter().map(|i| &generics[i]).for_each(|g| {
221                        args_required_generics.insert(g.ident.clone(), g.clone());
222                    });
223                    args_required.push(FilterArgumentRequired {
224                        idx: arg_idx,
225                        ident: arg_pat.ident.clone(),
226                        mutability: arg_pat.mutability,
227                        ty: arg_type,
228                        generics: used_generics,
229                    });
230                }
231                // optional argument (= has default value)
232                Some(default) => {
233                    // check if the argument uses any generics (which is not allowed for optional arguments)
234                    if let Some(span) = generics
235                        .keys()
236                        .filter_map(|i| type_contains_ident(&arg.ty, i))
237                        .next()
238                    {
239                        p_err!(span => "Optional arguments must not use generic parameters")?;
240                    }
241
242                    args_optional.push(FilterArgumentOptional {
243                        idx: arg_idx,
244                        ident: arg_pat.ident.clone(),
245                        mutability: arg_pat.mutability,
246                        ty: arg_type,
247                        default,
248                    });
249                }
250            }
251        }
252        // lifetimes
253        let lifetimes = sig
254            .generics
255            .lifetimes()
256            .map(|lt| {
257                let lifetime = lt.lifetime.clone();
258                let bounds = lt.bounds.clone();
259                let used_by_extra_args = lifetimes_used_in_non_required.contains(&lifetime.ident);
260                FilterLifetime {
261                    lifetime,
262                    bounds,
263                    used_by_extra_args,
264                }
265            })
266            .collect::<Vec<_>>();
267
268        // ########################################
269
270        Ok(FilterSignature {
271            ident: sig.ident.clone(),
272            lifetimes,
273            arg_input,
274            arg_input_generics,
275            arg_env,
276            args_required,
277            args_optional,
278            args_required_generics,
279            where_clause: sig.generics.where_clause.clone(),
280            result_ty: sig.output.clone(),
281        })
282    }
283
284    /// Parse one of the fixed filter arguments (value and env)
285    fn try_get_fixed_arg(
286        arg: &FnArg,
287        generics: &HashMap<Ident, FilterArgumentGeneric>,
288    ) -> Result<FilterArgumentRequired, CompileError> {
289        let FnArg::Typed(arg) = arg else {
290            p_err!(arg.span() => "Illegal or unsupported type of argument for filter function")?
291        };
292        let (arg_ident, mutability) = match &*arg.pat {
293            Pat::Ident(pat_ident) => (pat_ident.ident.clone(), pat_ident.mutability),
294            Pat::Wild(pat) => (Ident::new("_", pat.span()), None), // little hack
295            _ => p_err!(arg.pat.span() => "Only conventional function arguments are supported")?,
296        };
297
298        Ok(FilterArgumentRequired {
299            idx: 0,
300            ident: arg_ident,
301            ty: *arg.ty.clone(),
302            mutability,
303            generics: generics
304                .keys()
305                .filter(|i| type_contains_ident(&arg.ty, i).is_some())
306                .cloned()
307                .collect(),
308        })
309    }
310
311    /// Parse the `#[optional(<default_expr>)]` attribute found on filter function arguments.
312    /// For optional arguments, this is mandatory.
313    fn get_optional_arg_attr(arg: &PatType) -> Result<Option<Expr>, CompileError> {
314        for attr in &arg.attrs {
315            if let Some(ident) = attr.meta.path().get_ident()
316                && ident == "optional"
317            {
318                let default: Expr = match attr.parse_args() {
319                    Ok(default) => default,
320                    Err(_) => p_err!(attr.span() => "Default argument not a valid expression")?,
321                };
322                return Ok(Some(default));
323            }
324        }
325        Ok(None)
326    }
327}
328
329// ##############################################################################################
330// code generation
331// ##############################################################################################
332impl FilterSignature {
333    /// Returns a tuple containing two items:
334    ///
335    /// 1. The list of lifetimes with their bounds.
336    /// 2. The list of lifetimes without their bounds.
337    fn lifetimes_bounds<F: Fn(&FilterLifetime) -> bool>(
338        &self,
339        filter: F,
340    ) -> (Vec<TokenStream>, Vec<&Lifetime>) {
341        let mut lifetimes = Vec::with_capacity(self.lifetimes.len());
342        let mut lifetimes_no_bounds = Vec::with_capacity(self.lifetimes.len());
343        for lt in &self.lifetimes {
344            if !filter(lt) {
345                continue;
346            }
347            let name = &lt.lifetime;
348            let bounds = &lt.bounds;
349            lifetimes.push(quote! { #name: #bounds });
350            lifetimes_no_bounds.push(name);
351        }
352        (lifetimes, lifetimes_no_bounds)
353    }
354
355    fn lifetimes_fillers<F: Fn(&FilterLifetime) -> bool>(&self, filter: F) -> Vec<TokenStream> {
356        self.lifetimes
357            .iter()
358            .filter(|l| filter(l))
359            .map(|_| quote! { '_ })
360            .collect()
361    }
362
363    /// Generates a struct named after the filter function.
364    /// This struct will contain all the filter's arguments (except input and env).
365    /// The struct is basically a builder pattern for the custom filter arguments.
366    /// It is structured like this:
367    /// - All required arguments (no default value supplied) are contained in an `Option`
368    /// - All optional arguments (default value supplied via attr) are contained as is
369    /// - The struct adopts all the generic parameters which are in use by custom args
370    /// - The struct always has a 'filter lifetime. This is the default lifetime relating
371    ///   to the struct instance itself. It is patched onto reference arguments without
372    ///   own explicit lifetime.
373    /// - The struct has one const generic bool parameter for each required argument, tracking
374    ///   whether the required argument was supplied.
375    ///
376    /// For every user argument to the filter, we implement the trait:
377    /// `askama::filters::ValidArgIdx<const IDX: usize>` on the generated struct (where IDX = arg.idx).
378    /// During code generation, the line: `const _: bool = askama::filters::ValidArgIdx<n>::VALID`
379    /// can then check at compile-time whether there is an argument with the given index.
380    fn gen_struct_definition(&self, vis: &Visibility) -> TokenStream {
381        let ident = &self.ident;
382        // struct generic parameters
383        let struct_generics = self
384            .args_required_generics
385            .values()
386            .map(|g| g.ident.clone());
387        let required_flags = self
388            .args_required
389            .iter()
390            .map(|a| format_ident!("REQUIRED_ARG_FLAG_{}", a.idx));
391        // struct field definitions
392        let required_fields = self.args_required.iter().map(|arg| {
393            let (name, ty) = (&arg.ident, &arg.ty);
394            quote! { #name: Option<#ty> }
395        });
396        let optional_fields = self.args_optional.iter().map(|arg| {
397            let (name, ty) = (&arg.ident, &arg.ty);
398            quote! { #name: #ty }
399        });
400        // introspection (better compile error messages on misuse)
401        let required_arg_cnt = self.args_required.len();
402        let optional_arg_cnt = self.args_optional.len();
403        let arg_cnt = required_arg_cnt + optional_arg_cnt;
404        let lifetimes_fillers = self.lifetimes_fillers(|l| l.used_by_extra_args);
405        let valid_arg_impls = (0..arg_cnt).map(|idx| {
406            quote! {
407                #[diagnostic::do_not_recommend]
408                impl askama::filters::ValidArgIdx<#idx> for #ident<'_, #(#lifetimes_fillers,)*> {}
409            }
410        });
411
412        let (_, lifetimes) = self.lifetimes_bounds(|l| l.used_by_extra_args);
413        quote! {
414            #[allow(non_camel_case_types)]
415            #vis struct #ident<'filter, #(#lifetimes,)* #(#struct_generics = (),)* #(const #required_flags : bool = false,)*> {
416                _lifetime: std::marker::PhantomData<&'filter ()>,
417                /* required fields */
418                #(#required_fields,)*
419                /* optional fields */
420                #(#optional_fields,)*
421            }
422
423            #(#valid_arg_impls)*
424        }
425    }
426
427    /// Generate the entry-point for the filter builder struct.
428    /// This fills all required arguments (`Option<Ty>`) as `None`, and all the optional
429    /// arguments with the default value supplied in the `#[optional(..)]` attribute.
430    ///
431    /// This entry point starts with a type of `()` for all the generic parameter
432    /// used by required arguments. They are only filled with the correct type
433    /// as soon as the argument is supplied into the corresponding setter.
434    fn gen_default_impl(&self) -> TokenStream {
435        let ident = &self.ident;
436        // initial field values
437        let required_defaults = self
438            .args_required
439            .iter()
440            .map(|a| &a.ident)
441            .map(|i| quote! { #i: None });
442        let optional_defaults = self.args_optional.iter().map(|a| {
443            let ident = &a.ident;
444            let value = &a.default;
445            quote! { #ident: #value }
446        });
447        let lifetimes_fillers = self.lifetimes_fillers(|l| l.used_by_extra_args);
448
449        quote! {
450            impl std::default::Default for #ident<'_, #(#lifetimes_fillers,)*> {
451                fn default() -> Self {
452                    Self {
453                        _lifetime: std::marker::PhantomData::default(),
454                        #(#required_defaults,)*
455                        #(#optional_defaults,)*
456                    }
457                }
458            }
459        }
460    }
461
462    /// Generate the builder-style setter methods. Each argument gets two methods.
463    /// - with_{arg_name}() for when an argument is passed as named arg
464    /// - with_{arg_idx}() for when an argument is passed as positional arg
465    ///
466    /// Positional setters are always implemented by calling their named counterparts.
467    ///
468    /// Since optional arguments don't support generic arguments and their presence
469    /// does not need to be checked, they simply change the field's value in the struct.
470    /// Whereas required arguments construct a new struct instance, because they need to
471    /// - Patch generic arguments (that started out with `()`)
472    /// - Change the const generic bool parameter that tracks their presence to `true`
473    fn gen_setters(&self) -> TokenStream {
474        let optional_setters = self.gen_setters_optional();
475        let required_setters = self
476            .args_required
477            .iter()
478            .map(|arg| self.gen_required_setter(arg));
479
480        quote! {
481            #optional_setters
482            #(#required_setters)*
483        }
484    }
485
486    /// This generates setters for required arguments - which is much more complex than
487    /// optional arguments. Each setter for a required argument:
488    /// - constructs a new instance of the builder struct.
489    /// - patches the required arguments' tracking const bool flag to `true`
490    /// - fills the required argument's corresponding generic type arguments
491    ///
492    /// So setters for required arguments do not just return a copy of the builder struct,
493    /// they also change its type signature (due to differing generic arguments).
494    fn gen_required_setter(&self, arg: &FilterArgumentRequired) -> TokenStream {
495        let ident = &self.ident;
496        let cur_arg_ident = &arg.ident;
497        let cur_arg_ty = &arg.ty;
498        // setter idents
499        let named_ident = format_ident!("with_{}", arg.ident);
500        let positional_ident = format_ident!("with_{}", arg.idx);
501        // impl generics
502        let required_generics_impl: Vec<_> = self
503            .args_required_generics
504            .keys()
505            .map(|i| format_ident!("{}__OLD", i))
506            .collect();
507        let required_flags: Vec<_> = self
508            .args_required
509            .iter()
510            .map(|a| format_ident!("REQUIRED_ARG_FLAG_{}", a.idx))
511            .collect();
512        // function generics
513        let required_generics_fn: Vec<_> = arg
514            .generics
515            .iter()
516            .map(|i| &self.args_required_generics[i])
517            .map(|g| {
518                let ident = &g.ident;
519                let bounds = &g.bounds;
520                quote! { #ident: #bounds }
521            })
522            .collect();
523        let (_, lifetimes_no_bounds) = self.lifetimes_bounds(|l| l.used_by_extra_args);
524        // return type
525        let fn_return_ty = {
526            let required_generics_result =
527                self.args_required_generics
528                    .keys()
529                    .map(|i| match arg.generics.contains(i) {
530                        true => i.clone(),
531                        false => format_ident!("{}__OLD", i),
532                    });
533            let required_flags_result = self.args_required.iter().map(|a| {
534                match a.idx == arg.idx {
535                    true => quote!(true), // current arg
536                    false => format_ident!("REQUIRED_ARG_FLAG_{}", a.idx).to_token_stream(),
537                }
538            });
539            quote! { #ident<'filter, #(#lifetimes_no_bounds,)* #(#required_generics_result,)* #(#required_flags_result,)*> }
540        };
541        // struct fields - (all fields, except that of current argument)
542        let other_required_fields = self
543            .args_required
544            .iter()
545            .filter(|a| a.idx != arg.idx)
546            .map(|a| &a.ident)
547            .map(|i| quote! { #i: self.#i });
548        let optional_fields = self.args_optional.iter().map(|a| &a.ident);
549
550        quote! {
551            #[allow(non_camel_case_types)]
552            impl<'filter, #(#lifetimes_no_bounds,)* #(#required_generics_impl,)* #(const #required_flags: bool,)*>
553            #ident<'filter, #(#lifetimes_no_bounds,)* #(#required_generics_impl,)* #(#required_flags,)*> {
554                // named setter
555                #[inline(always)]
556                pub fn #named_ident<#(#required_generics_fn,)*>(self, new_value: #cur_arg_ty) -> #fn_return_ty {
557                    // construct new instance of filter builder struct, by copying over all current values.
558                    // But replace the value of the setter's corresponding field with `Some(new_value)`.
559                    #ident {
560                        _lifetime: self._lifetime,
561                        // copy previous field values (all except field of current setter)
562                        #(#other_required_fields,)*
563                        #(#optional_fields: self.#optional_fields,)*
564                        // patch field of current argument to new value
565                        #cur_arg_ident: Some(new_value)
566                    }
567                }
568
569                // positional setter
570                #[inline(always)]
571                pub fn #positional_ident<#(#required_generics_fn,)*>(self, new_value: #cur_arg_ty) -> #fn_return_ty {
572                    self.#named_ident(new_value)
573                }
574            }
575        }
576    }
577
578    /// Generate setters for optional arguments
579    /// Compared to required arguments, they don't need to create a new struct instance,
580    /// because they don't need to change the struct's generic parameters.
581    /// Each getter just overwrites its corresponding field with the new value.
582    fn gen_setters_optional(&self) -> TokenStream {
583        let ident = &self.ident;
584        // generics (use stupid enumeration instead of named arguments for simplicity)
585        let required_generics: Vec<_> = (0..self.args_required_generics.len())
586            .map(|i| format_ident!("T{}", i))
587            .collect();
588        let required_flags: Vec<_> = (0..self.args_required.len())
589            .map(|i| format_ident!("F{}", i))
590            .collect();
591
592        let optional_setters = self.args_optional.iter().map(|arg| {
593            let arg_ident = &arg.ident;
594            let named_ident = format_ident!("with_{arg_ident}");
595            let positioned_ident = format_ident!("with_{}", arg.idx);
596            let arg_ty = &arg.ty;
597
598            quote! {
599                // named setter
600                #[inline(always)]
601                pub fn #named_ident(mut self, value: #arg_ty) -> Self {
602                    self.#arg_ident = value;
603                    self
604                }
605                // positional setter
606                #[inline(always)]
607                pub fn #positioned_ident(self, value: #arg_ty) -> Self {
608                    self.#named_ident(value)
609                }
610            }
611        });
612
613        let (_, lifetimes_no_bounds) = self.lifetimes_bounds(|l| l.used_by_extra_args);
614        quote! {
615            #[allow(non_camel_case_types)]
616            impl<'filter, #(#lifetimes_no_bounds,)* #(#required_generics,)* #(const #required_flags: bool,)*>
617            #ident<'filter, #(#lifetimes_no_bounds,)* #(#required_generics,)* #(#required_flags,)*> {
618                #(#optional_setters)*
619            }
620        }
621    }
622
623    /// Generate the `execute(input, env)` method that does the filter's actual work.
624    /// This method only takes the filter's input (before the pipe), as well as the askama values
625    /// environment variable as arguments.
626    /// The method is contained in an `impl{}` block that guards against missing required arguments
627    /// by requiring the value `true` for all argument-tracking const generic bool parameters.
628    ///
629    /// The method's body contains an internal "preamble" that first maps all of the struct's
630    /// fields into the local context by consuming them. Required arguments are unwrapped from
631    /// their `Option<>` container, and optional arguments are moved as is.
632    /// Then, the actual filter code is inserted after.
633    fn gen_exec_impl(&self, sig: &Signature, filter_impl: &Block) -> TokenStream {
634        let ident = &self.ident;
635        // input variable
636        // method generics (only the parameters not already present on struct)
637        let input_ident = &self.arg_input.ident;
638        let input_mutability = &self.arg_input.mutability;
639        let input_ty = &self.arg_input.ty;
640        let input_bounds = self
641            .arg_input_generics
642            .iter()
643            .filter(|g| !self.args_required_generics.contains_key(&g.ident))
644            .map(|g| {
645                let ident = &g.ident;
646                let bounds = &g.bounds;
647                quote! { #ident: #bounds }
648            });
649        let (all_lifetimes, _) = self.lifetimes_bounds(|_| true);
650        let (_, type_lifetimes) = self.lifetimes_bounds(|l| l.used_by_extra_args);
651
652        // env variable
653        let env_ident = &self.arg_env.ident;
654        let env_ty = &self.arg_env.ty;
655
656        // struct generics
657        let required_generics: Vec<_> = self
658            .args_required_generics
659            .values()
660            .map(|g| &g.ident)
661            .collect();
662        let required_generic_bounds = self.args_required_generics.values().map(|g| &g.bounds);
663        let required_flags = std::iter::repeat_n(quote!(true), self.args_required.len());
664
665        // filter result
666        let result_ty = &self.result_ty;
667
668        // variables
669        let required_args = self.args_required.iter().map(|a| {
670            let mutability = a.mutability;
671            let ident = &a.ident;
672            quote! {
673                let #mutability #ident = unsafe { self.#ident.unwrap_unchecked() };
674            }
675        });
676        let optional_args = self.args_optional.iter().map(|a| {
677            let mutability = a.mutability;
678            let ident = &a.ident;
679            quote! {
680                let #mutability #ident = unsafe { self.#ident };
681            }
682        });
683
684        let fn_token = &sig.fn_token;
685        let where_clause = self.where_clause.as_ref();
686        let impl_generics = quote! { #(#required_generics: #required_generic_bounds,)* };
687        let impl_struct_generics = quote! { #(#required_generics,)* #(#required_flags,)* };
688        let lifetimes_fillers = self.lifetimes_fillers(|l| l.used_by_extra_args);
689        quote_spanned! {
690            sig.paren_token.span =>
691            // if all required arguments have been supplied (P0 == true, P1 == true)
692            // ... the execute() method is "unlocked":
693            impl<#(#all_lifetimes,)* #impl_generics> #ident<'_, #(#type_lifetimes,)* #impl_struct_generics> {
694                #[inline(always)]
695                pub #fn_token execute< #(#input_bounds,)* >(
696                    self,
697                    #input_mutability #input_ident: #input_ty,
698                    #env_ident: #env_ty
699                ) #result_ty #where_clause {
700                    // map filter variables with original name into scope
701                    #( #required_args )*
702                    #( #optional_args )*
703                    // insert actual filter function implementation
704                    #filter_impl
705                }
706            }
707
708            impl<#impl_generics> askama::filters::ValidFilterInvocation for #ident<'_, #(#lifetimes_fillers,)* #impl_struct_generics> {}
709        }
710    }
711}
712
713// ######################################################
714
715fn filter_fn_impl(attr: TokenStream, ffn: &ItemFn) -> Result<TokenStream, CompileError> {
716    p_assert!(
717        attr.is_empty(),
718        attr.span() => "`#[askama::filter_fn]` does not expect any attributes"
719    )?;
720
721    let fsig = FilterSignature::try_from_signature(&ffn.sig)?;
722
723    for gp in &ffn.sig.generics.params {
724        match gp {
725            GenericParam::Type(_) | GenericParam::Lifetime(_) => {}
726            GenericParam::Const(_) => {
727                p_err!(gp.span() => "Const generic arguments are not supported for now")?;
728            }
729        }
730    }
731
732    let struct_def = fsig.gen_struct_definition(&ffn.vis);
733    let default_impl = fsig.gen_default_impl();
734    let setter_impl = fsig.gen_setters();
735    let exec_impl = fsig.gen_exec_impl(&ffn.sig, &ffn.block);
736
737    Ok(quote!(
738        #struct_def
739        #default_impl
740        #setter_impl
741        #exec_impl
742    ))
743}
744
745/// Recursively check if a type contains one of the given Idents
746fn type_contains_ident(ty: &Type, ident: &Ident) -> Option<Span> {
747    match ty {
748        Type::Path(type_path) => {
749            for segment in &type_path.path.segments {
750                // Check if the segment ident matches
751                if &segment.ident == ident {
752                    return Some(segment.ident.span());
753                }
754
755                // Check generic arguments recursively
756                if let syn::PathArguments::AngleBracketed(ref args) = segment.arguments {
757                    for arg in &args.args {
758                        match arg {
759                            syn::GenericArgument::Type(inner_ty) => {
760                                if let Some(span) = type_contains_ident(inner_ty, ident) {
761                                    return Some(span);
762                                }
763                            }
764                            syn::GenericArgument::AssocType(assoc) => {
765                                if let Some(span) = type_contains_ident(&assoc.ty, ident) {
766                                    return Some(span);
767                                }
768                            }
769                            _ => {} // Not types -> skip
770                        }
771                    }
772                }
773            }
774            None
775        }
776        Type::Reference(type_ref) => type_contains_ident(&type_ref.elem, ident),
777        Type::Slice(type_slice) => type_contains_ident(&type_slice.elem, ident),
778        Type::Array(type_array) => type_contains_ident(&type_array.elem, ident),
779        Type::Tuple(type_tuple) => type_tuple
780            .elems
781            .iter()
782            .filter_map(|elem_ty| type_contains_ident(elem_ty, ident))
783            .next(),
784        Type::Paren(type_paren) => type_contains_ident(&type_paren.elem, ident),
785        Type::Group(type_group) => type_contains_ident(&type_group.elem, ident),
786        _ => None, // covers everything else
787    }
788}
789
790fn patch_ref_with_lifetime(ty: &Type, lifetime: &Ident) -> Type {
791    match ty {
792        Type::Reference(type_ref) => {
793            let mut new_type_ref = type_ref.clone();
794
795            // Inject the lifetime if it's missing
796            if new_type_ref.lifetime.is_none() {
797                new_type_ref.lifetime = Some(Lifetime {
798                    apostrophe: Span::call_site(),
799                    ident: lifetime.clone(),
800                });
801            }
802
803            Type::Reference(new_type_ref)
804        }
805        _ => ty.clone(), // Only patch reference types; others remain unchanged
806    }
807}