azure_data_cosmos_macros 0.1.0

Procedural macros for the Azure Cosmos DB SDK for Rust.
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

use crate::parse::{Layer, OptionField, OptionsInput};
use crate::Result;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::{PathArguments, Type};

/// Generates the `{Name}View` struct and its accessor methods.
pub fn generate_view(input: &OptionsInput) -> Result<TokenStream> {
    let view_name = format_ident!("{}View", input.name);
    let struct_name = &input.name;
    let vis = &input.vis;

    let layers = &input.layers;
    let last_layer_idx = layers.len() - 1;

    // Build struct fields: env + explicit layers.
    // The env layer is always present so that nested Views have a uniform constructor
    // signature regardless of whether their fields use `#[option(env)]`.
    // All layers are wrapped in Option. Arc layers are Option<Arc<T>>,
    // the last (highest-priority) layer is Option<&'a T> to avoid cloning.
    let mut struct_fields = Vec::new();
    let mut new_params = Vec::new();

    struct_fields.push(quote! { env: Option<::std::sync::Arc<#struct_name>> });
    new_params.push(quote! { env: Option<::std::sync::Arc<#struct_name>> });

    for (i, layer) in layers.iter().enumerate() {
        let field_name = layer.ident();
        if i == last_layer_idx {
            // Last layer is borrowed
            struct_fields.push(quote! { #field_name: Option<&'a #struct_name> });
            new_params.push(quote! { #field_name: Option<&'a #struct_name> });
        } else {
            struct_fields.push(quote! { #field_name: Option<::std::sync::Arc<#struct_name>> });
            new_params.push(quote! { #field_name: Option<::std::sync::Arc<#struct_name>> });
        }
    }

    // Build accessor methods — env layer is always checked.
    let accessors = input
        .fields
        .iter()
        .map(|field| generate_accessor(field, layers))
        .collect::<Result<Vec<_>>>()?;

    // Build the new() constructor body
    let mut new_body_fields = Vec::new();
    new_body_fields.push(quote! { env });
    for layer in layers {
        let field_name = layer.ident();
        new_body_fields.push(quote! { #field_name });
    }

    Ok(quote! {
        /// Snapshot view across all layers for resolution.
        #[automatically_derived]
        #vis struct #view_name<'a> {
            #(#struct_fields),*
        }

        #[automatically_derived]
        impl<'a> #view_name<'a> {
            /// Creates a new view from layer snapshots.
            #vis fn new(#(#new_params),*) -> Self {
                Self {
                    #(#new_body_fields),*
                }
            }

            #(#accessors)*
        }
    })
}

fn generate_accessor(field: &OptionField, layers: &[Layer]) -> Result<TokenStream> {
    if field.nested {
        return generate_nested_accessor(field, layers);
    }

    if field.merge.is_some() {
        return generate_merge_accessor(field, layers);
    }

    generate_shadow_accessor(field, layers)
}

/// Generates a shadow accessor: returns `Option<&T>` walking highest → lowest priority.
fn generate_shadow_accessor(field: &OptionField, layers: &[Layer]) -> Result<TokenStream> {
    let field_name = &field.ident;
    let inner_type = &field.inner_type;
    let last_layer_idx = layers.len() - 1;

    // Build the chain: operation → account → runtime → env
    // Layers are stored in order [runtime, account, operation], so we walk in reverse.
    // Each layer is Option<...>, so we unwrap with and_then.
    let mut chain_parts = Vec::new();

    for (i, layer) in layers.iter().enumerate().rev() {
        let layer_name = layer.ident();
        if i == last_layer_idx {
            // Bottom layer is Option<&'a T> — unwrap directly
            chain_parts.push(quote! {
                self.#layer_name.and_then(|l| l.#field_name.as_ref())
            });
        } else {
            // Arc layer is Option<Arc<T>> — unwrap with as_ref first
            chain_parts.push(quote! {
                self.#layer_name.as_ref().and_then(|l| l.#field_name.as_ref())
            });
        }
    }

    chain_parts.push(quote! {
        self.env.as_ref().and_then(|l| l.#field_name.as_ref())
    });

    // Build the chain with .or()
    let first = &chain_parts[0];
    let rest = &chain_parts[1..];

    let chain = rest
        .iter()
        .fold(first.clone(), |acc, part| quote! { #acc.or(#part) });

    Ok(quote! {
        /// Resolves this field across layers (highest priority first).
        pub fn #field_name(&self) -> Option<&#inner_type> {
            #chain
        }
    })
}

/// Generates a merge accessor for `#[option(merge = "extend")]` fields.
fn generate_merge_accessor(field: &OptionField, layers: &[Layer]) -> Result<TokenStream> {
    let field_name = &field.ident;
    let inner_type = &field.inner_type;
    let last_layer_idx = layers.len() - 1;

    // Merge from lowest to highest priority (env → runtime → account → operation).
    // Each layer is Optional, so we unwrap before checking the field.
    let mut extend_stmts = Vec::new();

    extend_stmts.push(quote! {
        if let Some(ref env) = self.env {
            if let Some(ref v) = env.#field_name {
                merged.extend(v.clone());
            }
        }
    });

    for (i, layer) in layers.iter().enumerate() {
        let layer_name = layer.ident();
        if i == last_layer_idx {
            // Bottom layer is Option<&'a T>
            extend_stmts.push(quote! {
                if let Some(#layer_name) = self.#layer_name {
                    if let Some(ref v) = #layer_name.#field_name {
                        merged.extend(v.clone());
                    }
                }
            });
        } else {
            // Arc layer is Option<Arc<T>>
            extend_stmts.push(quote! {
                if let Some(ref #layer_name) = self.#layer_name {
                    if let Some(ref v) = #layer_name.#field_name {
                        merged.extend(v.clone());
                    }
                }
            });
        }
    }

    Ok(quote! {
        /// Merges this field across all layers (lowest priority first).
        pub fn #field_name(&self) -> #inner_type {
            let mut merged = <#inner_type>::default();
            #(#extend_stmts)*
            merged
        }
    })
}

/// Generates a nested accessor that delegates to a child View.
fn generate_nested_accessor(field: &OptionField, layers: &[Layer]) -> Result<TokenStream> {
    let field_name = &field.ident;
    let inner_type = &field.inner_type;
    let view_path = nested_view_path(inner_type)?;
    let last_layer_idx = layers.len() - 1;

    // Build arguments for the child View's new().
    // The env arg is always passed — all Views uniformly accept it.
    // Arc layers extract the nested field and clone into a new Arc.
    // The bottom layer borrows the nested field (no clone).
    // All results are Option — None when the parent layer or nested field is absent.
    let mut new_args = Vec::new();

    new_args.push(quote! {
        self.env.as_ref()
            .and_then(|l| l.#field_name.as_ref())
            .map(|v| ::std::sync::Arc::new(v.clone()))
    });

    for (i, layer) in layers.iter().enumerate() {
        let layer_name = layer.ident();
        if i == last_layer_idx {
            // Bottom layer is Option<&'a T> — borrow the nested field
            new_args.push(quote! {
                self.#layer_name.and_then(|l| l.#field_name.as_ref())
            });
        } else {
            // Arc layer — extract nested field and clone into a new Arc
            new_args.push(quote! {
                self.#layer_name.as_ref()
                    .and_then(|l| l.#field_name.as_ref())
                    .map(|v| ::std::sync::Arc::new(v.clone()))
            });
        }
    }

    Ok(quote! {
        /// Returns a child View for the nested option group.
        pub fn #field_name(&self) -> #view_path<'_> {
            #view_path::new(#(#new_args),*)
        }
    })
}

/// Constructs the View type path from a nested inner type.
///
/// Given `NestedOpts`, returns the path `NestedOptsView`.
/// Given `inner::NestedOpts`, returns the path `inner::NestedOptsView`.
fn nested_view_path(inner_type: &Type) -> Result<syn::Path> {
    match inner_type {
        Type::Path(type_path) if type_path.qself.is_none() => {
            let mut path = type_path.path.clone();
            let last_seg = path.segments.last_mut().ok_or_else(|| {
                syn::Error::new_spanned(
                    inner_type,
                    "nested type must have at least one path segment",
                )
            })?;
            last_seg.ident = format_ident!("{}View", last_seg.ident);
            last_seg.arguments = PathArguments::None;
            Ok(path)
        }
        _ => Err(syn::Error::new_spanned(
            inner_type,
            "nested option type must be a simple path type",
        )),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parse::OptionsInput;
    use quote::quote;

    #[test]
    fn view_generated_for_three_layers() {
        let input: syn::DeriveInput = syn::parse_quote! {
            #[options(layers(runtime, account, operation))]
            pub struct RequestOptions {
                pub consistency_level: Option<String>,
                pub throughput_bucket: Option<usize>,
            }
        };
        let parsed = OptionsInput::from_derive_input(&input).unwrap();
        let tokens = generate_view(&parsed).unwrap();

        let expected = quote! {
            /// Snapshot view across all layers for resolution.
            #[automatically_derived]
            pub struct RequestOptionsView<'a> {
                env: Option<::std::sync::Arc<RequestOptions>>,
                runtime: Option<::std::sync::Arc<RequestOptions>>,
                account: Option<::std::sync::Arc<RequestOptions>>,
                operation: Option<&'a RequestOptions>
            }

            #[automatically_derived]
            impl<'a> RequestOptionsView<'a> {
                /// Creates a new view from layer snapshots.
                pub fn new(
                    env: Option<::std::sync::Arc<RequestOptions>>,
                    runtime: Option<::std::sync::Arc<RequestOptions>>,
                    account: Option<::std::sync::Arc<RequestOptions>>,
                    operation: Option<&'a RequestOptions>
                ) -> Self {
                    Self { env, runtime, account, operation }
                }

                /// Resolves this field across layers (highest priority first).
                pub fn consistency_level(&self) -> Option<&String> {
                    self.operation.and_then(|l| l.consistency_level.as_ref())
                        .or(self.account.as_ref().and_then(|l| l.consistency_level.as_ref()))
                        .or(self.runtime.as_ref().and_then(|l| l.consistency_level.as_ref()))
                        .or(self.env.as_ref().and_then(|l| l.consistency_level.as_ref()))
                }

                /// Resolves this field across layers (highest priority first).
                pub fn throughput_bucket(&self) -> Option<&usize> {
                    self.operation.and_then(|l| l.throughput_bucket.as_ref())
                        .or(self.account.as_ref().and_then(|l| l.throughput_bucket.as_ref()))
                        .or(self.runtime.as_ref().and_then(|l| l.throughput_bucket.as_ref()))
                        .or(self.env.as_ref().and_then(|l| l.throughput_bucket.as_ref()))
                }
            }
        };

        assert_eq!(expected.to_string(), tokens.to_string());
    }

    #[test]
    fn view_generated_for_two_layers() {
        let input: syn::DeriveInput = syn::parse_quote! {
            #[options(layers(runtime, account))]
            pub struct ConnectionOptions {
                pub request_timeout: Option<u64>,
            }
        };
        let parsed = OptionsInput::from_derive_input(&input).unwrap();
        let tokens = generate_view(&parsed).unwrap();

        let expected = quote! {
            /// Snapshot view across all layers for resolution.
            #[automatically_derived]
            pub struct ConnectionOptionsView<'a> {
                env: Option<::std::sync::Arc<ConnectionOptions>>,
                runtime: Option<::std::sync::Arc<ConnectionOptions>>,
                account: Option<&'a ConnectionOptions>
            }

            #[automatically_derived]
            impl<'a> ConnectionOptionsView<'a> {
                /// Creates a new view from layer snapshots.
                pub fn new(
                    env: Option<::std::sync::Arc<ConnectionOptions>>,
                    runtime: Option<::std::sync::Arc<ConnectionOptions>>,
                    account: Option<&'a ConnectionOptions>
                ) -> Self {
                    Self { env, runtime, account }
                }

                /// Resolves this field across layers (highest priority first).
                pub fn request_timeout(&self) -> Option<&u64> {
                    self.account.and_then(|l| l.request_timeout.as_ref())
                        .or(self.runtime.as_ref().and_then(|l| l.request_timeout.as_ref()))
                        .or(self.env.as_ref().and_then(|l| l.request_timeout.as_ref()))
                }
            }
        };

        assert_eq!(expected.to_string(), tokens.to_string());
    }

    #[test]
    fn view_includes_env_field_when_env_attr_present() {
        let input: syn::DeriveInput = syn::parse_quote! {
            #[options(layers(runtime, account))]
            pub struct TestOptions {
                #[option(env = "MY_VAR")]
                pub my_field: Option<String>,
            }
        };
        let parsed = OptionsInput::from_derive_input(&input).unwrap();
        let tokens = generate_view(&parsed).unwrap();

        let expected = quote! {
            /// Snapshot view across all layers for resolution.
            #[automatically_derived]
            pub struct TestOptionsView<'a> {
                env: Option<::std::sync::Arc<TestOptions>>,
                runtime: Option<::std::sync::Arc<TestOptions>>,
                account: Option<&'a TestOptions>
            }

            #[automatically_derived]
            impl<'a> TestOptionsView<'a> {
                /// Creates a new view from layer snapshots.
                pub fn new(
                    env: Option<::std::sync::Arc<TestOptions>>,
                    runtime: Option<::std::sync::Arc<TestOptions>>,
                    account: Option<&'a TestOptions>
                ) -> Self {
                    Self { env, runtime, account }
                }

                /// Resolves this field across layers (highest priority first).
                pub fn my_field(&self) -> Option<&String> {
                    self.account.and_then(|l| l.my_field.as_ref())
                        .or(self.runtime.as_ref().and_then(|l| l.my_field.as_ref()))
                        .or(self.env.as_ref().and_then(|l| l.my_field.as_ref()))
                }
            }
        };

        assert_eq!(expected.to_string(), tokens.to_string());
    }

    #[test]
    fn view_merge_accessor_generated() {
        let input: syn::DeriveInput = syn::parse_quote! {
            #[options(layers(runtime, account))]
            pub struct TestOptions {
                #[option(merge = "extend")]
                pub headers: Option<Vec<String>>,
            }
        };
        let parsed = OptionsInput::from_derive_input(&input).unwrap();
        let tokens = generate_view(&parsed).unwrap();

        let inner_type: syn::Type = syn::parse_quote!(Vec<String>);
        let expected = quote! {
            /// Snapshot view across all layers for resolution.
            #[automatically_derived]
            pub struct TestOptionsView<'a> {
                env: Option<::std::sync::Arc<TestOptions>>,
                runtime: Option<::std::sync::Arc<TestOptions>>,
                account: Option<&'a TestOptions>
            }

            #[automatically_derived]
            impl<'a> TestOptionsView<'a> {
                /// Creates a new view from layer snapshots.
                pub fn new(
                    env: Option<::std::sync::Arc<TestOptions>>,
                    runtime: Option<::std::sync::Arc<TestOptions>>,
                    account: Option<&'a TestOptions>
                ) -> Self {
                    Self { env, runtime, account }
                }

                /// Merges this field across all layers (lowest priority first).
                pub fn headers(&self) -> Vec<String> {
                    let mut merged = <#inner_type>::default();
                    if let Some(ref env) = self.env {
                        if let Some(ref v) = env.headers {
                            merged.extend(v.clone());
                        }
                    }
                    if let Some(ref runtime) = self.runtime {
                        if let Some(ref v) = runtime.headers {
                            merged.extend(v.clone());
                        }
                    }
                    if let Some(account) = self.account {
                        if let Some(ref v) = account.headers {
                            merged.extend(v.clone());
                        }
                    }
                    merged
                }
            }
        };

        assert_eq!(expected.to_string(), tokens.to_string());
    }

    #[test]
    fn view_nested_accessor_with_qualified_path() {
        let input: syn::DeriveInput = syn::parse_quote! {
            #[options(layers(runtime, account))]
            pub struct TestOptions {
                #[option(nested)]
                pub child: Option<inner::ChildOptions>,
            }
        };
        let parsed = OptionsInput::from_derive_input(&input).unwrap();
        let tokens = generate_view(&parsed).unwrap();

        let expected = quote! {
            /// Snapshot view across all layers for resolution.
            #[automatically_derived]
            pub struct TestOptionsView<'a> {
                env: Option<::std::sync::Arc<TestOptions>>,
                runtime: Option<::std::sync::Arc<TestOptions>>,
                account: Option<&'a TestOptions>
            }

            #[automatically_derived]
            impl<'a> TestOptionsView<'a> {
                /// Creates a new view from layer snapshots.
                pub fn new(
                    env: Option<::std::sync::Arc<TestOptions>>,
                    runtime: Option<::std::sync::Arc<TestOptions>>,
                    account: Option<&'a TestOptions>
                ) -> Self {
                    Self { env, runtime, account }
                }

                /// Returns a child View for the nested option group.
                pub fn child(&self) -> inner::ChildOptionsView<'_> {
                    inner::ChildOptionsView::new(
                        self.env.as_ref()
                            .and_then(|l| l.child.as_ref())
                            .map(|v| ::std::sync::Arc::new(v.clone())),
                        self.runtime.as_ref()
                            .and_then(|l| l.child.as_ref())
                            .map(|v| ::std::sync::Arc::new(v.clone())),
                        self.account.and_then(|l| l.child.as_ref())
                    )
                }
            }
        };

        assert_eq!(expected.to_string(), tokens.to_string());
    }

    #[test]
    fn view_nested_accessor_with_simple_path() {
        let input: syn::DeriveInput = syn::parse_quote! {
            #[options(layers(runtime, account))]
            pub struct TestOptions {
                #[option(nested)]
                pub child: Option<ChildOptions>,
            }
        };
        let parsed = OptionsInput::from_derive_input(&input).unwrap();
        let tokens = generate_view(&parsed).unwrap();

        let expected = quote! {
            /// Snapshot view across all layers for resolution.
            #[automatically_derived]
            pub struct TestOptionsView<'a> {
                env: Option<::std::sync::Arc<TestOptions>>,
                runtime: Option<::std::sync::Arc<TestOptions>>,
                account: Option<&'a TestOptions>
            }

            #[automatically_derived]
            impl<'a> TestOptionsView<'a> {
                /// Creates a new view from layer snapshots.
                pub fn new(
                    env: Option<::std::sync::Arc<TestOptions>>,
                    runtime: Option<::std::sync::Arc<TestOptions>>,
                    account: Option<&'a TestOptions>
                ) -> Self {
                    Self { env, runtime, account }
                }

                /// Returns a child View for the nested option group.
                pub fn child(&self) -> ChildOptionsView<'_> {
                    ChildOptionsView::new(
                        self.env.as_ref()
                            .and_then(|l| l.child.as_ref())
                            .map(|v| ::std::sync::Arc::new(v.clone())),
                        self.runtime.as_ref()
                            .and_then(|l| l.child.as_ref())
                            .map(|v| ::std::sync::Arc::new(v.clone())),
                        self.account.and_then(|l| l.child.as_ref())
                    )
                }
            }
        };

        assert_eq!(expected.to_string(), tokens.to_string());
    }
}