Skip to main content

livewire_rust_macros/
lib.rs

1//! The derives that make a Rust struct a Livewire component.
2//!
3//! [`LivewireComponent`](macro@LivewireComponent) writes the wire-public state: what crosses the
4//! wire, in which order, and which fields the browser may not touch. [`component`](macro@component)
5//! writes the lifecycle forwarding and the action dispatch, so an inherent method is reachable from
6//! the browser only when it appears in the annotated implementation.
7
8use proc_macro::TokenStream;
9use proc_macro2::TokenStream as TokenStream2;
10use quote::{ToTokens, format_ident, quote};
11use syn::parse::{Parse, ParseStream};
12use syn::punctuated::Punctuated;
13use syn::{
14    Attribute, FnArg, Ident, ImplItem, ItemImpl, ItemStruct, LitStr, Path, ReturnType, Token, Type, parse_macro_input,
15};
16
17/// Makes a struct a Livewire component's state: its wire-public fields, their rules, and the view it
18/// renders by default.
19///
20/// ```ignore
21/// #[derive(Default, LivewireComponent)]
22/// #[livewire(view = "livewire.counter")]
23/// struct Counter {
24///     count: i32,
25///     #[livewire(locked)]
26///     id: String,
27///     #[livewire(skip)]
28///     cache: Vec<String>,
29/// }
30/// ```
31///
32/// The struct must implement `Default`, because a later request rebuilds it from its snapshot and
33/// then reads the fields the snapshot holds.
34///
35/// Field attributes:
36///
37/// | Attribute | Meaning |
38/// | --- | --- |
39/// | `skip` | Never crosses the wire; keeps its default |
40/// | `locked` | Crosses the wire, but the browser may not change it |
41/// | `modelable` | A parent may bind it with `wire:model` |
42/// | `reactive` | A parent's change resets the component |
43/// | `synth(path::to::Synth)` | A synthesizer reads and writes it |
44/// | `form` | A struct of wire-public fields crosses the wire as one object |
45/// | `url` / `url(as = "q", use = "replace", always_show = true, except = "a")` | Follows the query string |
46/// | `session` / `session(key = "component-key")` | Persists in the session |
47/// | `validate(required, max_length(255))` | Validation rules |
48#[proc_macro_derive(LivewireComponent, attributes(livewire))]
49pub fn livewire_component(input: TokenStream) -> TokenStream {
50    let item = parse_macro_input!(input as ItemStruct);
51
52    match derive_state(&item) {
53        Ok(tokens) => tokens.into(),
54        Err(error) => error.to_compile_error().into(),
55    }
56}
57
58/// Publishes an implementation's lifecycle hooks and actions to the browser.
59///
60/// ```ignore
61/// #[component]
62/// impl Counter {
63///     fn mount(&mut self, count: Option<i32>) {
64///         self.count = count.unwrap_or(0);
65///     }
66///
67///     fn increment(&mut self, by: i32) {
68///         self.count += by;
69///     }
70/// }
71/// ```
72///
73/// Class options go on the attribute: `layout = "…"`, `title = "…"`, `transition = "…"`, `lazy`,
74/// `defer`, and `isolate`. Method options go on the method:
75///
76/// | Method attribute | Meaning |
77/// | --- | --- |
78/// | `on = "event"` | The method listens for the event |
79/// | `renderless` | The method's response carries no HTML |
80/// | `json` | The method answers with JSON |
81/// | `async` | The browser sends the call ahead of the others |
82/// | `authorize(path::to::policy)` | The policy decides whether the call may run |
83#[proc_macro_attribute]
84pub fn component(attribute: TokenStream, item: TokenStream) -> TokenStream {
85    let options = parse_macro_input!(attribute with ClassOptions::parse);
86    let item = parse_macro_input!(item as ItemImpl);
87
88    match generate_component(&item, &options) {
89        Ok(tokens) => tokens.into(),
90        Err(error) => error.to_compile_error().into(),
91    }
92}
93
94/// One field's `#[livewire(..)]` options.
95#[derive(Default)]
96struct FieldOptions {
97    skip: bool,
98    locked: bool,
99    modelable: bool,
100    reactive: bool,
101    model: bool,
102    synth: Option<syn::Type>,
103    form: bool,
104    url: Option<UrlOptions>,
105    session: Option<SessionOptions>,
106    rules: Vec<String>,
107}
108
109#[derive(Default)]
110struct UrlOptions {
111    as_name: Option<String>,
112    push: bool,
113    always_show: bool,
114    except: Option<String>,
115}
116
117#[derive(Default)]
118struct SessionOptions {
119    key: Option<String>,
120}
121
122impl FieldOptions {
123    fn parse(attribute: &Attribute) -> syn::Result<Self> {
124        let mut options = Self::default();
125
126        attribute.parse_nested_meta(|meta| {
127            if meta.path.is_ident("skip") {
128                options.skip = true;
129                return Ok(());
130            }
131            if meta.path.is_ident("locked") {
132                options.locked = true;
133                return Ok(());
134            }
135            if meta.path.is_ident("modelable") {
136                options.modelable = true;
137                return Ok(());
138            }
139            if meta.path.is_ident("reactive") {
140                options.reactive = true;
141                return Ok(());
142            }
143            if meta.path.is_ident("synth") {
144                let content;
145                syn::parenthesized!(content in meta.input);
146                options.synth = Some(content.parse::<syn::Type>()?);
147                return Ok(());
148            }
149            if meta.path.is_ident("model") {
150                options.model = true;
151                return Ok(());
152            }
153            if meta.path.is_ident("form") {
154                options.form = true;
155                return Ok(());
156            }
157            if meta.path.is_ident("url") {
158                options.url = Some(if meta.input.peek(syn::token::Paren) {
159                    let content;
160                    syn::parenthesized!(content in meta.input);
161                    parse_url_options(&content)?
162                } else {
163                    UrlOptions::default()
164                });
165                return Ok(());
166            }
167            if meta.path.is_ident("session") {
168                options.session = Some(if meta.input.peek(syn::token::Paren) {
169                    let content;
170                    syn::parenthesized!(content in meta.input);
171                    parse_session_options(&content)?
172                } else {
173                    SessionOptions::default()
174                });
175                return Ok(());
176            }
177            if meta.path.is_ident("validate") {
178                let content;
179                syn::parenthesized!(content in meta.input);
180                options.rules = parse_rules(&content)?;
181                return Ok(());
182            }
183
184            Err(meta.error(
185                "unknown `#[livewire(..)]` field option: expected skip, locked, modelable, reactive, \
186                 synth(..), url(..), session(..), or validate(..)",
187            ))
188        })?;
189
190        if options.model && (options.synth.is_some() || options.session.is_some() || options.skip) {
191            return Err(syn::Error::new_spanned(
192                attribute,
193                "`model` cannot be combined with `synth`, `session`, or `skip`: the reference is its \
194                 own wire form",
195            ));
196        }
197
198        if options.form && (options.synth.is_some() || options.session.is_some() || options.locked || options.skip) {
199            return Err(syn::Error::new_spanned(
200                attribute,
201                "`form` cannot be combined with `synth`, `session`, `locked`, or `skip`: a form object \
202                 carries its own fields",
203            ));
204        }
205
206        if options.skip && (options.locked || options.modelable || options.reactive || options.synth.is_some()) {
207            return Err(syn::Error::new_spanned(
208                attribute,
209                "`skip` cannot be combined with `locked`, `modelable`, `reactive`, or `synth`: a \
210                 skipped field never crosses the wire",
211            ));
212        }
213
214        Ok(options)
215    }
216}
217
218/// Parses `as = "q", use = "replace", always_show = true, except = "…"`.
219///
220/// `as` and `use` are Rust keywords, so the group is read as token trees instead of through syn's
221/// structured parsing, which refuses a keyword where it expects an identifier.
222fn parse_url_options(content: ParseStream<'_>) -> syn::Result<UrlOptions> {
223    let mut options = UrlOptions::default();
224    let entries = entries(content)?;
225    let mut index = 0;
226
227    while index < entries.len() {
228        let key = entries[index].clone();
229        let Some(value) = entries.get(index + 2).cloned() else {
230            return Err(syn::Error::new(key.span(), "each `url(..)` option needs `key = value`"));
231        };
232        index += 3;
233
234        match key.to_string().as_str() {
235            "as" => options.as_name = Some(string(&value)?),
236            "use" => match string(&value)?.as_str() {
237                "push" => options.push = true,
238                "replace" => options.push = false,
239                other => {
240                    return Err(syn::Error::new(
241                        value.span(),
242                        format!("`url(use = ..)` accepts `push` or `replace`, not `{other}`"),
243                    ));
244                }
245            },
246            "always_show" => {
247                let always = match value.to_string().as_str() {
248                    "true" => true,
249                    "false" => false,
250                    other => {
251                        return Err(syn::Error::new(
252                            value.span(),
253                            format!("`url(always_show = ..)` accepts `true` or `false`, not `{other}`"),
254                        ));
255                    }
256                };
257                options.always_show = always;
258            }
259            "except" => options.except = Some(string(&value)?),
260            other => {
261                return Err(syn::Error::new(
262                    key.span(),
263                    format!("unknown `url(..)` option `{other}`: expected as, use, always_show, or except"),
264                ));
265            }
266        }
267    }
268
269    Ok(options)
270}
271
272/// Parses `key = "component-key"`, whose keys and values are ordinary identifiers.
273fn parse_session_options(content: ParseStream<'_>) -> syn::Result<SessionOptions> {
274    let mut options = SessionOptions::default();
275    let entries = entries(content)?;
276    let mut index = 0;
277
278    while index < entries.len() {
279        let key = entries[index].clone();
280        let Some(value) = entries.get(index + 2).cloned() else {
281            return Err(syn::Error::new(
282                key.span(),
283                "each `session(..)` option needs `key = value`",
284            ));
285        };
286        index += 3;
287
288        match key.to_string().as_str() {
289            "key" => options.key = Some(string(&value)?),
290            other => {
291                return Err(syn::Error::new(
292                    key.span(),
293                    format!("unknown `session(..)` option `{other}`: expected key"),
294                ));
295            }
296        }
297    }
298
299    Ok(options)
300}
301
302/// The `key`, `=` and `value` tokens of an options group, in order.
303fn entries(content: ParseStream<'_>) -> syn::Result<Vec<proc_macro2::TokenTree>> {
304    let tokens: proc_macro2::TokenStream = content.parse()?;
305
306    Ok(tokens
307        .into_iter()
308        .filter(|token| !matches!(token, proc_macro2::TokenTree::Punct(punct) if punct.as_char() == ','))
309        .collect())
310}
311
312/// A token that must be a string literal.
313fn string(token: &proc_macro2::TokenTree) -> syn::Result<String> {
314    match token {
315        proc_macro2::TokenTree::Literal(literal) => {
316            syn::parse_str::<LitStr>(&literal.to_string()).map(|literal| literal.value())
317        }
318        other => Err(syn::Error::new(other.span(), "expected a string literal")),
319    }
320}
321
322/// Parses validation rules such as `required, max_length(255)` into the framework's rule syntax.
323/// One declared rule as the constructor call the generated `validation_rules` builds.
324fn rule_constructor(rule: &str) -> syn::Result<TokenStream2> {
325    let (name, argument) = match rule.split_once('(') {
326        Some((name, rest)) => (name, Some(rest.trim_end_matches(')'))),
327        None => (rule, None),
328    };
329
330    let path = match (name, argument) {
331        ("required", None) => quote!(::livewire::__private::Rule::required()),
332        ("string", None) => quote!(::livewire::__private::Rule::string()),
333        ("min_length", Some(length)) => {
334            let length: usize = length.parse().map_err(|_| {
335                syn::Error::new(
336                    proc_macro2::Span::call_site(),
337                    "`min_length` takes a number: write `validate(min_length(3))`",
338                )
339            })?;
340            quote!(::livewire::__private::Rule::min_length(#length))
341        }
342        ("max_length", Some(length)) => {
343            let length: usize = length.parse().map_err(|_| {
344                syn::Error::new(
345                    proc_macro2::Span::call_site(),
346                    "`max_length` takes a number: write `validate(max_length(255))`",
347                )
348            })?;
349            quote!(::livewire::__private::Rule::max_length(#length))
350        }
351        _ => {
352            return Err(syn::Error::new(
353                proc_macro2::Span::call_site(),
354                "unsupported validation rule: this port generates `required`, `string`, \
355                 `min_length(n)`, and `max_length(n)`",
356            ));
357        }
358    };
359
360    Ok(path)
361}
362
363/// The synthesizer a field's value goes through: the path it names, or the reference its `model`
364/// type declares.
365fn synth_type(ty: &syn::Type, options: &FieldOptions) -> syn::Result<Option<TokenStream2>> {
366    if let Some(synth) = &options.synth {
367        return Ok(Some(quote!(#synth)));
368    }
369
370    if !options.model {
371        return Ok(None);
372    }
373
374    let model = model_type(ty)?;
375
376    Ok(Some(quote!(::livewire::models::ModelRef<#model>)))
377}
378
379/// The model type inside `ModelRef<T>`, which a `model` field must declare.
380fn model_type(ty: &syn::Type) -> syn::Result<syn::Type> {
381    let wrong = || {
382        syn::Error::new_spanned(
383            ty,
384            "a `model` field is declared as `ModelRef<Model>`, as in `pub post: ModelRef<Post>`",
385        )
386    };
387
388    let syn::Type::Path(path) = ty else {
389        return Err(wrong());
390    };
391
392    let segment = path.path.segments.last().ok_or_else(wrong)?;
393
394    if segment.ident != "ModelRef" {
395        return Err(wrong());
396    }
397
398    let syn::PathArguments::AngleBracketed(arguments) = &segment.arguments else {
399        return Err(wrong());
400    };
401
402    arguments
403        .args
404        .iter()
405        .find_map(|argument| match argument {
406            syn::GenericArgument::Type(ty) => Some(ty.clone()),
407            _ => None,
408        })
409        .ok_or_else(wrong)
410}
411
412fn parse_rules(content: ParseStream<'_>) -> syn::Result<Vec<String>> {
413    let mut rules = Vec::new();
414
415    for rule in Punctuated::<syn::Meta, Token![,]>::parse_terminated(content)? {
416        match rule {
417            syn::Meta::Path(path) => rules.push(path.to_token_stream().to_string().replace(' ', "")),
418            syn::Meta::List(list) => {
419                let name = list.path.to_token_stream().to_string().replace(' ', "");
420                let arguments = list.tokens.to_string().replace(' ', "");
421                rules.push(format!("{name}({arguments})"));
422            }
423            syn::Meta::NameValue(value) => {
424                return Err(syn::Error::new_spanned(
425                    value,
426                    "a validation rule takes no `=` value: write `validate(max_length(255))`",
427                ));
428            }
429        }
430    }
431
432    Ok(rules)
433}
434
435/// Turns `PostEditor` into `post-editor`, so a type's default view matches its component name.
436fn kebab_case(ident: &Ident) -> String {
437    let name = ident.to_string();
438    let mut out = String::with_capacity(name.len() + 4);
439
440    for (index, character) in name.char_indices() {
441        if character.is_uppercase() {
442            if index > 0 {
443                out.push('-');
444            }
445            out.extend(character.to_lowercase());
446        } else {
447            out.push(character);
448        }
449    }
450
451    out
452}
453
454fn derive_state(item: &ItemStruct) -> syn::Result<TokenStream2> {
455    let name = &item.ident;
456
457    if !item.generics.params.is_empty() {
458        return Err(syn::Error::new_spanned(
459            &item.generics,
460            "a Livewire component cannot be generic: its fields cross the wire by name",
461        ));
462    }
463    if !matches!(item.fields, syn::Fields::Named(_)) {
464        return Err(syn::Error::new_spanned(
465            item,
466            "a Livewire component needs named fields: its fields cross the wire by name",
467        ));
468    }
469
470    let mut view: Option<String> = None;
471    let mut inline: Option<String> = None;
472
473    for attribute in &item.attrs {
474        if !attribute.path().is_ident("livewire") {
475            continue;
476        }
477
478        attribute.parse_nested_meta(|meta| {
479            if meta.path.is_ident("view") {
480                view = Some(meta.value()?.parse::<LitStr>()?.value());
481                Ok(())
482            } else if meta.path.is_ident("inline") {
483                inline = Some(meta.value()?.parse::<LitStr>()?.value());
484                Ok(())
485            } else {
486                Err(meta.error("unknown `#[livewire(..)]` struct option: expected view = \"…\" or inline = \"…\""))
487            }
488        })?;
489    }
490
491    if view.is_some() && inline.is_some() {
492        return Err(syn::Error::new_spanned(
493            item,
494            "`view` and `inline` select different templates: use one of them",
495        ));
496    }
497
498    let mut fields = Vec::new();
499    for field in &item.fields {
500        let Some(ident) = field.ident.as_ref() else {
501            continue;
502        };
503
504        let mut options = FieldOptions::default();
505        for attribute in &field.attrs {
506            if attribute.path().is_ident("livewire") {
507                options = FieldOptions::parse(attribute)?;
508            }
509        }
510
511        fields.push((ident.clone(), field.ty.clone(), options));
512    }
513
514    let synth_by_name: std::collections::BTreeMap<String, TokenStream2> = fields
515        .iter()
516        .filter_map(|(ident, ty, options)| {
517            synth_type(ty, options)
518                .transpose()
519                .map(|synth| synth.map(|synth| (ident.to_string(), synth)))
520        })
521        .collect::<syn::Result<_>>()?;
522
523    let model_blocks = fields
524        .iter()
525        .filter(|(_, _, options)| options.model)
526        .map(|(ident, ty, _)| {
527            let model = model_type(ty)?;
528
529            Ok(quote! {
530                if let ::core::option::Option::Some(key) = self.#ident.unresolved().cloned() {
531                    let found = <#model>::query().find(key).await.map_err(|error| {
532                        ::livewire::error::LivewireError::Database { message: error.to_string() }
533                    })?;
534                    self.#ident.found(found)?;
535                }
536            })
537        })
538        .collect::<syn::Result<Vec<_>>>()?;
539
540    let render_models = fields
541        .iter()
542        .filter(|(_, _, options)| options.model)
543        .map(|(ident, _, _)| {
544            let name = ident.to_string();
545
546            quote! {
547                if let ::core::option::Option::Some(row) = self.#ident.get()
548                    && let ::core::result::Result::Ok(value) = ::livewire::__private::serde_json::to_value(row)
549                {
550                    data.insert(::std::string::String::from(#name), value);
551                }
552            }
553        })
554        .collect::<Vec<_>>();
555
556    let wire_fields = fields
557        .iter()
558        .filter(|(_, _, options)| !options.skip)
559        .map(|(ident, ty, options)| {
560            let field_name = ident.to_string();
561            let locked = options.locked;
562            let modelable = options.modelable;
563            let reactive = options.reactive;
564
565            let url = match &options.url {
566                None => quote!(::core::option::Option::None),
567                Some(url) => {
568                    let as_name = match &url.as_name {
569                        None => quote!(::core::option::Option::None),
570                        Some(name) => quote!(::core::option::Option::Some(#name)),
571                    };
572                    let push = url.push;
573                    let always_show = url.always_show;
574                    let except = url.except.clone().unwrap_or_default();
575                    quote!(::core::option::Option::Some(::livewire::component::UrlBinding {
576                        as_name: #as_name,
577                        push: #push,
578                        always_show: #always_show,
579                        except: #except,
580                    }))
581                }
582            };
583
584            let session = match &options.session {
585                None => quote!(::core::option::Option::None),
586                Some(session) => {
587                    let key = match &session.key {
588                        None => quote!(::core::option::Option::None),
589                        Some(key) => quote!(::core::option::Option::Some(#key)),
590                    };
591                    quote!(::core::option::Option::Some(::livewire::component::SessionBinding { key: #key }))
592                }
593            };
594
595            let synth = match synth_by_name.get(&field_name) {
596                None => quote!(::core::option::Option::None),
597                Some(path) => quote!(::core::option::Option::Some(<#path as ::livewire::synthesizers::Synth>::KEY)),
598            };
599
600            let rules = &options.rules;
601            let type_name = quote!(#ty).to_string().replace(' ', "");
602
603            quote! {
604                ::livewire::component::WireField {
605                    name: #field_name,
606                    locked: #locked,
607                    modelable: #modelable,
608                    reactive: #reactive,
609                    url: #url,
610                    session: #session,
611                    synth: #synth,
612                    rules: &[#(#rules),*],
613                    type_name: #type_name,
614                }
615            }
616        });
617
618    let dehydrate = fields
619        .iter()
620        .filter(|(_, _, options)| !options.skip)
621        .map(|(ident, ty, options)| {
622            let field_name = ident.to_string();
623
624            if let Some(path) = synth_by_name.get(&field_name) {
625                return quote! {
626                    if let ::core::option::Option::Some((value, meta)) =
627                        <#path as ::livewire::synthesizers::Synth>::dehydrate(&self.#ident)
628                    {
629                        data.insert(::std::string::String::from(#field_name), value);
630                        synth_meta.insert(::std::string::String::from(#field_name), ::livewire::__private::serde_json::Value::Object(meta));
631                    }
632                };
633            }
634
635            if options.form {
636                // A form object crosses the wire as a plain object of its own fields, as
637                // `FormObjectSynth` writes it; there is no `s:` envelope and no reference, because
638                // the form is a value the component owns.
639                return quote! {
640                    {
641                        let mut fields = ::livewire::__private::serde_json::Map::new();
642                        <#ty as ::livewire::component::LivewireState>::dehydrate_fields(&self.#ident, &mut fields);
643                        data.insert(
644                            ::std::string::String::from(#field_name),
645                            ::livewire::__private::serde_json::Value::Object(fields),
646                        );
647                    }
648                };
649            }
650
651            if let Some(session) = &options.session {
652                let key = match &session.key {
653                    None => quote!(::core::option::Option::None),
654                    Some(key) => quote!(::core::option::Option::Some(#key)),
655                };
656                // The value still reaches the template, which renders it; the snapshot builder drops
657                // it again so that it does not also cross the wire.
658                return quote! {
659                    {
660                        let session_key = ::livewire::session::property_key(
661                            <Self as ::livewire::component::LivewireState>::component_name(),
662                            #field_name,
663                            #key,
664                            |path| ::livewire::component::lookup_scalar(data, path),
665                        );
666                        let value = ::livewire::component::to_wire(&self.#ident);
667                        ::livewire::session::put(&session_key, &value);
668                        data.insert(::std::string::String::from(#field_name), value);
669                    }
670                };
671            }
672
673            quote! {
674                data.insert(
675                    ::std::string::String::from(#field_name),
676                    ::livewire::component::to_wire(&self.#ident),
677                );
678            }
679        });
680
681    let hydrate = fields
682        .iter()
683        .filter(|(_, _, options)| !options.skip)
684        .map(|(ident, ty, options)| {
685            let field_name = ident.to_string();
686
687            if let Some(path) = synth_by_name.get(&field_name) {
688                return quote! {
689                    if let ::core::option::Option::Some(value) = data.get(#field_name) {
690                        self.#ident = <#path as ::livewire::synthesizers::Synth>::hydrate(
691                            value,
692                            meta.and_then(|meta| meta.get(#field_name)).and_then(|meta| meta.as_object()),
693                        )
694                        .map_err(|error| ::livewire::error::LivewireError::HydrationFailed {
695                            property: ::std::string::String::from(#field_name),
696                            component: ::std::string::String::from(
697                                <Self as ::livewire::component::LivewireState>::component_name(),
698                            ),
699                            message: error.to_string(),
700                        })?;
701                    }
702                };
703            }
704
705            if options.form {
706                // Only the fields present are read, so a consolidated update that carries one path
707                // of the form leaves its siblings alone.
708                return quote! {
709                    if let ::core::option::Option::Some(::livewire::__private::serde_json::Value::Object(fields)) =
710                        data.get(#field_name)
711                    {
712                        <#ty as ::livewire::component::LivewireState>::hydrate_fields(&mut self.#ident, fields)?;
713                    }
714                };
715            }
716
717            if let Some(session) = &options.session {
718                let key = match &session.key {
719                    None => quote!(::core::option::Option::None),
720                    Some(key) => quote!(::core::option::Option::Some(#key)),
721                };
722                return quote! {
723                    {
724                        let session_key = ::livewire::session::property_key(
725                            <Self as ::livewire::component::LivewireState>::component_name(),
726                            #field_name,
727                            #key,
728                            |path| ::livewire::component::lookup_scalar(data, path),
729                        );
730                        if let ::core::option::Option::Some(value) = data
731                            .get(#field_name)
732                            .cloned()
733                            .or_else(|| ::livewire::session::get(&session_key))
734                        {
735                            match ::livewire::__private::serde_json::from_value::<#ty>(value) {
736                                ::core::result::Result::Ok(value) => self.#ident = value,
737                                ::core::result::Result::Err(_) => {
738                                    ::livewire::session::forget(&session_key);
739                                }
740                            }
741                        }
742                    }
743                };
744            }
745
746            quote! {
747                if let ::core::option::Option::Some(value) = data.get(#field_name) {
748                    self.#ident = ::livewire::component::coerce::<#ty>(&value).map_err(|error| {
749                        ::livewire::error::LivewireError::HydrationFailed {
750                            property: ::std::string::String::from(#field_name),
751                            component: ::std::string::String::from(
752                                <Self as ::livewire::component::LivewireState>::component_name(),
753                            ),
754                            message: error.to_string(),
755                        }
756                    })?;
757                }
758            }
759        });
760
761    let setters = fields
762        .iter()
763        .filter(|(_, _, options)| !options.skip)
764        .map(|(ident, ty, options)| {
765            let field_name = ident.to_string();
766
767            if options.locked {
768                return quote! {
769                    #field_name => {
770                        return ::core::result::Result::Err(::livewire::error::LivewireError::LockedProperty {
771                            property: ::std::string::String::from(#field_name),
772                            component: ::std::string::String::from(
773                                <Self as ::livewire::component::LivewireState>::component_name(),
774                            ),
775                        });
776                    }
777                };
778            }
779
780            if options.form {
781                return quote! {
782                    #field_name => {
783                        if let ::livewire::__private::serde_json::Value::Object(fields) = value {
784                            <#ty as ::livewire::component::LivewireState>::hydrate_fields(&mut self.#ident, &fields)?;
785                        } else {
786                            return ::core::result::Result::Err(::livewire::error::LivewireError::HydrationFailed {
787                                property: ::std::string::String::from(#field_name),
788                                component: ::std::string::String::from(
789                                    <Self as ::livewire::component::LivewireState>::component_name(),
790                                ),
791                                message: ::std::string::String::from("a form object is an object of its fields"),
792                            });
793                        }
794                    }
795                };
796            }
797
798            if let Some(path) = synth_by_name.get(&field_name) {
799                return quote! {
800                    #field_name => {
801                        self.#ident = <#path as ::livewire::synthesizers::Synth>::hydrate(&value, ::core::option::Option::None)
802                            .map_err(|error| ::livewire::error::LivewireError::HydrationFailed {
803                                property: ::std::string::String::from(#field_name),
804                                component: ::std::string::String::from(
805                                    <Self as ::livewire::component::LivewireState>::component_name(),
806                                ),
807                                message: error.to_string(),
808                            })?;
809                    }
810                };
811            }
812
813            quote! {
814                #field_name => {
815                    self.#ident = ::livewire::component::coerce::<#ty>(&value).map_err(|error| {
816                        ::livewire::error::LivewireError::HydrationFailed {
817                            property: ::std::string::String::from(#field_name),
818                            component: ::std::string::String::from(
819                                <Self as ::livewire::component::LivewireState>::component_name(),
820                            ),
821                            message: error.to_string(),
822                        }
823                    })?;
824                }
825            }
826        });
827
828    let validation_rules = fields
829        .iter()
830        .filter(|(_, _, options)| !options.rules.is_empty())
831        .map(|(ident, _, options)| {
832            let name = ident.to_string();
833            let constructors = options
834                .rules
835                .iter()
836                .map(|rule| rule_constructor(rule))
837                .collect::<syn::Result<Vec<_>>>()?;
838
839            Ok(quote! {
840                rules = rules.field(#name, [#(#constructors),*]);
841            })
842        })
843        .collect::<syn::Result<Vec<_>>>()?;
844
845    let default_view = match (view.as_deref(), inline.as_deref()) {
846        (Some(view), _) => quote!(::livewire::component::ComponentView::Named(::std::string::String::from(#view))),
847        (_, Some(inline)) => quote! {
848            ::livewire::component::ComponentView::Inline {
849                source: #inline,
850                data: {
851                    let mut data = ::livewire::__private::serde_json::Map::new();
852                    <Self as ::livewire::component::LivewireState>::dehydrate_fields(self, &mut data);
853                    data
854                },
855            }
856        },
857        _ => {
858            let view = format!("livewire.{}", kebab_case(name));
859            quote!(::livewire::component::ComponentView::Named(::std::string::String::from(#view)))
860        }
861    };
862
863    let component_name = kebab_case(name);
864
865    Ok(quote! {
866        // Generated bodies carry branches the field list makes dead, such as the empty
867        // dehydration of a component whose fields are all skipped; they are not the user's code.
868        #[allow(unreachable_code, unused_variables, unused_mut)]
869        impl #name {
870            /// Fetches the model references this component holds, which the update pipeline calls
871            /// before the hooks, the actions, and the render.
872            pub(crate) async fn resolve_model_refs(&mut self) -> ::livewire::component::Result<()> {
873                #(#model_blocks)*
874
875                ::core::result::Result::Ok(())
876            }
877        }
878
879        #[allow(unreachable_code, unused_variables, unused_mut)]
880        impl ::livewire::component::LivewireState for #name {
881            fn wire_fields() -> &'static [::livewire::component::WireField] {
882                &[#(#wire_fields),*]
883            }
884
885            fn component_name() -> &'static str {
886                #component_name
887            }
888
889            fn dehydrate_fields(&self, data: &mut ::livewire::__private::serde_json::Map<::std::string::String, ::livewire::__private::serde_json::Value>) {
890                let mut synth_meta = ::livewire::__private::serde_json::Map::new();
891                #(#dehydrate)*
892
893                if !synth_meta.is_empty() {
894                    data.insert(
895                        ::std::string::String::from("__meta__"),
896                        ::livewire::__private::serde_json::Value::Object(synth_meta),
897                    );
898                }
899            }
900
901            fn hydrate_fields(
902                &mut self,
903                data: &::livewire::__private::serde_json::Map<::std::string::String, ::livewire::__private::serde_json::Value>,
904            ) -> ::livewire::component::Result<()> {
905                let meta = data
906                    .get("__meta__")
907                    .and_then(::livewire::__private::serde_json::Value::as_object);
908                #(#hydrate)*
909
910                ::core::result::Result::Ok(())
911            }
912
913            fn set_field(
914                &mut self,
915                field: &str,
916                value: ::livewire::__private::serde_json::Value,
917            ) -> ::livewire::component::Result<()> {
918                match field {
919                    #(#setters)*
920                    other => {
921                        return ::core::result::Result::Err(::livewire::error::LivewireError::UnknownProperty {
922                            property: ::std::string::String::from(other),
923                            component: ::std::string::String::from(
924                                <Self as ::livewire::component::LivewireState>::component_name(),
925                            ),
926                        });
927                    }
928                }
929
930                ::core::result::Result::Ok(())
931            }
932
933            fn render_values(
934                &self,
935                data: &mut ::livewire::__private::serde_json::Map<::std::string::String, ::livewire::__private::serde_json::Value>,
936            ) {
937                <Self as ::livewire::component::LivewireState>::dehydrate_fields(self, data);
938
939                // A model field shows its row to the template, while the snapshot keeps the
940                // reference, so the browser never receives the row.
941                #(#render_models)*
942            }
943
944            fn default_view(&self) -> ::livewire::component::ComponentView {
945                #default_view
946            }
947
948            fn validation_rules(&self) -> ::livewire::__private::Rules {
949                let mut rules = ::livewire::__private::Rules::new();
950                #(#validation_rules)*
951                rules
952            }
953        }
954    })
955}
956
957/// The class-level options on `#[component(..)]`.
958#[derive(Default)]
959struct ClassOptions {
960    layout: Option<String>,
961    title: Option<String>,
962    lazy: bool,
963    defer: bool,
964    isolate: bool,
965    transition: Option<String>,
966}
967
968impl Parse for ClassOptions {
969    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
970        let mut options = Self::default();
971
972        while !input.is_empty() {
973            let key: Ident = input.parse()?;
974
975            match key.to_string().as_str() {
976                "layout" => {
977                    input.parse::<Token![=]>()?;
978                    options.layout = Some(input.parse::<LitStr>()?.value());
979                }
980                "title" => {
981                    input.parse::<Token![=]>()?;
982                    options.title = Some(input.parse::<LitStr>()?.value());
983                }
984                "transition" => {
985                    input.parse::<Token![=]>()?;
986                    options.transition = Some(input.parse::<LitStr>()?.value());
987                }
988                "lazy" => options.lazy = true,
989                "defer" => options.defer = true,
990                "isolate" => options.isolate = true,
991                other => {
992                    return Err(syn::Error::new_spanned(
993                        key,
994                        format!(
995                            "unknown `#[component(..)]` option `{other}`: expected layout, title, \
996                             transition, lazy, defer, or isolate"
997                        ),
998                    ));
999                }
1000            }
1001
1002            if input.peek(Token![,]) {
1003                input.parse::<Token![,]>()?;
1004            }
1005        }
1006
1007        Ok(options)
1008    }
1009}
1010
1011/// One public method in the annotated implementation.
1012struct Method {
1013    name: Ident,
1014    item: syn::ImplItemFn,
1015    listener: Option<String>,
1016    renderless: bool,
1017    json: bool,
1018    asynchronous: bool,
1019    authorize: Option<Path>,
1020    computed: bool,
1021}
1022
1023impl Method {
1024    fn parameters(&self) -> Vec<(Ident, Type, bool)> {
1025        parameters(&self.item)
1026    }
1027
1028    fn returns_result(&self) -> bool {
1029        returns_result(&self.item)
1030    }
1031
1032    fn returns_value(&self) -> bool {
1033        match &self.item.sig.output {
1034            ReturnType::Default => false,
1035            ReturnType::Type(_, ty) => {
1036                let rendered = quote!(#ty).to_string().replace(' ', "");
1037                rendered != "()" && !rendered.starts_with("Result<(),") && !rendered.starts_with("laravel::Result<(),")
1038            }
1039        }
1040    }
1041}
1042
1043fn parameters(method: &syn::ImplItemFn) -> Vec<(Ident, Type, bool)> {
1044    method
1045        .sig
1046        .inputs
1047        .iter()
1048        .filter_map(|argument| match argument {
1049            FnArg::Receiver(_) => None,
1050            FnArg::Typed(typed) => {
1051                let name = match typed.pat.as_ref() {
1052                    syn::Pat::Ident(ident) => ident.ident.clone(),
1053                    _ => return None,
1054                };
1055                let optional = matches!(typed.ty.as_ref(), Type::Path(path) if path
1056                    .path
1057                    .segments
1058                    .last()
1059                    .is_some_and(|segment| segment.ident == "Option"));
1060                Some((name, (*typed.ty).clone(), optional))
1061            }
1062        })
1063        .collect()
1064}
1065
1066fn returns_result(method: &syn::ImplItemFn) -> bool {
1067    match &method.sig.output {
1068        ReturnType::Default => false,
1069        ReturnType::Type(_, ty) => {
1070            let rendered = quote!(#ty).to_string().replace(' ', "");
1071            rendered.starts_with("Result<") || rendered.starts_with("laravel::Result<")
1072        }
1073    }
1074}
1075
1076/// The parameters an action reads, as one expression per declared argument.
1077fn argument_reads(method: &Method, params: TokenStream2) -> impl Iterator<Item = TokenStream2> + use<> {
1078    method
1079        .parameters()
1080        .into_iter()
1081        .enumerate()
1082        .map(move |(index, (parameter, ty, optional))| {
1083            let parameter_name = parameter.to_string();
1084            let params = params.clone();
1085
1086            // An action that asks for the component's context gets it instead of a wire parameter,
1087            // so it can dispatch an event, redirect, or skip its render.
1088            let rendered = quote!(#ty).to_string();
1089            if rendered.contains("ComponentContext") {
1090                return if rendered.contains("mut") {
1091                    quote!(context)
1092                } else {
1093                    quote!(&*context)
1094                };
1095            }
1096
1097            match optional.then(|| optional_inner(&ty)).flatten() {
1098                Some(inner) => quote! {{
1099                    let value: ::core::option::Option<#inner> = #params.optional(&#parameter_name, #index)?;
1100                    value
1101                }},
1102                None => quote! {{
1103                    let value: #ty = #params.arg(&#parameter_name, #index)?;
1104                    value
1105                }},
1106            }
1107        })
1108        .collect::<Vec<_>>()
1109        .into_iter()
1110}
1111
1112/// The `T` of an `Option<T>`.
1113fn optional_inner(ty: &Type) -> Option<Type> {
1114    let Type::Path(path) = ty else {
1115        return None;
1116    };
1117    let segment = path.path.segments.last()?;
1118    if segment.ident != "Option" {
1119        return None;
1120    }
1121    let syn::PathArguments::AngleBracketed(arguments) = &segment.arguments else {
1122        return None;
1123    };
1124    arguments.args.iter().find_map(|argument| match argument {
1125        syn::GenericArgument::Type(ty) => Some(ty.clone()),
1126        _ => None,
1127    })
1128}
1129
1130fn generate_component(item: &ItemImpl, options: &ClassOptions) -> syn::Result<TokenStream2> {
1131    let self_ty = &item.self_ty;
1132    let mut methods = Vec::new();
1133    let mut computed: Vec<Method> = Vec::new();
1134    let mut lifecycle: Vec<String> = Vec::new();
1135
1136    for entry in &item.items {
1137        let ImplItem::Fn(method) = entry else {
1138            continue;
1139        };
1140        // A hand-written `authorize` is never called: the generated impl defines the trait's, from
1141        // the per-action policies. Refuse it here, where the mistake is, instead of at runtime —
1142        // and before the visibility filter, so a private one is refused too.
1143        if method.sig.ident == "authorize" {
1144            return Err(syn::Error::new(
1145                method.sig.ident.span(),
1146                "`authorize` is generated from the actions' policies: declare a policy with \
1147                 `#[livewire(authorize(path::to::policy))]` on the action it guards",
1148            ));
1149        }
1150
1151        if !matches!(method.vis, syn::Visibility::Public(_)) {
1152            continue;
1153        }
1154
1155        let name = method.sig.ident.clone();
1156        let mut parsed = Method {
1157            name: name.clone(),
1158            item: method.clone(),
1159            listener: None,
1160            renderless: false,
1161            json: false,
1162            asynchronous: false,
1163            authorize: None,
1164            computed: false,
1165        };
1166
1167        for attribute in &method.attrs {
1168            if !attribute.path().is_ident("livewire") {
1169                continue;
1170            }
1171
1172            attribute.parse_nested_meta(|meta| {
1173                if meta.path.is_ident("renderless") {
1174                    parsed.renderless = true;
1175                    return Ok(());
1176                }
1177                if meta.path.is_ident("json") {
1178                    parsed.json = true;
1179                    return Ok(());
1180                }
1181                if meta.path.is_ident("async") {
1182                    parsed.asynchronous = true;
1183                    return Ok(());
1184                }
1185                if meta.path.is_ident("on") {
1186                    let value: LitStr = meta.value()?.parse()?;
1187                    parsed.listener = Some(value.value());
1188                    return Ok(());
1189                }
1190                if meta.path.is_ident("authorize") {
1191                    let content;
1192                    syn::parenthesized!(content in meta.input);
1193                    parsed.authorize = Some(content.parse()?);
1194                    return Ok(());
1195                }
1196                if meta.path.is_ident("computed") {
1197                    if meta.input.peek(syn::token::Paren) {
1198                        return Err(
1199                            meta.error("`computed(..)` options are not implemented: write `#[livewire(computed)]`")
1200                        );
1201                    }
1202                    parsed.computed = true;
1203                    return Ok(());
1204                }
1205                Err(meta.error(
1206                    "unknown `#[livewire(..)]` method option: expected on = \"event\", renderless, \
1207                     json, async, or authorize(..)",
1208                ))
1209            })?;
1210        }
1211
1212        let name_text = name.to_string();
1213        if is_lifecycle(&name_text) {
1214            lifecycle.push(name_text);
1215        } else if parsed.computed {
1216            computed.push(parsed);
1217        } else {
1218            methods.push(parsed);
1219        }
1220    }
1221
1222    let has = |name: &str| lifecycle.iter().any(|lifecycle| lifecycle == name);
1223
1224    let mut hooks = Vec::new();
1225
1226    if has("boot") {
1227        hooks.push(quote! {
1228            fn boot(&mut self) -> ::livewire::component::Result<()> {
1229                self.boot()
1230            }
1231        });
1232    }
1233
1234    let mount_call = if has("mount") {
1235        let mount_item = item.items.iter().find_map(|entry| match entry {
1236            ImplItem::Fn(method) if method.sig.ident == "mount" => Some(method),
1237            _ => None,
1238        });
1239        let probe = Method {
1240            name: format_ident!("mount"),
1241            item: mount_item.cloned().unwrap_or_else(|| {
1242                syn::parse_quote! {
1243                    fn mount(&mut self) {}
1244                }
1245            }),
1246            listener: None,
1247            renderless: false,
1248            json: false,
1249            asynchronous: false,
1250            authorize: None,
1251            computed: false,
1252        };
1253        let arguments = argument_reads(&probe, quote!(params)).collect::<Vec<_>>();
1254        let call = quote!(self.mount(#(#arguments),*));
1255
1256        if mount_item.is_some_and(returns_result) {
1257            quote!(#call?;)
1258        } else {
1259            quote!({ #call; })
1260        }
1261    } else {
1262        quote!()
1263    };
1264
1265    let mount = quote! {
1266        fn mount(
1267            &mut self,
1268            params: ::livewire::component::Params,
1269            context: &mut ::livewire::component::ComponentContext,
1270        ) -> ::livewire::component::Result<()> {
1271            let _ = context;
1272
1273            {
1274                let mut known = ::livewire::__private::serde_json::Map::new();
1275                if let ::livewire::component::Params::Named(named) = &params {
1276                    let fields = <Self as ::livewire::component::LivewireState>::wire_fields();
1277                    for (key, value) in named {
1278                        let camel = ::livewire::component::camel_case(key);
1279                        if fields.iter().any(|field| field.name == camel && !field.locked) {
1280                            known.insert(camel, value.clone());
1281                        }
1282                    }
1283                }
1284                <Self as ::livewire::component::LivewireState>::hydrate_fields(self, &known)?;
1285            }
1286
1287            #mount_call
1288
1289            ::core::result::Result::Ok(())
1290        }
1291    };
1292
1293    if has("initialize") {
1294        hooks.push(quote! {
1295            fn initialize(
1296                &mut self,
1297                context: &mut ::livewire::component::ComponentContext,
1298            ) -> ::livewire::component::Result<()> {
1299                self.initialize(context)
1300            }
1301        });
1302    }
1303    if has("booted") {
1304        hooks.push(quote! {
1305            fn booted(&mut self) -> ::livewire::component::Result<()> {
1306                self.booted()
1307            }
1308        });
1309    }
1310    if has("hydrate") {
1311        hooks.push(quote! {
1312            fn hydrate(
1313                &mut self,
1314                context: &mut ::livewire::component::ComponentContext,
1315            ) -> ::livewire::component::Result<()> {
1316                self.hydrate(context)
1317            }
1318        });
1319    }
1320    if has("render") {
1321        hooks.push(quote! {
1322            fn render(&self) -> ::livewire::component::Result<::livewire::component::ComponentView> {
1323                self.render()
1324            }
1325        });
1326    }
1327    if has("dehydrate") {
1328        hooks.push(quote! {
1329            fn dehydrate(
1330                &mut self,
1331                context: &mut ::livewire::component::ComponentContext,
1332            ) -> ::livewire::component::Result<()> {
1333                self.dehydrate(context)
1334            }
1335        });
1336    }
1337    if has("destroy") {
1338        hooks.push(quote! {
1339            fn destroy(&mut self) {
1340                self.destroy();
1341            }
1342        });
1343    }
1344    if has("updating") {
1345        hooks.push(quote! {
1346            fn updating(
1347                &mut self,
1348                property: &str,
1349                value: &::livewire::__private::serde_json::Value,
1350                context: &mut ::livewire::component::ComponentContext,
1351            ) -> ::livewire::component::Result<()> {
1352                self.updating(property, value, context)
1353            }
1354        });
1355    }
1356    if has("updated") {
1357        hooks.push(quote! {
1358            fn updated(
1359                &mut self,
1360                property: &str,
1361                context: &mut ::livewire::component::ComponentContext,
1362            ) -> ::livewire::component::Result<()> {
1363                self.updated(property, context)
1364            }
1365        });
1366    }
1367    if has("exception") {
1368        hooks.push(quote! {
1369            fn exception(
1370                &mut self,
1371                error: &::livewire::error::LivewireError,
1372                context: &mut ::livewire::component::ComponentContext,
1373            ) {
1374                self.exception(error, context);
1375            }
1376        });
1377    }
1378    if has("release_token") {
1379        hooks.push(quote! {
1380            fn release_token(&self) -> &'static str {
1381                self.release_token()
1382            }
1383        });
1384    }
1385    if has("listeners") {
1386        hooks.push(quote! {
1387            fn listeners(&self) -> &'static [::livewire::component::Listener] {
1388                self.listeners()
1389            }
1390        });
1391    }
1392    if has("dispatches") {
1393        hooks.push(quote! {
1394            fn dispatches(&self) -> &'static [::livewire::component::Listener] {
1395                self.dispatches()
1396            }
1397        });
1398    }
1399
1400    let arms = methods.iter().map(action_arm);
1401
1402    let declared_listeners = methods.iter().filter_map(|method| {
1403        let event = method.listener.as_ref()?;
1404        let name = method.name.to_string();
1405        Some(quote!(::livewire::component::Listener {
1406            event: #event,
1407            method: ::core::option::Option::Some(#name),
1408        }))
1409    });
1410    let listeners = if methods.iter().any(|method| method.listener.is_some()) {
1411        quote! {
1412            fn listeners(&self) -> &'static [::livewire::component::Listener] {
1413                &[#(#declared_listeners),*]
1414            }
1415        }
1416    } else {
1417        quote!()
1418    };
1419
1420    let authorize_arms = methods.iter().filter_map(|method| {
1421        let name = method.name.to_string();
1422        let policy = method.authorize.as_ref()?;
1423        Some(quote! {
1424            #name => #policy(self).await.map_err(|error| {
1425                ::livewire::error::LivewireError::PolicyFailed {
1426                    method: ::std::string::String::from(#name),
1427                    message: error.to_string(),
1428                }
1429            }),
1430        })
1431    });
1432
1433    let authorize = quote! {
1434        async fn authorize(
1435            &mut self,
1436            method: &str,
1437            context: &::livewire::component::ComponentContext,
1438        ) -> ::livewire::component::Result<bool> {
1439            let _ = context;
1440
1441            match method {
1442                #(#authorize_arms)*
1443                _ => ::core::result::Result::Ok(true),
1444            }
1445        }
1446    };
1447
1448    let computed_values = computed.iter().map(|method| {
1449        let name = method.name.to_string();
1450        let identifier = &method.name;
1451
1452        quote! {
1453            {
1454                let value = match ::livewire::context::LivewireRequest::current()
1455                    .and_then(|request| request.computed(id, #name))
1456                {
1457                    ::core::option::Option::Some(value) => value,
1458                    ::core::option::Option::None => {
1459                        let value = ::livewire::component::to_wire(&self.#identifier());
1460                        if let ::core::option::Option::Some(request) = ::livewire::context::LivewireRequest::current() {
1461                            request.set_computed(id, #name, value.clone());
1462                        }
1463                        value
1464                    }
1465                };
1466                values.insert(::std::string::String::from(#name), value);
1467            }
1468        }
1469    });
1470
1471    let computed_impl = if computed.is_empty() {
1472        quote!()
1473    } else {
1474        quote! {
1475            fn computed_values(
1476                &self,
1477                id: &str,
1478            ) -> ::livewire::__private::serde_json::Map<::std::string::String, ::livewire::__private::serde_json::Value> {
1479                let mut values = ::livewire::__private::serde_json::Map::new();
1480                #(#computed_values)*
1481                values
1482            }
1483        }
1484    };
1485
1486    let json_methods: Vec<String> = methods
1487        .iter()
1488        .filter(|method| method.json)
1489        .map(|method| method.name.to_string())
1490        .collect();
1491    let async_methods = methods
1492        .iter()
1493        .filter(|method| method.asynchronous)
1494        .map(|method| method.name.to_string());
1495
1496    let layout = match &options.layout {
1497        None => quote!(::core::option::Option::None),
1498        Some(layout) => quote!(::core::option::Option::Some(#layout)),
1499    };
1500    let title = match &options.title {
1501        None => quote!(::core::option::Option::None),
1502        Some(title) => quote!(::core::option::Option::Some(#title)),
1503    };
1504    let transition = match &options.transition {
1505        None => quote!(::core::option::Option::None),
1506        Some(transition) => quote!(::core::option::Option::Some(#transition)),
1507    };
1508    let lazy = options.lazy;
1509    let defer = options.defer;
1510    let isolate = options.isolate;
1511
1512    // The component's own implementation stays, minus the helper attributes this macro consumed:
1513    // Rust has no helper attributes of its own for an attribute macro.
1514    let mut original = item.clone();
1515    for entry in &mut original.items {
1516        if let ImplItem::Fn(method) = entry {
1517            method.attrs.retain(|attribute| !attribute.path().is_ident("livewire"));
1518        }
1519    }
1520
1521    Ok(quote! {
1522        #original
1523
1524        #[::livewire::__private::async_trait]
1525        impl ::livewire::component::Component for #self_ty {
1526            #mount
1527            #computed_impl
1528
1529            async fn hydrate_models(
1530                &mut self,
1531                _context: &mut ::livewire::component::ComponentContext,
1532            ) -> ::livewire::component::Result<()> {
1533                self.resolve_model_refs().await
1534            }
1535            #(#hooks)*
1536            #listeners
1537            #authorize
1538
1539            async fn call(
1540                &mut self,
1541                call: ::livewire::component::Call,
1542                context: &mut ::livewire::component::ComponentContext,
1543            ) -> ::livewire::component::Result<::core::option::Option<::livewire::__private::serde_json::Value>> {
1544                match call.method.as_str() {
1545                    #(#arms)*
1546                    "$refresh" | "$commit" | "$sync" | "__dispatch" | "__lazyLoad" | "__lazyLoadIsland" => ::core::result::Result::Ok(::core::option::Option::None),
1547                    "$set" => {
1548                        let property: ::std::string::String = call.params.arg("property", 0)?;
1549                        let value: ::livewire::__private::serde_json::Value = call.params.arg("value", 1)?;
1550                        <Self as ::livewire::component::LivewireState>::set_field(self, &property, value)?;
1551                        ::core::result::Result::Ok(::core::option::Option::None)
1552                    }
1553                    other => ::core::result::Result::Err(::livewire::error::LivewireError::MethodNotFound {
1554                        method: ::std::string::String::from(other),
1555                    }),
1556                }
1557            }
1558
1559            fn action_result_kind(&self, method: &str) -> ::livewire::component::ActionResultKind {
1560                match method {
1561                    #(#json_methods => ::livewire::component::ActionResultKind::Json,)*
1562                    _ => ::livewire::component::ActionResultKind::Ignored,
1563                }
1564            }
1565
1566            fn json_methods(&self) -> &'static [&'static str] {
1567                &[#(#json_methods),*]
1568            }
1569
1570            fn class_options(&self) -> ::livewire::component::ClassOptions {
1571                ::livewire::component::ClassOptions {
1572                    layout: #layout,
1573                    title: #title,
1574                    transition: #transition,
1575                    lazy: #lazy,
1576                    defer: #defer,
1577                    isolate: #isolate,
1578                }
1579            }
1580
1581            fn async_methods(&self) -> &'static [&'static str] {
1582                &[#(#async_methods),*]
1583            }
1584        }
1585    })
1586}
1587
1588/// The method names the trait implements, which an inherent method may also define: the inherent
1589/// method wins in method-call syntax, so the generated forwarding calls the component's own.
1590fn is_lifecycle(name: &str) -> bool {
1591    matches!(
1592        name,
1593        "boot"
1594            | "initialize"
1595            | "mount"
1596            | "booted"
1597            | "hydrate"
1598            | "render"
1599            | "dehydrate"
1600            | "destroy"
1601            | "updating"
1602            | "updated"
1603            | "release_token"
1604            | "listeners"
1605            | "dispatches"
1606            | "exception"
1607    )
1608}
1609
1610/// Generates one dispatch arm: decode the declared parameters, call the method, and record what it
1611/// returned.
1612fn action_arm(method: &Method) -> TokenStream2 {
1613    let name = method.name.to_string();
1614    let identifier = &method.name;
1615    let arguments = argument_reads(method, quote!(call.params)).collect::<Vec<_>>();
1616    // An `async fn` action is awaited here: a dropped future would answer the browser while the
1617    // action's body never ran.
1618    let invocation = if method.item.sig.asyncness.is_some() {
1619        quote!(self.#identifier(#(#arguments),*).await)
1620    } else {
1621        quote!(self.#identifier(#(#arguments),*))
1622    };
1623
1624    let mut flags = Vec::new();
1625    if method.renderless {
1626        flags.push(quote! {
1627            context.add_effect("skipRender", ::livewire::__private::serde_json::Value::Bool(true));
1628        });
1629    }
1630    if method.json {
1631        // The snapshot's `json` list tells the browser how to answer; the render is skipped either
1632        // way, as upstream's `BaseJson` does.
1633        flags.push(quote! {
1634            context.add_effect("skipRender", ::livewire::__private::serde_json::Value::Bool(true));
1635        });
1636    }
1637
1638    let body = match (method.returns_result(), method.returns_value()) {
1639        (true, true) => quote! {
1640            let value = #invocation?;
1641            ::core::result::Result::Ok(::core::option::Option::Some(
1642                ::livewire::__private::serde_json::to_value(value)
1643                    .unwrap_or(::livewire::__private::serde_json::Value::Null),
1644            ))
1645        },
1646        (true, false) => quote! {
1647            #invocation?;
1648            ::core::result::Result::Ok(::core::option::Option::None)
1649        },
1650        (false, true) => quote! {
1651            let value = #invocation;
1652            ::core::result::Result::Ok(::core::option::Option::Some(
1653                ::livewire::__private::serde_json::to_value(value)
1654                    .unwrap_or(::livewire::__private::serde_json::Value::Null),
1655            ))
1656        },
1657        (false, false) => quote! {
1658            #invocation;
1659            ::core::result::Result::Ok(::core::option::Option::None)
1660        },
1661    };
1662
1663    quote! {
1664        #name => {
1665            #(#flags)*
1666            #body
1667        }
1668    }
1669}