odata_client_codegen 0.1.0

Strongly-typed OData client code generation
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
/*
Generate a module structure with public types/relevant trait impls.

TODO:
- Structural types
    - Where default value is defined for a property, use `#[serde(default = "...")]` on Rust struct
    field
- Enum types
    - Where default value is defined, `impl Default`
        - Use `#[serde(default)]` for any properties of this type
- Entity container
    - Members (entity sets, singletons, action/function imports) should be defined directly
    in the qualifier (don't create a sub-module for the Entity Container's name)
    - Entity sets
        - Static/const instance of an `EntitySet<T>`, where `EntitySet` is defined in `odata_client`
        lib, not generated
        - `include_in_service_document` property on set definiion: no idea what to do with this
        - Navigation property bindings
            - Not sure we need to use this info, since each navigation field on a fetched entity
            provides a direct link to the record
    - Singletons
        - Static/const instance of a `EntityLink<T>`
            - May have to use a separate type `Singleton<T>`, defined in `odata_client`, if we need
            any additional info/functionality on the Singleton
- Limited type codegen
    - For when a full schema is prohibitively large. Support only generating type/set definitions
    for a subset of a entity types. Any direct dependency entity types would still need a
    definition; these should be generated with no fields of their own, other than key fields. This
    avoids dragging in a full dependency graph.
*/

mod ident_source;
#[cfg(test)]
mod test;

use std::collections::{HashMap, HashSet, VecDeque};

use bumpalo::Bump;
use petgraph::{algo::greedy_feedback_arc_set, stable_graph::StableDiGraph};
use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens};
use syn::{parse::Parse, parse::ParseStream, parse_quote, Ident};

use crate::{
    entity_model::{
        definition_lookup::{EdmItem, NamedEdmItem},
        identifiers::{QualifiedName, TargetPath},
        ComplexishType, EntityModel, EntitySet, EntityType, EnumType, NavigationProperty,
        NavigationPropertyModifier, NavigationPropertyVariant, PrimitiveTypeAlias, Property,
        PropertyVariant, Schema, Singleton,
    },
    entity_model_filter::{EntityModelFilterLookup, EntityTypeInclusion},
    EntityModelFilter,
};
use ident_source::{FieldNameSource, ModChildNameSource};

use self::ident_source::to_snake_case;

/// Represents a module's full path in segments, and its pre-written contents as a token stream.
type ModPathAndContents = (VecDeque<String>, TokenStream);

#[derive(Clone, Copy)]
enum ServiceUrlReference<'a> {
    Declare { url: &'a str },
    RefParent { level: usize },
}

impl<'a> ServiceUrlReference<'a> {
    fn to_stream(&self) -> TokenStream {
        match self {
            ServiceUrlReference::Declare { url } => quote! {
                pub const SERVICE_URL: &'static str = #url;
            },
            ServiceUrlReference::RefParent { level } => format!(
                "use {}::SERVICE_URL;",
                std::iter::repeat("super")
                    .take(*level)
                    .collect::<Vec<_>>()
                    .join("::")
            )
            .parse()
            .unwrap(),
        }
    }
}

// TODO: convert to return result instead of panic
pub fn generate_client_module<'ar>(
    entity_model: &EntityModel<'ar>,
    arena: &'ar Bump,
    entity_model_filter: Option<&mut dyn EntityModelFilter>,
) -> TokenStream {
    let mut schemas_and_mod_paths: Vec<(VecDeque<String>, &Schema)> = entity_model
        .schemas
        .iter()
        .map(|schema| {
            let mod_path = namespace_to_module_path(schema.alias.unwrap_or(schema.namespace));
            (mod_path, schema)
        })
        .collect();

    // Trim any common leading module path segments
    loop {
        enum MatchingSegment<'a> {
            Start,
            Match(&'a str),
            NoMatch,
        }
        use MatchingSegment::*;

        let leading_segment =
            schemas_and_mod_paths
                .iter()
                .fold(Start, |prev_seg, (mod_path, _schema)| {
                    match (prev_seg, mod_path.get(0)) {
                        (Start, Some(curr_seg)) => Match(curr_seg),
                        (Match(prev_seg), Some(curr_seg)) => {
                            if prev_seg == curr_seg {
                                Match(prev_seg)
                            } else {
                                NoMatch
                            }
                        }
                        (_, None) => NoMatch,
                        (NoMatch, _) => NoMatch,
                    }
                });

        if let Match(_) = leading_segment {
            for (mod_path, _schema) in &mut schemas_and_mod_paths {
                mod_path.pop_front();
            }
        } else {
            break;
        }
    }

    let indirection_points = get_property_indirection_points(entity_model);
    let entity_model_filter_lookup =
        EntityModelFilterLookup::new(entity_model, entity_model_filter);

    let mut modules: Vec<ModPathAndContents> = Vec::new();

    // Child item name sources for each submodule
    let mut item_name_sources: HashMap<Vec<String>, ModChildNameSource> = HashMap::new();

    for (mod_path, schema) in schemas_and_mod_paths {
        let mut mod_stream = TokenStream::new();
        let child_name_source = item_name_sources
            .entry(mod_path.iter().map(|s| s.to_string()).collect())
            .or_insert_with(|| ModChildNameSource::new(arena));

        // TODO: doc comment stating this schema's namespace

        for &entity_set in &schema.entity_container.entity_sets {
            if !entity_model_filter_lookup.includes(entity_set) {
                continue;
            }

            let syn_entity_set_struct = gen_entity_set(entity_set, child_name_source);
            syn_entity_set_struct.to_tokens(&mut mod_stream);
        }

        for &singleton in &schema.entity_container.singletons {
            if !entity_model_filter_lookup.includes(singleton) {
                continue;
            }

            let syn_singleton_struct = gen_singleton(singleton, child_name_source);
            syn_singleton_struct.to_tokens(&mut mod_stream);
        }

        for &complex_type in &schema.complex_types {
            if !entity_model_filter_lookup.includes(complex_type) {
                continue;
            }

            let syn_struct = gen_complexish_type_struct(
                &complex_type.0,
                &indirection_points,
                child_name_source,
                &entity_model_filter_lookup,
            );

            // TODO: `EXPAND_QUERY` for complex types? (may be used in nested `EXPAND_QUERY` in
            // entity type)

            syn_struct.to_tokens(&mut mod_stream);
        }

        for &entity_type in &schema.entity_types {
            match entity_model_filter_lookup.includes(entity_type) {
                EntityTypeInclusion::IncludeFull => {
                    let syn_struct = gen_complexish_type_struct(
                        &entity_type.complex_type_fields,
                        &indirection_points,
                        child_name_source,
                        &entity_model_filter_lookup,
                    );

                    syn_struct.to_tokens(&mut mod_stream);

                    let entity_properties_impl =
                        gen_entity_properties_impl(&entity_type, child_name_source);

                    entity_properties_impl.to_tokens(&mut mod_stream);
                }
                EntityTypeInclusion::IncludeStub => {
                    let syn_struct = gen_complexish_type_stub(
                        &entity_type.complex_type_fields,
                        child_name_source,
                    );

                    syn_struct.to_tokens(&mut mod_stream);
                }
                EntityTypeInclusion::Exclude => {
                    continue;
                }
            }
        }

        for &primitive_alias in &schema.primitive_aliases {
            if !entity_model_filter_lookup.includes(primitive_alias) {
                continue;
            }

            let syn_newtype = gen_primitive_alias_newtype(primitive_alias, child_name_source);
            syn_newtype.to_tokens(&mut mod_stream);
        }

        for &enum_type in &schema.enum_types {
            if !entity_model_filter_lookup.includes(enum_type) {
                continue;
            }

            let syn_enum = gen_enum_type(enum_type, child_name_source);
            syn_enum.to_tokens(&mut mod_stream);
        }

        modules.push((mod_path, mod_stream));
    }

    let service_url = ServiceUrlReference::Declare {
        url: &entity_model.service_url,
    };

    build_submodules(modules, service_url)
}

fn namespace_to_module_path(namespace: &str) -> VecDeque<String> {
    namespace.split('.').map(to_snake_case).collect()
}

/// Determines where to add indirection on properties of complex types/entity types in order to
/// avoid "recursive type has infinite size" compile error on generated code. Does not include nav
/// properties, as they only generate `EntityLink` fields.
fn get_property_indirection_points<'ar>(
    entity_model: &EntityModel<'ar>,
) -> HashSet<TargetPath<'ar>> {
    let mut graph = StableDiGraph::new();
    let mut node_indices = HashMap::new();

    // Add each entity/complex type as a node
    for schema in &entity_model.schemas {
        for entity_type in &schema.entity_types {
            let node_index = graph.add_node(entity_type.name());
            node_indices.insert(entity_type.name(), node_index);
        }

        for complex_type in &schema.complex_types {
            let node_index = graph.add_node(complex_type.name());
            node_indices.insert(complex_type.name(), node_index);
        }
    }

    // Add properties with complex type as directional edges
    for schema in &entity_model.schemas {
        for entity_type in &schema.entity_types {
            let src_node_index = node_indices[&entity_type.name()];

            for prop in &entity_type.complex_type_fields.properties {
                if let PropertyVariant::Complex(complex_type) = prop.r#type.get() {
                    let tgt_node_index = node_indices[&complex_type.name()];
                    graph.add_edge(src_node_index, tgt_node_index, prop.name());
                }
            }
        }

        for complex_type in &schema.complex_types {
            let src_node_index = node_indices[&complex_type.name()];

            for prop in &complex_type.0.properties {
                if let PropertyVariant::Complex(complex_type) = prop.r#type.get() {
                    let tgt_node_index = node_indices[&complex_type.name()];
                    graph.add_edge(src_node_index, tgt_node_index, prop.name());
                }
            }
        }
    }

    let indirected_props = greedy_feedback_arc_set(&graph);

    indirected_props.map(|e| *e.weight()).collect()
}

fn to_ident(s: &str) -> Ident {
    syn::parse_str(s).unwrap()
}

fn build_submodules(
    submodules: Vec<ModPathAndContents>,
    service_url: ServiceUrlReference,
) -> TokenStream {
    let mut submod_groups: Vec<(String, Vec<ModPathAndContents>)> = Vec::new();
    let mut direct_members: Vec<TokenStream> = Vec::new();

    // Partition modules by first segment (and direct child(ren))
    for (mut namespace, mod_contents) in submodules {
        if namespace.is_empty() {
            direct_members.push(mod_contents);
            continue;
        }

        let existing_group = submod_groups
            .iter_mut()
            .find(|(first_seg, _members)| first_seg == &namespace[0]);

        match existing_group {
            Some((_first_seg, members)) => {
                namespace.pop_front().unwrap();
                members.push((namespace, mod_contents));
            }
            None => {
                let subgroup_mod_name = namespace.pop_front().unwrap();
                submod_groups.push((subgroup_mod_name, vec![(namespace, mod_contents)]));
            }
        };
    }

    let add_import_statements = !direct_members.is_empty();

    // Always render the url declaration at the top level; only reference the top-level declaration
    // on modules which contain other direct members, which may use it
    let add_service_url_ref =
        !direct_members.is_empty() || matches!(service_url, ServiceUrlReference::Declare { .. });

    let service_url_ref = if add_service_url_ref {
        service_url.to_stream()
    } else {
        quote! {}
    };

    let imports = if add_import_statements {
        module_imports()
    } else {
        quote! {}
    };

    let child_service_url = match service_url {
        ServiceUrlReference::Declare { .. } => ServiceUrlReference::RefParent { level: 1 },
        ServiceUrlReference::RefParent { level } => {
            ServiceUrlReference::RefParent { level: level + 1 }
        }
    };

    // Recursive call to submodules
    let submodules: TokenStream = submod_groups
        .into_iter()
        .map(|(mod_name, contents)| {
            let mod_ident = to_ident(&mod_name);
            let mod_contents = build_submodules(contents, child_service_url);

            quote! {
                pub mod #mod_ident {
                    #mod_contents
                }
            }
        })
        .collect();

    let direct_members: TokenStream = direct_members.into_iter().collect();

    quote! {
        #imports
        #service_url_ref
        #submodules
        #direct_members
    }
}

/// `Field` wrapper that implements `Parse`: https://github.com/dtolnay/syn/issues/651#issuecomment-503771863
struct ParseableNamedField {
    pub field: syn::Field,
}

impl Parse for ParseableNamedField {
    fn parse(input: ParseStream<'_>) -> Result<Self, syn::Error> {
        let field = syn::Field::parse_named(input)?;

        Ok(ParseableNamedField { field })
    }
}

fn gen_complexish_type_struct<'ar, BaseType: EdmItem + NamedEdmItem<Name = QualifiedName<'ar>>>(
    complexish_type: &ComplexishType<'ar, BaseType>,
    indirection_points: &HashSet<TargetPath<'ar>>,
    child_name_source: &mut ModChildNameSource<'ar>,
    entity_model_filter_lookup: &EntityModelFilterLookup<'ar>,
) -> syn::ItemStruct {
    let ComplexishType {
        name,
        base_type,
        is_open_type,
        is_abstract: _,
        properties,
        nav_properties,
    } = &complexish_type;

    let struct_name = child_name_source.get_type_name(name.uq_name);
    let struct_ident = to_ident(struct_name);

    let item_attrs = type_item_attributes();
    let mut item_struct: syn::ItemStruct = parse_quote! {
        #item_attrs
        pub struct #struct_ident {}
    };

    let fields = match item_struct.fields {
        syn::Fields::Named(ref mut f) => f,
        _ => panic!("Unexpected struct fields type"),
    };

    let mut field_name_source = FieldNameSource::new();

    if let Some(base_type) = base_type {
        let base_type_field =
            gen_base_type_field(base_type.get(), &mut field_name_source, child_name_source);
        fields.named.push(base_type_field);
    }

    for prop in properties {
        let is_indirected = indirection_points.contains(&prop.name());
        let field = gen_property_field(
            prop,
            is_indirected,
            &mut field_name_source,
            child_name_source,
        );
        fields.named.push(field);
    }

    for nav_prop in nav_properties {
        let field = gen_nav_property_field(
            nav_prop,
            &mut field_name_source,
            child_name_source,
            entity_model_filter_lookup,
        );
        fields.named.push(field);
    }

    if *is_open_type {
        // TODO: capture dynamic properties in a `HashMap<String, DynamicProperty>`
        // (`DynamicProperty` type to be defined). See odata-json-format-v4.01 sec 4.5.3.
        // This `HashMap` should have the `#[serde(flatten)]` attributes, and it should be declared
        // after the `base` field (if any), otherwise field values which belong to the base type
        // will end up in the hash map.
        // The declared type for a dynamic property is de/serialised in-line as
        // `"PropertyName@type": "TypeName"`. This should information should be used in
        // `DynamicProperty` if possible.
        // In general, fields with "@" in the name are metadata, and should not be added to the hash
        // map.
    }

    item_struct
}

// TODO: sub-types may override properties/nav properties of their base type with a more restrictive
// base type (odata-csdl-xml-v4.01 sec 7, sec 8). Supporting base types in Rust with the `base`
// field is generally incompatible with this behaviour. We could:
// - Remove the `base` field, and instead merge in fields from the base type
// - Allow the user to choose between having a `base` field and merging fields, erroring if the
//   former isn't possible, due to overridden fields.
fn gen_base_type_field<'ar, BaseType: NamedEdmItem<Name = QualifiedName<'ar>>>(
    base_type: &BaseType,
    field_name_source: &mut FieldNameSource,
    mod_child_name_source: &mut ModChildNameSource<'ar>,
) -> syn::Field {
    let base_field_name = field_name_source.get_struct_field_name("base");
    let base_field_ident = to_ident(base_field_name);
    let base_type_name = mod_child_name_source.get_type_name(base_type.name().uq_name);
    let field_type: syn::Type = syn::Type::Verbatim(
        base_type_name
            .parse()
            .expect("Failed to parse type str as token stream"),
    );

    // TODO: check `base` isn't the name of a property; append `_` prefix if so (and check that
    // that `_base` isn't used, etc)
    let base_type_field: ParseableNamedField = parse_quote! {
        #[serde(flatten)]
        pub #base_field_ident: #field_type
    };

    base_type_field.field
}

fn gen_property_field<'ar>(
    prop: &Property<'ar>,
    is_indirected: bool,
    field_name_source: &mut FieldNameSource,
    mod_child_name_source: &mut ModChildNameSource<'ar>,
) -> syn::Field {
    let prop_name = prop.name().path;
    let field_name = field_name_source.get_struct_field_name(prop_name);
    let field_ident = to_ident(field_name);

    let inner_type_name = match prop.r#type.get() {
        PropertyVariant::Primitive(p) => p.value_representation_type_name(),
        PropertyVariant::Abstract => panic!("Abstract EDM type handling not implemented"),
        PropertyVariant::PrimitiveAlias(a) => mod_child_name_source.get_type_name(a.name().uq_name),
        PropertyVariant::Complex(c) => mod_child_name_source.get_type_name(c.name().uq_name),
        PropertyVariant::Enumeration { enum_type, .. } => {
            mod_child_name_source.get_type_name(enum_type.name.uq_name)
        }
    };

    let inner_type = syn::Type::Verbatim(
        inner_type_name
            .parse()
            .expect("Failed to parse type str as token stream"),
    );

    let field_type = match (prop.nullable, prop.is_collection, is_indirected) {
        (false, false, false) => inner_type,
        (false, false, true) => parse_quote!(Box<#inner_type>),
        (false, true, _) => parse_quote!(Vec<#inner_type>),
        (true, false, false) => parse_quote!(Option<#inner_type>),
        (true, false, true) => parse_quote!(Option<Box<#inner_type>>),
        (true, true, _) => parse_quote!(Vec<Option<#inner_type>>),
    };

    // TODO: handle default value for primitive/enum types. In this case:
    // - omit `Option` from type ascription
    // - add a private function to get the default value.
    // - add `#[serde(default = "[default_getter]")]` attribute

    let serde_as_attr = match prop.r#type.get() {
        PropertyVariant::Primitive(prim) => {
            if let Some(inner_type_name) = prim.deserialize_as_path() {
                let serde_as_path = match (prop.nullable, prop.is_collection, is_indirected) {
                    (false, false, false) => inner_type_name.to_string(),
                    (false, false, true) => format!("Box<{}>", inner_type_name),
                    (false, true, _) => format!("Vec<{}>", inner_type_name),
                    (true, false, false) => format!("Option<{}>", inner_type_name),
                    (true, false, true) => format!("Option<Box<{}>>", inner_type_name),
                    (true, true, _) => format!("Vec<Option<{}>>", inner_type_name),
                };

                quote! {
                    #[serde_as(as = #serde_as_path)]
                }
            } else {
                quote! {}
            }
        }
        _ => quote! {},
    };

    // TODO: could add `#[serde(rename_all = "PascalCase")]` to container and skip
    // `#[serde(rename = "...")]` on fields where possible. Also for nav props.
    let serde_rename_attr = if field_name != prop_name {
        quote! {
            #[serde(rename = #prop_name)]
        }
    } else {
        quote! {}
    };

    let prop_field: ParseableNamedField = parse_quote! {
        #serde_rename_attr
        #serde_as_attr
        pub #field_ident: #field_type
    };

    prop_field.field
}

fn gen_nav_property_field<'ar>(
    nav_prop: &NavigationProperty<'ar>,
    field_name_source: &mut FieldNameSource,
    mod_child_name_source: &mut ModChildNameSource<'ar>,
    entity_model_filter_lookup: &EntityModelFilterLookup<'ar>,
) -> syn::Field {
    let nav_prop_path = &nav_prop.name().path;
    let field_name = field_name_source.get_struct_field_name(nav_prop_path);
    let field_ident = to_ident(field_name);
    let field_type =
        nav_property_field_type(nav_prop, mod_child_name_source, entity_model_filter_lookup);

    let serde_rename_attr = if &field_name != nav_prop_path {
        quote! {
            #[serde(rename = #nav_prop_path)]
        }
    } else {
        quote! {}
    };

    let prop_field: ParseableNamedField = parse_quote! {
        #serde_rename_attr
        pub #field_ident: #field_type
    };

    prop_field.field
}

fn nav_property_field_type<'ar>(
    nav_prop: &NavigationProperty<'ar>,
    mod_child_name_source: &mut ModChildNameSource<'ar>,
    entity_model_filter_lookup: &EntityModelFilterLookup<'ar>,
) -> syn::Type {
    let entity_type = match &nav_prop.r#type {
        NavigationPropertyVariant::Abstract => panic!("Abstract EDM type handling not implemented"),
        NavigationPropertyVariant::Entity(e) => e.get(),
    };

    let inner_type = syn::Type::Verbatim(
        mod_child_name_source
            .get_type_name(entity_type.name().uq_name)
            .parse()
            .expect("Failed to parse type str as token stream"),
    );

    let link_type = match entity_model_filter_lookup.includes(entity_type) {
        EntityTypeInclusion::IncludeFull => syn::Type::Verbatim("EntityLink".parse().unwrap()),
        EntityTypeInclusion::IncludeStub => syn::Type::Verbatim("EntityLinkStub".parse().unwrap()),
        EntityTypeInclusion::Exclude => {
            panic!(
                "{} field type {} not included in codegen (should be included fully or as stub)",
                nav_prop.name(),
                entity_type.name()
            )
        }
    };

    // Non-containment navigation property fields will be `EntityLink`s which allow fetching of the
    // full partner from the appropriate entity set. Containment navigation property fields will
    // fetch the partner data initially, so the field type is the actual type of partner.
    match (nav_prop.contains_target, &nav_prop.type_modifier) {
        (false, NavigationPropertyModifier::NonNull) => parse_quote!(#link_type<#inner_type>),
        (false, NavigationPropertyModifier::Nullable) => {
            parse_quote!(Option<#link_type<#inner_type>>)
        }
        (false, NavigationPropertyModifier::Collection) => {
            parse_quote!(Vec<#link_type<#inner_type>>)
        }
        (true, NavigationPropertyModifier::NonNull) => inner_type,
        (true, NavigationPropertyModifier::Nullable) => parse_quote!(Option<#inner_type>),
        (true, NavigationPropertyModifier::Collection) => parse_quote!(Vec<#inner_type>),
    }
}

fn gen_entity_properties_impl<'ar>(
    entity_type: &EntityType<'ar>,
    child_name_source: &mut ModChildNameSource<'ar>,
) -> syn::ItemImpl {
    let type_name = child_name_source.get_type_name(entity_type.name().uq_name);
    let type_ident = to_ident(type_name);
    let expand_query: syn::Expr = match gen_expand_query_string(entity_type) {
        s if s.is_empty() => parse_quote!(ExpandQuery::None),
        s => parse_quote!(ExpandQuery::Expand(#s)),
    };

    parse_quote! {
        impl EntityProperties for #type_ident {
            const EXPAND_QUERY: ExpandQuery = #expand_query;
        }
    }
}

// TODO: avoid stack overflow on reference cycles of containment properties. afaik this is legal,
// so we might need a very special way of handling this.
fn gen_expand_query_string(entity_type: &EntityType) -> String {
    let mut segments = Vec::new();

    for nav_prop in &entity_type.complex_type_fields.nav_properties {
        if nav_prop.contains_target {
            let nav_prop_type = match &nav_prop.r#type {
                NavigationPropertyVariant::Abstract => panic!(), // TODO
                NavigationPropertyVariant::Entity(e) => e.get(),
            };

            let sub_expand_query = gen_expand_query_string(nav_prop_type);

            if sub_expand_query.is_empty() {
                segments.push(nav_prop.name.path.to_string());
            } else {
                segments.push(format!(
                    "{}($expand={})",
                    &nav_prop.name.path, sub_expand_query
                ));
            }
        } else {
            segments.push(format!("{}/$ref", &nav_prop.name.path));
        }
    }

    segments.join(",")
}

fn gen_complexish_type_stub<'ar, BaseType: EdmItem + NamedEdmItem<Name = QualifiedName<'ar>>>(
    complexish_type: &ComplexishType<'ar, BaseType>,
    child_name_source: &mut ModChildNameSource<'ar>,
) -> syn::ItemStruct {
    let struct_name = child_name_source.get_type_name(complexish_type.name.uq_name);
    let struct_ident = to_ident(struct_name);

    parse_quote! {
        #[derive(Debug)]
        pub struct #struct_ident;
    }
}

fn gen_primitive_alias_newtype<'ar>(
    primitive_alias: &PrimitiveTypeAlias<'ar>,
    child_name_source: &mut ModChildNameSource<'ar>,
) -> syn::ItemStruct {
    let struct_name = child_name_source.get_type_name(primitive_alias.name().uq_name);
    let struct_ident = to_ident(struct_name);
    let inner_type_name = primitive_alias.r#type.value_representation_type_name();
    let inner_type_ident = to_ident(inner_type_name);
    let item_attrs = type_item_attributes();

    parse_quote! {
        #item_attrs
        #[serde(transparent)]
        pub struct #struct_ident(pub #inner_type_ident);
    }
}

fn gen_enum_type<'ar>(
    enum_type: &EnumType<'ar>,
    child_name_source: &mut ModChildNameSource<'ar>,
) -> syn::ItemEnum {
    let enum_type_name = child_name_source.get_type_name(enum_type.name.uq_name);
    let enum_type_ident = to_ident(enum_type_name);

    let item_attrs = type_item_attributes();

    let mut item_enum: syn::ItemEnum = parse_quote! {
        #item_attrs
        pub enum #enum_type_ident {}
    };

    let mut field_name_source = FieldNameSource::new();

    for member in &enum_type.members {
        let edm_member_name = &member.name;
        let variant_name = field_name_source.get_enum_variant_name(edm_member_name);
        let variant_ident = to_ident(&variant_name);
        let variant_value = syn::LitInt::new(&format!("{}", member.value), Span::call_site());

        let serde_rename_attr = if &variant_name != edm_member_name {
            quote! {
                #[serde(rename = #edm_member_name)]
            }
        } else {
            quote! {}
        };

        let variant: syn::Variant = parse_quote! {
            #serde_rename_attr
            #variant_ident = #variant_value
        };

        item_enum.variants.push(variant);
    }

    item_enum
}

fn gen_entity_set<'ar>(
    entity_set: &EntitySet<'ar>,
    child_name_source: &mut ModChildNameSource<'ar>,
) -> syn::ItemConst {
    let entity_set_path = entity_set.name().path;
    let const_item_name = child_name_source.get_const_item_name(entity_set_path);
    let const_item_ident = to_ident(const_item_name);
    let type_name = child_name_source.get_type_name(entity_set.entity_type.get().name().uq_name);
    let type_ident = to_ident(type_name);

    parse_quote! {
        #[allow(dead_code)]
        pub const #const_item_ident: EntitySetEndpoint<#type_ident> = EntitySetEndpoint {
            service_url: SERVICE_URL,
            name: #entity_set_path,
            marker: PhantomData
        };
    }
}

fn gen_singleton<'ar>(
    singleton: &Singleton<'ar>,
    child_name_source: &mut ModChildNameSource<'ar>,
) -> syn::ItemConst {
    let singleton_path = singleton.name().path;
    let const_item_name = child_name_source.get_const_item_name(singleton_path);
    let const_item_ident = to_ident(const_item_name);
    let type_name = child_name_source.get_type_name(singleton.entity_type.get().name().uq_name);
    let type_ident = to_ident(type_name);

    parse_quote! {
        #[allow(dead_code)]
        pub const #const_item_ident: SingletonEndpoint<#type_ident> = SingletonEndpoint {
            service_url: SERVICE_URL,
            name: #singleton_path,
            marker: PhantomData
        };
    }
}

fn type_item_attributes() -> TokenStream {
    parse_quote! {
        #[serde_as(crate = "odata_client::serde_with")]
        #[derive(Debug, Deserialize)]
        #[serde(crate = "odata_client::serde")]
    }
}

fn module_imports() -> TokenStream {
    quote! {
        #[allow(unused_imports)]
        use odata_client::{
            EntityProperties,
            EntitySetEndpoint,
            ExpandQuery,
            SingletonEndpoint,
            EntityLink,
            EntityLinkStub,
            deserialize_with,
            serde_with::serde_as,
            serde::Deserialize,
            chrono::{
                FixedOffset,
                DateTime,
                NaiveDate,
                NaiveTime
            },
            iso8601,
            uuid,
        };
        use std::marker::PhantomData;
    }
}