vim_macros 0.4.4

Rust Binding MAcros for the VMware by Broadcom vCenter VI JSON API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
//! # vim_macros
//!
//! Procedural macros for simplified VMware vSphere property retrieval and monitoring.
//!
//! ## Property Retrieval with Macros
//!
//! The library provides two powerful macros to simplify property retrieval and monitoring:
//!
//! ### One-time Property Retrieval with `vim_retrievable`
//!
//! The `vim_retrievable` macro creates structs for efficient, one-time property retrieval:
//!
//! ```ignore
//! use vim_macros::vim_retrievable;
//! use vim_rs::core::pc_retrieve::ObjectRetriever;
//!
//! // Define a struct mapping to HostSystem properties
//! vim_retrievable!(
//!     struct Host: HostSystem {
//!         name = "name",
//!         power_state = "runtime.power_state",
//!         connected = "runtime.connection_state",
//!         cpu_usage = "summary.quick_stats.overall_cpu_usage",
//!         memory_usage = "summary.quick_stats.overall_memory_usage",
//!         uptime = "summary.quick_stats.uptime",
//!         datastores = "datastore.length",
//!     }
//! );
//!
//! async fn print_hosts(client: &Client) -> Result<()> {
//!    // Create a retriever using the client
//!    let retriever = ObjectRetriever::new(client.clone())?;
//!
//!    // Retrieve all hosts with their properties in a single API call
//!    let hosts: Vec<HostInfo> = retriever
//!            .retrieve_objects_from_container(&client.service_content().root_folder)
//!            .await?;
//!
//!    // Work with strongly-typed host objects
//!    for host in hosts {
//!       println!("Host {} is {:?}", host.name, host.power_state);
//!    }
//!
//!    Ok(())
//! }
//! ```
//!
//! The `ObjectRetriever` utility class is used to retrieve properties from the vSphere API. It
//! allows you to retrieve properties from a container (e.g., a datacenter or cluster) or a specific
//! list of managed objects. The `retrieve_objects_from_container` method retrieves all objects
//! from the specified container and returns them as a vector of strongly-typed objects. The
//! `retrieve_objects_from_list` method retrieves a specific list of managed objects.
//!
//! ### Continuous Property Monitoring with `vim_updatable`
//!
//! The `vim_updatable` macro creates structs for continuous property monitoring:
//!
//! ```ignore
//! vim_updatable!(
//!     struct VmDetails: VirtualMachine {
//!         name = "name",
//!         power_state = "runtime.power_state",
//!     }
//! );
//!
//! impl Display for VmDetails {
//!     fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
//!         write!(
//!             f,
//!             "VM ({}): {} with power state: {:?}", self.id.value, self.name, self.power_state
//!         )
//!     }
//! }
//!
//! struct ChangeListener {}
//!
//! impl ObjectCacheListener<VmDetails> for ChangeListener {
//!     fn on_new(&mut self, obj: &VmDetails) {
//!         info!("New VM: {}", obj);
//!     }
//!
//!     fn on_update(&mut self, obj: &VmDetails) {
//!         info!("VM updated: {}", obj);
//!     }
//!
//!     fn on_remove(&mut self, obj: VmDetails) {
//!         info!("VM removed: {}", obj);
//!     }
//! }
//!
//! async fn monitor_vms(client: &Arc<Client>) -> Result<(), Error> {
//!     let cache = Box::new(ObjectCache::new_with_listener(Box::new(ChangeListener {})));
//!     let mut manager = CacheManager::new(client.clone())?;
//!     let mut monitor = manager.create_monitor()?;
//!
//!     manager.add_container_cache(cache, &client.service_content().root_folder).await?;
//!
//!     let start = Instant::now();
//!     loop {
//!         let updates = monitor.wait_updates(10).await?;
//!         if let Some(updates) = updates {
//!             manager.apply_updates(updates)?;
//!         }
//!         if start.elapsed().as_secs() > 60 {
//!             break;
//!         }
//!     }
//!
//!     manager.destroy().await?;
//!     Ok(())
//! }
//! ```
//! Note that `CacheManager` also supports `add_list_cache` method to monitor predefined list of
//! objects.
//!
//! ### How the Macros Work
//!
//! Both macros:
//!
//! 1. Generate a struct based on the data structure defined in the macro, corresponding to a vSphere managed object type (VirtualMachine, HostSystem, etc.)
//! 2. Elicit the types of struct fields from the property paths in the vSphere API
//! 3. Handle type conversion between vSphere dynamic types and Rust types
//!
//! The `vim_rs::core::pc_retrieve` module supports one-time property retrieval,
//! while `vim_rs::core::pc_cache` provides infrastructure for continuous property monitoring.
//!
//! ### Macro Syntax
//!
//! ```ignore
//! vim_retrievable!(
//!     struct StructName: ManagedObjectType {
//!         field_name = "property.path",
//!         another_field = "another.property.path",
//!         tolerant = "some.path"?, // optional: force `Option<T>` if the server may omit it
//!     }
//! );
//! ```
//!
//! Property paths use dot delimited rust field name starting from the managed object property
//! accessor and going deeper inside the structure. Property paths only support the properties of
//! the declared field types i.e. properties from child types are not supported.
//!
//! Array properties support special `length` property to retrieve their length e.g.
//! "datastore.length"to obtain the count of datastores attached to a host.
//!
//! The same syntax applies to the `vim_updatable!` macro.
//!
//! ### Forcing a field to be optional
//!
//! A trailing `?` after the property-path string forces the generated field to be
//! `Option<T>` even when the XSD marks the property as required. The same syntax
//! works in **`vim_retrievable!`** and **`vim_updatable!`**: both share resolution
//! and generated `TryFrom` logic, so missing nominally-required properties surface
//! as `None` instead of failing `TryFrom<vim_rs::types::structs::ObjectContent>`
//! (retrieval) or `TryFrom<vim_rs::types::structs::ObjectUpdate>` (cache). For
//! updatable structs, `apply_update` treats forced-optional fields like any other
//! `Option<T>` (assign `Some(...)`, clear with `None`).
//!
//! ```ignore
//! vim_updatable!(
//!     struct ClusterDetails: ClusterComputeResource {
//!         name = "name",
//!         // XSD-required fields that some servers (notably vcsim) never
//!         // populate. The `?` tells the macro to type them as `Option<T>`
//!         // instead of `T` so that missing values do not cause the whole
//!         // object to be dropped by `TryFrom<ObjectUpdate>`.
//!         available_cpu = "summary_ex.effective_cpu"?,
//!         available_memory = "summary_ex.effective_memory"?,
//!     }
//! );
//! ```
//!
//! Fields already resolved as `Option<T>` (because the XSD or some ancestor in
//! the path is optional) are unaffected; `?` is idempotent.
mod field_data;
mod resolver;

use proc_macro::TokenStream;
use quote::quote;
use resolver::get_default_field_data;
use syn::token::Comma;
use syn::{
    braced, parse::Parse, parse::ParseStream, parse_macro_input, punctuated::Punctuated, token,
    Ident, LitStr, Result, Token,
};

#[allow(dead_code)]
struct PropertyField {
    name: Ident,
    colon_token: Token![=],
    path: LitStr,
    /// Trailing `?` after the path forces the generated field to be
    /// `Option<T>` even when the XSD marks it as required. Useful for
    /// servers that deviate from the spec (vcsim, older vCenters) where
    /// a nominally-required property may simply be absent.
    force_optional: Option<Token![?]>,
}

#[allow(dead_code)]
struct VimObjectMacro {
    struct_token: Token![struct],
    struct_name: Ident,
    colon_token: Token![:],
    object_type: Ident,
    brace_token: token::Brace,
    fields: Punctuated<PropertyField, Token![,]>,
}

impl Parse for PropertyField {
    fn parse(input: ParseStream) -> Result<Self> {
        let name: Ident = input.parse()?;
        let colon_token: Token![=] = input.parse()?;
        let path: LitStr = input.parse()?;
        let force_optional: Option<Token![?]> = input.parse()?;
        Ok(PropertyField {
            name,
            colon_token,
            path,
            force_optional,
        })
    }
}

impl Parse for VimObjectMacro {
    fn parse(input: ParseStream) -> Result<Self> {
        let content;
        Ok(VimObjectMacro {
            struct_token: input.parse()?,
            struct_name: input.parse()?,
            colon_token: input.parse()?,
            object_type: input.parse()?,
            brace_token: braced!(content in input),
            fields: Punctuated::parse_terminated(&content)?,
        })
    }
}

struct FieldInfo<'a> {
    property_field: &'a PropertyField,
    field_data: resolver::FieldData,
}

/// A macro to generate a struct and implementation necessary to work with
/// PropertyCollector::RetrievePropertiesEx API. Developers need to select the managed object type
/// of interest and the properties they need retrieved. For example to retrieve properties of a
/// VirtualMachine object, the macro can be used as follows:
///
/// ```ignore
/// vim_retrievable!(
///    struct VM: VirtualMachine {
///       name = "name",
///       os = "summary.guest.guest_full_name",
///       storage = "summary.storage",
///       host_cpu = "summary.quick_stats.overall_cpu_usage",
///       host_memory = "summary.quick_stats.host_memory_usage",
///       status = "summary.overall_status",
///       power_state = "runtime.power_state",
///       devices = "config.hardware.device",
///       ft_info = "config.ft_info",
///   }
/// );
/// ```
/// The macro will generate a struct `VM` with the specified properties and extract their types from
/// the vSphere API. The generated struct will implement the `TryFrom<vim_rs::types::structs::ObjectContent>`
/// trait, allowing you to convert the output of the `PropertyCollector::retrieve_properties_ex`
/// into vector of objects from the generated struct.
///
/// Optional trailing `?` after a path string forces `Option<T>` for that field even
/// when the spec marks it required (see crate-level "Forcing a field to be optional").
#[proc_macro]
pub fn vim_retrievable(input: TokenStream) -> TokenStream {
    let VimObjectMacro {
        struct_token: _,
        struct_name,
        colon_token: _,
        object_type: managed_object_type,
        brace_token: _,
        fields,
    } = parse_macro_input!(input as VimObjectMacro);

    let (field_infos, errors) = resolve_fields(&managed_object_type, &fields);

    let struct_tokens = generate_struct_decl(&struct_name, &field_infos);

    let struct_impl_tokens =
        generate_retrieve_struct_impl(&struct_name, &managed_object_type, &field_infos);

    let try_from_object_content = generate_try_from_object_content(&struct_name, &field_infos);

    let output = quote! {
        #( #errors )*

        #struct_tokens
        #struct_impl_tokens

        #try_from_object_content
    };
    output.into()
}

/// A macro to generate a struct and implementation necessary to work with
/// PropertyCollector::wait_for_updates_ex API. Developers need to select the managed object type
/// of interest and the properties they need replicated. For example to replicate properties of a
/// VirtualMachine object, the macro can be used as follows:
///
/// ```ignore
/// vim_updatable!(
///    struct VM: VirtualMachine {
///       name = "name",
///       os = "summary.guest.guest_full_name",
///       storage = "summary.storage",
///       host_cpu = "summary.quick_stats.overall_cpu_usage",
///       host_memory = "summary.quick_stats.host_memory_usage",
///       status = "summary.overall_status",
///       power_state = "runtime.power_state",
///       devices = "config.hardware.device",
///       ft_info = "config.ft_info",
///   }
/// );
/// ```
/// The macro will generate a struct `VM` with the specified properties and extract their types from
/// the vSphere API. The generated struct will implement the `TryFrom<vim_rs::types::structs::ObjectUpdate>`
/// trait, allowing you to convert the output of the `PropertyCollector::wait_for_updates_ex`
/// into vector of objects from the generated struct. Subsequently, the generated struct content can
/// be updated using the `apply_update` method. The generated struct will also implement the
/// `Queriable` trait, allowing you to use the `prop_spec` method to generate a `PropertySpec` for
/// the specified properties.
///
/// The generated struct is usable with the `ObjectCache` and `CacheManager` utility objects.
///
/// Optional trailing `?` after a path string forces `Option<T>` for that field even
/// when the spec marks it required (see crate-level "Forcing a field to be optional").
#[proc_macro]
pub fn vim_updatable(input: TokenStream) -> TokenStream {
    let VimObjectMacro {
        struct_token: _,
        struct_name,
        colon_token: _,
        object_type: managed_object_type,
        brace_token: _,
        fields,
    } = parse_macro_input!(input as VimObjectMacro);

    let (field_infos, errors) = resolve_fields(&managed_object_type, &fields);

    let struct_tokens = generate_struct_decl(&struct_name, &field_infos);

    let struct_impl_tokens =
        generate_updateable_struct_impl(&struct_name, &managed_object_type, &field_infos);

    let try_from_object_content = generate_try_from_object_update(&struct_name, &field_infos);

    let output = quote! {
        #( #errors )*

        #struct_tokens
        #struct_impl_tokens

        #try_from_object_content
    };
    output.into()
}

fn resolve_fields<'a>(
    managed_object_type: &Ident,
    fields: &'a Punctuated<PropertyField, Comma>,
) -> (Vec<FieldInfo<'a>>, Vec<proc_macro2::TokenStream>) {
    let mut field_infos = Vec::new();
    let mut errors: Vec<proc_macro2::TokenStream> = Vec::new();
    for property_field in fields {
        let path_str = property_field.path.value();
        let res = resolver::resolve_path(&managed_object_type.to_string(), &path_str);
        let mut field_data = match res {
            Ok(field_type) => field_type,
            Err(e) => {
                let msg = format!("Error resolving path: {}", e);
                errors.push(syn::Error::new(property_field.path.span(), msg).to_compile_error());
                get_default_field_data()
            }
        };
        // Caller-side opt-out from XSD required-ness: `field = "path"?` forces
        // the generated field to be `Option<T>`. Servers that omit the
        // property (vcsim is the prime offender) then leave the value as
        // `None` instead of making `TryFrom<ObjectUpdate>` bail with
        // `missing_required_field`.
        if property_field.force_optional.is_some() && !field_data.is_optional {
            field_data.is_optional = true;
            field_data.data_type = format!("Option<{}>", field_data.data_type);
        }
        field_infos.push(FieldInfo {
            property_field,
            field_data,
        });
    }
    (field_infos, errors)
}

/// Generates a struct declaration based on the provided struct name and fields.
fn generate_struct_decl(struct_name: &Ident, fields: &Vec<FieldInfo>) -> proc_macro2::TokenStream {
    let mut field_declarations: Vec<proc_macro2::TokenStream> = Vec::with_capacity(fields.len());
    let mut docs: Vec<&'static str> = Vec::with_capacity(fields.len());

    for f in fields {
        let field_name = &f.property_field.name;
        let parsed_field_type: syn::Type = syn::parse_str(&f.field_data.data_type).unwrap();
        let decl = quote! {
            #field_name : #parsed_field_type
        };
        field_declarations.push(decl);
        docs.push(f.field_data.doc.unwrap_or(""))
    }

    let struct_tokens = quote! {
        #[derive(Debug)]
        pub struct #struct_name {
            #[doc = "Object identifier"]
            pub id: vim_rs::types::structs::ManagedObjectReference,
            #(#[doc = #docs]
            pub #field_declarations,)*
        }
    };
    struct_tokens
}

fn generate_retrieve_struct_impl(
    struct_name: &Ident,
    managed_object_type: &Ident,
    fields: &Vec<FieldInfo>,
) -> proc_macro2::TokenStream {
    let prop_spec = prop_spec(managed_object_type, fields);
    let id = id();
    quote! {
        impl vim_rs::core::pc_helpers::Queriable for #struct_name {
            #prop_spec
        }

        impl #struct_name {
            pub #id
        }
    }
}

fn generate_updateable_struct_impl(
    struct_name: &Ident,
    managed_object_type: &Ident,
    fields: &Vec<FieldInfo>,
) -> proc_macro2::TokenStream {
    let prop_spec = prop_spec(managed_object_type, fields);
    let id = id();
    let apply_update = generate_apply_update(fields);
    quote! {
        impl vim_rs::core::pc_helpers::Queriable for #struct_name {
            #prop_spec
        }

        impl vim_rs::core::pc_cache::Cacheable for #struct_name {
            #id
            #apply_update
        }
    }
}

fn prop_spec(managed_object_type: &Ident, fields: &Vec<FieldInfo>) -> proc_macro2::TokenStream {
    let field_paths: Vec<&str> = fields
        .iter()
        .map(|f| f.field_data.vim_path.as_str())
        .collect();
    let prop_paths_quoted: Vec<proc_macro2::TokenStream> = field_paths
        .iter()
        .map(|path| quote! { #path.into() })
        .collect();

    quote! {
        fn prop_spec() -> vim_rs::types::structs::PropertySpec {
            vim_rs::types::structs::PropertySpec {
                all: Some(false),
                path_set: Some(vec![
                    #(#prop_paths_quoted),*
                ]),
                r#type: vim_rs::types::enums::MoTypesEnum::#managed_object_type.as_str().to_string(),
            }
        }
    }
}

fn id() -> proc_macro2::TokenStream {
    quote! {
        fn id(&self) -> &vim_rs::types::structs::ManagedObjectReference {
            &self.id
        }
    }
}

fn generate_try_from_object_content(
    struct_name: &Ident,
    fields: &Vec<FieldInfo>,
) -> proc_macro2::TokenStream {
    let mut field_declarations: Vec<proc_macro2::TokenStream> = Vec::with_capacity(fields.len());
    let mut field_conversions: Vec<proc_macro2::TokenStream> = Vec::with_capacity(fields.len());
    let mut field_assignments: Vec<proc_macro2::TokenStream> = Vec::with_capacity(fields.len());
    let mut idx = 1;
    for field in fields {
        let field_alias: Ident = syn::parse_str(&format!("field{}", idx)).unwrap();
        let field_name = &field.property_field.name;
        field_declarations.push(quote! { let mut #field_alias = None; });
        match field.field_data.processing_type {
            resolver::FieldProcessingType::Enum(enum_field_name) => {
                field_conversions.push(generate_enum_field_from_content(
                    field,
                    &field_alias,
                    &enum_field_name,
                ));
            }
            resolver::FieldProcessingType::Struct => {
                field_conversions.push(generate_struct_field_from_content(
                    field,
                    &field_alias,
                    &field.field_data.data_type,
                ));
            }
            resolver::FieldProcessingType::Trait => {
                field_conversions.push(generate_trait_field_from_content(
                    field,
                    &field_alias,
                    &field.field_data.data_type,
                ));
            }
        }
        if field.field_data.is_optional {
            field_assignments.push(quote! { #field_name: #field_alias });
        } else {
            let field_name_str = field.field_data.vim_path.as_str();
            field_assignments.push(quote! { #field_name: #field_alias.ok_or_else(|| vim_rs::core::error::Error::missing_required_field(#field_name_str.to_string()))? });
        }
        idx += 1;
    }

    quote! {
        impl core::convert::TryFrom<vim_rs::types::structs::ObjectContent> for #struct_name {
            type Error = vim_rs::core::error::Error;

            fn try_from(row: vim_rs::types::structs::ObjectContent) -> vim_rs::core::error::Result<Self> {
                let id = row.obj;
                let Some(row) = row.prop_set else {
                    return Err(vim_rs::core::error::Error::no_data_found());
                };

                #(#field_declarations)*

                for prop in row {
                    match prop.name.as_str() {
                        #(#field_conversions)*
                        name => {
                            return Err(vim_rs::core::error::Error::unexpected_property_path(name.to_string()));
                        }
                    }
                }

                Ok(#struct_name {
                    id,
                    #(#field_assignments),*
                })
            }
        }
    }
}

fn generate_try_from_object_update(
    struct_name: &Ident,
    fields: &Vec<FieldInfo>,
) -> proc_macro2::TokenStream {
    let mut field_declarations: Vec<proc_macro2::TokenStream> = Vec::with_capacity(fields.len());
    let mut field_conversions: Vec<proc_macro2::TokenStream> = Vec::with_capacity(fields.len());
    let mut field_assignments: Vec<proc_macro2::TokenStream> = Vec::with_capacity(fields.len());
    let mut idx = 1;
    for field in fields {
        let field_alias: Ident = syn::parse_str(&format!("field{}", idx)).unwrap();
        let field_name = &field.property_field.name;
        field_declarations.push(quote! { let mut #field_alias = None; });
        match field.field_data.processing_type {
            resolver::FieldProcessingType::Enum(enum_field_name) => {
                field_conversions.push(generate_enum_field_from_update(
                    field,
                    &field_alias,
                    &enum_field_name,
                ));
            }
            resolver::FieldProcessingType::Struct => {
                field_conversions.push(generate_struct_field_from_update(
                    field,
                    &field_alias,
                    &field.field_data.data_type,
                ));
            }
            resolver::FieldProcessingType::Trait => {
                field_conversions.push(generate_trait_field_from_update(
                    field,
                    &field_alias,
                    &field.field_data.data_type,
                ));
            }
        }
        if field.field_data.is_optional {
            field_assignments.push(quote! { #field_name: #field_alias });
        } else {
            let field_name_str = field.field_data.vim_path.as_str();
            field_assignments.push(quote! { #field_name: #field_alias.ok_or_else(|| vim_rs::core::error::Error::missing_required_field(#field_name_str.to_string()))? });
        }
        idx += 1;
    }

    quote! {
        impl core::convert::TryFrom<vim_rs::types::structs::ObjectUpdate> for #struct_name {
            type Error = vim_rs::core::error::Error;

            fn try_from(row: vim_rs::types::structs::ObjectUpdate) -> vim_rs::core::error::Result<Self> {
                let id = row.obj;
                let Some(row) = row.change_set else {
                    return Err(vim_rs::core::error::Error::no_data_found());
                };

                #(#field_declarations)*

                for prop in row {
                    if matches!(prop.op, vim_rs::types::enums::PropertyChangeOpEnum::Add | vim_rs::types::enums::PropertyChangeOpEnum::Remove | vim_rs::types::enums::PropertyChangeOpEnum::Other_(_)) {
                        // It is assumption of the code here that create_filter was called with `partial_updates = false`.
                        // This flag value implies only `assign` and `indirectRemove` operations are returned. `add` and
                        // `remove` operations are used when `partial_updates = true`. The big problem is that with
                        // `partial_updates` server will return paths to sub-properties that we cannot easily resolve in
                        // Rust hence the assumption that `partial_updates = false` is made.`Add` and `Remove` operations
                        // are not supported in this code.
                        // error!("Unsupported PropertyChangeOp: {:?} for property {} in  object {:?}", prop.op, prop.name, id);
                        continue;
                    }
                    match prop.name.as_str() {
                        #(#field_conversions)*
                        name => {
                            return Err(vim_rs::core::error::Error::unexpected_property_path(name.to_string()));
                        }
                    }
                }

                Ok(#struct_name {
                    id,
                    #(#field_assignments),*
                })
            }
        }
    }
}

fn generate_apply_update(fields: &Vec<FieldInfo>) -> proc_macro2::TokenStream {
    let mut field_conversions: Vec<proc_macro2::TokenStream> = Vec::with_capacity(fields.len());
    for field in fields {
        match field.field_data.processing_type {
            resolver::FieldProcessingType::Enum(enum_field_name) => {
                field_conversions.push(generate_enum_field_apply(field, &enum_field_name));
            }
            resolver::FieldProcessingType::Struct => {
                field_conversions.push(generate_struct_field_apply(
                    field,
                    &field.field_data.data_type,
                ));
            }
            resolver::FieldProcessingType::Trait => {
                field_conversions.push(generate_trait_field_apply(
                    field,
                    &field.field_data.data_type,
                ));
            }
        }
    }

    quote! {
        fn apply_update(&mut self, update: vim_rs::types::structs::ObjectUpdate) -> vim_rs::core::pc_helpers::Result<()> {
            let Some(row) = update.change_set else {
                return Ok(());
            };

            for prop in row {
                if matches!(prop.op, vim_rs::types::enums::PropertyChangeOpEnum::Add | vim_rs::types::enums::PropertyChangeOpEnum::Remove | vim_rs::types::enums::PropertyChangeOpEnum::Other_(_)) {
                    // It is assumption of the code here that create_filter was called with `partial_updates = false`.
                    // This flag value implies only `assign` and `indirectRemove` operations are returned. `add` and
                    // `remove` operations are used when `partial_updates = true`. The big problem is that with
                    // `partial_updates` server will return paths to sub-properties that we cannot easily resolve in
                    // Rust hence the assumption that `partial_updates = false` is made.`Add` and `Remove` operations
                    // are not supported in this code.
                    // error!("Unsupported PropertyChangeOp: {:?} for property {} in  object {:?}", prop.op, prop.name, id);
                    continue;
                }
                match prop.name.as_str() {
                    #(#field_conversions)*
                    name => {
                        return Err(vim_rs::core::error::Error::unexpected_property_path(name.to_string()));
                    }
                }
            }
            Ok(())
        }
    }
}

// Templates for TryFrom<ObjectContent> generated code

// 1. Generate ValueElements enum members deserialize code
//                 "<property path>" => {
//                     <field name with ordinal> = match prop.val {
//                         VimAny::Value(ValueElements::<enum field name>(vd)) => Some(vd),
//                         ref val => return Err(pc_helpers::Error::InvalidPropertyType { property: "<property path>".to_string(), "<enum field name>".to_string(), got: pc_helpers::type_name(val)}),
//                     };
//                 }
fn generate_enum_field_from_content(
    field: &FieldInfo,
    field_alias: &Ident,
    enum_field_name: &str,
) -> proc_macro2::TokenStream {
    let path = &field.field_data.vim_path;
    let enum_field = Ident::new(enum_field_name, field.property_field.path.span());
    quote! {
        #path => {
            #field_alias = match prop.val {
                vim_rs::types::vim_any::VimAny::Value(vim_rs::types::boxed_types::ValueElements::#enum_field(vd)) => Some(vd),
                ref val => return Err(vim_rs::core::error::Error::invalid_property_type(#path.to_string(), #enum_field_name.to_string(), vim_rs::core::pc_helpers::type_name(val))),
            };
        }
    }
}

fn generate_enum_field_from_update(
    field: &FieldInfo,
    field_alias: &Ident,
    enum_field_name: &str,
) -> proc_macro2::TokenStream {
    let path = &field.field_data.vim_path;
    let enum_field = Ident::new(enum_field_name, field.property_field.path.span());
    quote! {
        #path => {
            #field_alias = match prop.val {
                Some(vim_rs::types::vim_any::VimAny::Value(vim_rs::types::boxed_types::ValueElements::#enum_field(vd))) => Some(vd),
                None => continue,
                Some(ref val) => return Err(vim_rs::core::error::Error::invalid_property_type(#path.to_string(), #enum_field_name.to_string(), vim_rs::core::pc_helpers::type_name(val))),
            };
        }
    }
}

fn generate_enum_field_apply(field: &FieldInfo, enum_field_name: &str) -> proc_macro2::TokenStream {
    let path = &field.field_data.vim_path;
    let enum_field = Ident::new(enum_field_name, field.property_field.path.span());
    let field_name = &field.property_field.name;
    let none_code;
    let value_code;
    if field.field_data.is_optional {
        none_code = quote! { None };
        value_code = quote! { Some(vd) };
    } else {
        none_code = quote! { return Err(vim_rs::core::error::Error::missing_required_field(#path.to_string())) };
        value_code = quote! { vd };
    };

    quote! {
        #path => {
            self.#field_name = match prop.val {
                Some(vim_rs::types::vim_any::VimAny::Value(vim_rs::types::boxed_types::ValueElements::#enum_field(vd))) => #value_code,
                None => #none_code,
                Some(ref val) => return Err(vim_rs::core::error::Error::invalid_property_type(#path.to_string(), #enum_field_name.to_string(), vim_rs::core::pc_helpers::type_name(val))),
            };
        }
    }
}

// 2. Generate struct type deserialize code ofr structs without children
//                "<property path>" => {
//                     <field name with ordinal> = match prop.val {
//                         VimAny::Object(obj) => {
//                             let name = obj.data_type().as_str();
//                             match obj.as_any_box().downcast() {
//                                 Ok(val) => Some(*val),
//                                 Err(_) => return Err(pc_helpers::Error::InvalidPropertyType {property: "<property path>".to_string(), "<struct type name>".to_string(), name.to_string())),
//                             }
//                         },
//                         ref val => return Err(pc_helpers::Error::InvalidPropertyType {property: "<property path>".to_string(), "<struct type name>".to_string(), got: pc_helpers::type_name(val)}),
//                     };
//                 }
fn generate_struct_field_from_content(
    field: &FieldInfo,
    field_alias: &Ident,
    struct_type: &str,
) -> proc_macro2::TokenStream {
    let path = &field.field_data.vim_path;

    quote! {
        #path => {
            #field_alias = match prop.val {
                vim_rs::types::vim_any::VimAny::Object(obj) => {
                    let name = obj.data_type().as_str();
                    match obj.as_any_box().downcast() {
                        Ok(val) => Some(*val),
                        Err(_) => return Err(vim_rs::core::error::Error::invalid_property_type( #path.to_string(), #struct_type.to_string(), name.to_string())),
                    }
                },
                ref val => return Err(vim_rs::core::error::Error::invalid_property_type( #path.to_string(), #struct_type.to_string(), vim_rs::core::pc_helpers::type_name(val))),
            };
        }
    }
}

fn generate_struct_field_from_update(
    field: &FieldInfo,
    field_alias: &Ident,
    struct_type: &str,
) -> proc_macro2::TokenStream {
    let path = &field.field_data.vim_path;
    quote! {
        #path => {
            #field_alias = match prop.val {
                Some(vim_rs::types::vim_any::VimAny::Object(obj)) => {
                    let name = obj.data_type().as_str();
                    match obj.as_any_box().downcast() {
                        Ok(val) => Some(*val),
                        Err(_) => return Err(vim_rs::core::error::Error::invalid_property_type( #path.to_string(), #struct_type.to_string(), name.to_string())),
                    }
                },
                None => continue,
                Some(ref val) => return Err(vim_rs::core::error::Error::invalid_property_type( #path.to_string(), #struct_type.to_string(), vim_rs::core::pc_helpers::type_name(val))),
            };
        }
    }
}

fn generate_struct_field_apply(field: &FieldInfo, struct_type: &str) -> proc_macro2::TokenStream {
    let path = &field.field_data.vim_path;
    let field_name = &field.property_field.name;
    let none_code;
    let value_code;
    if field.field_data.is_optional {
        none_code = quote! { None };
        value_code = quote! { Some(*val) };
    } else {
        none_code = quote! { return Err(vim_rs::core::error::Error::missing_required_field(#path.to_string())) };
        value_code = quote! { *val };
    };
    quote! {
        #path => {
            self.#field_name = match prop.val {
                Some(vim_rs::types::vim_any::VimAny::Object(obj)) => {
                    let name = obj.data_type().as_str();
                    match obj.as_any_box().downcast() {
                        Ok(val) => #value_code,
                        Err(_) => return Err(vim_rs::core::error::Error::invalid_property_type( #path.to_string(), #struct_type.to_string(), name.to_string())),
                    }
                },
                None => #none_code,
                Some(ref val) => return Err(vim_rs::core::error::Error::invalid_property_type( #path.to_string(), #struct_type.to_string(), vim_rs::core::pc_helpers::type_name(val))),
            };
        }
    }
}

// 3. Generate trait type deserialize code for structs with children
//                "<property path>" => {
//                     <field name with ordinal> = match prop.val {
//                         vim_rs::types::vim_any::VimAny::Object(obj) => {
//                             let name = obj.data_type().as_str();
//                             match obj.into_box() {
//                                 Ok(val) => Some(val),
//                                 Err(_) => return Err(pc_helpers::Error::InvalidPropertyType {property: "<property path>".to_string(), "<trait type name>".to_string(), name.to_string())),
//                             }
//                         },
//                         ref val => return Err(pc_helpers::Error::InvalidPropertyType {property: "<property path>".to_string(), "<trait type name>".to_string(), got: pc_helpers::type_name(val)}),
//                     };
//                 }
fn generate_trait_field_from_content(
    field: &FieldInfo,
    field_alias: &Ident,
    trait_type: &str,
) -> proc_macro2::TokenStream {
    let path = &field.field_data.vim_path;
    quote! {
        #path => {
            #field_alias = match prop.val {
                vim_rs::types::vim_any::VimAny::Object(obj) => {
                    let name = obj.data_type().as_str();
                    match vim_rs::types::convert::CastInto::into_box(obj) {
                        Ok(val) => Some(val),
                        Err(_) => return Err(vim_rs::core::error::Error::invalid_property_type( #path.to_string(), #trait_type.to_string(), name.to_string())),
                    }
                },
                ref val => return Err(vim_rs::core::error::Error::invalid_property_type( #path.to_string(), #trait_type.to_string(), vim_rs::core::pc_helpers::type_name(val))),
            };
        }
    }
}

fn generate_trait_field_from_update(
    field: &FieldInfo,
    field_alias: &Ident,
    trait_type: &str,
) -> proc_macro2::TokenStream {
    let path = &field.field_data.vim_path;
    quote! {
        #path => {
            #field_alias = match prop.val {
                Some(vim_rs::types::vim_any::VimAny::Object(obj)) => {
                    let name = obj.data_type().as_str();
                    match vim_rs::types::convert::CastInto::into_box(obj) {
                        Ok(val) => Some(val),
                        Err(_) => return Err(vim_rs::core::error::Error::invalid_property_type( #path.to_string(), #trait_type.to_string(), name.to_string())),
                    }
                },
                None => continue,
                Some(ref val) => return Err(vim_rs::core::error::Error::invalid_property_type( #path.to_string(), #trait_type.to_string(), vim_rs::core::pc_helpers::type_name(val))),
            };
        }
    }
}

fn generate_trait_field_apply(field: &FieldInfo, trait_type: &str) -> proc_macro2::TokenStream {
    let path = &field.field_data.vim_path;
    let field_name = &field.property_field.name;
    let none_code;
    let value_code;
    if field.field_data.is_optional {
        none_code = quote! { None };
        value_code = quote! { Some(val) };
    } else {
        none_code = quote! { return Err(vim_rs::core::error::Error::missing_required_field(#path.to_string())) };
        value_code = quote! { val };
    };

    quote! {
        #path => {
            self.#field_name = match prop.val {
                Some(vim_rs::types::vim_any::VimAny::Object(obj)) => {
                    let name = obj.data_type().as_str();
                    match vim_rs::types::convert::CastInto::into_box(obj) {
                        Ok(val) => #value_code,
                        Err(_) => return Err(vim_rs::core::error::Error::invalid_property_type( #path.to_string(), #trait_type.to_string(), name.to_string())),
                    }
                },
                None => #none_code,
                Some(ref val) => return Err(vim_rs::core::error::Error::invalid_property_type( #path.to_string(), #trait_type.to_string(), vim_rs::core::pc_helpers::type_name(val))),
            };
        }
    }
}