-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathstruct.rs
394 lines (344 loc) · 15.4 KB
/
struct.rs
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
use std::ops::Not;
use darling::{util::IdentString, Error, FromAttributes, Result};
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{parse_quote, Generics, ItemStruct, Path, Visibility};
use crate::{
attrs::container::NestedContainerAttributes,
codegen::{
changes::Neighbors,
container::{CommonContainerData, Container, ContainerIdents, ContainerOptions},
item::VersionedField,
ItemStatus, StandaloneContainerAttributes, VersionDefinition,
},
utils::VersionExt,
};
impl Container {
pub(crate) fn new_standalone_struct(
item_struct: ItemStruct,
attributes: StandaloneContainerAttributes,
versions: &[VersionDefinition],
) -> Result<Self> {
// NOTE (@Techassi): Should we check if the fields are named here?
let mut versioned_fields = Vec::new();
for field in item_struct.fields {
let mut versioned_field = VersionedField::new(field, versions)?;
versioned_field.insert_container_versions(versions);
versioned_fields.push(versioned_field);
}
let kubernetes_options = attributes.kubernetes_arguments.map(Into::into);
let idents = ContainerIdents::from(item_struct.ident, kubernetes_options.as_ref());
// Validate K8s specific requirements
// Ensure that the struct name includes the 'Spec' suffix.
if kubernetes_options.is_some() && !idents.original.as_str().ends_with("Spec") {
return Err(Error::custom(
"struct name needs to include the `Spec` suffix if Kubernetes features are enabled via `#[versioned(k8s())]`"
).with_span(&idents.original.span()));
}
let options = ContainerOptions {
skip_from: attributes
.common
.options
.skip
.is_some_and(|s| s.from.is_present()),
kubernetes_options,
};
let common = CommonContainerData {
original_attributes: item_struct.attrs,
options,
idents,
};
Ok(Self::Struct(Struct {
generics: item_struct.generics,
fields: versioned_fields,
common,
}))
}
// TODO (@Techassi): See what can be unified into a single 'new' function
pub(crate) fn new_struct_nested(
item_struct: ItemStruct,
versions: &[VersionDefinition],
) -> Result<Self> {
let attributes = NestedContainerAttributes::from_attributes(&item_struct.attrs)?;
let mut versioned_fields = Vec::new();
for field in item_struct.fields {
let mut versioned_field = VersionedField::new(field, versions)?;
versioned_field.insert_container_versions(versions);
versioned_fields.push(versioned_field);
}
let kubernetes_options = attributes.kubernetes_arguments.map(Into::into);
let idents = ContainerIdents::from(item_struct.ident, kubernetes_options.as_ref());
// Validate K8s specific requirements
// Ensure that the struct name includes the 'Spec' suffix.
if kubernetes_options.is_some() && !idents.original.as_str().ends_with("Spec") {
return Err(Error::custom(
"struct name needs to include the `Spec` suffix if Kubernetes features are enabled via `#[versioned(k8s())]`"
).with_span(&idents.original.span()));
}
let options = ContainerOptions {
skip_from: attributes.options.skip.is_some_and(|s| s.from.is_present()),
kubernetes_options,
};
// Nested structs
// We need to filter out the `versioned` attribute, because these are not directly processed
// by darling, but instead by us (using darling). For this reason, darling won't remove the
// attribute from the input and as such, we need to filter it out ourself.
let original_attributes = item_struct
.attrs
.into_iter()
.filter(|attr| !attr.meta.path().is_ident("versioned"))
.collect();
let common = CommonContainerData {
original_attributes,
options,
idents,
};
Ok(Self::Struct(Struct {
generics: item_struct.generics,
fields: versioned_fields,
common,
}))
}
}
/// A versioned struct.
pub(crate) struct Struct {
/// List of fields defined in the original struct. How, and if, an item
/// should generate code, is decided by the currently generated version.
pub fields: Vec<VersionedField>,
/// Common container data which is shared between structs and enums.
pub common: CommonContainerData,
/// Generic types of the struct
pub generics: Generics,
}
// Common token generation
impl Struct {
/// Generates code for the struct definition.
pub(crate) fn generate_definition(&self, version: &VersionDefinition) -> TokenStream {
let where_clause = self.generics.where_clause.as_ref();
let type_generics = &self.generics;
let original_attributes = &self.common.original_attributes;
let ident = &self.common.idents.original;
let version_docs = &version.docs;
let mut fields = TokenStream::new();
for field in &self.fields {
fields.extend(field.generate_for_container(version));
}
// This only returns Some, if K8s features are enabled
let kube_attribute = self.generate_kube_attribute(version);
quote! {
#(#[doc = #version_docs])*
#(#original_attributes)*
#kube_attribute
pub struct #ident #type_generics #where_clause {
#fields
}
}
}
/// Generates code for the `From<Version> for NextVersion` implementation.
pub(crate) fn generate_from_impl(
&self,
version: &VersionDefinition,
next_version: Option<&VersionDefinition>,
add_attributes: bool,
) -> Option<TokenStream> {
if version.skip_from || self.common.options.skip_from {
return None;
}
match next_version {
Some(next_version) => {
// TODO (@Techassi): Support generic types which have been removed in newer versions,
// but need to exist for older versions How do we represent that? Because the
// defined struct always represents the latest version. I guess we could generally
// advise against using generic types, but if you have to, avoid removing it in
// later versions.
let (impl_generics, type_generics, where_clause) = self.generics.split_for_impl();
let struct_ident = &self.common.idents.original;
let from_struct_ident = &self.common.idents.from;
let for_module_ident = &next_version.ident;
let from_module_ident = &version.ident;
let fields = self.generate_from_fields(version, next_version, from_struct_ident);
// Include allow(deprecated) only when this or the next version is
// deprecated. Also include it, when a field in this or the next
// version is deprecated.
let allow_attribute = (version.deprecated.is_some()
|| next_version.deprecated.is_some()
|| self.is_any_field_deprecated(version)
|| self.is_any_field_deprecated(next_version))
.then(|| quote! { #[allow(deprecated)] });
// Only add the #[automatically_derived] attribute only if this impl is used
// outside of a module (in standalone mode).
let automatically_derived = add_attributes
.not()
.then(|| quote! {#[automatically_derived]});
Some(quote! {
#automatically_derived
#allow_attribute
impl #impl_generics ::std::convert::From<#from_module_ident::#struct_ident #type_generics> for #for_module_ident::#struct_ident #type_generics
#where_clause
{
fn from(#from_struct_ident: #from_module_ident::#struct_ident #type_generics) -> Self {
Self {
#fields
}
}
}
})
}
None => None,
}
}
/// Generates code for struct fields used in `From` implementations.
fn generate_from_fields(
&self,
version: &VersionDefinition,
next_version: &VersionDefinition,
from_struct_ident: &IdentString,
) -> TokenStream {
let mut tokens = TokenStream::new();
for field in &self.fields {
tokens.extend(field.generate_for_from_impl(version, next_version, from_struct_ident));
}
tokens
}
/// Returns whether any field is deprecated in the provided `version`.
fn is_any_field_deprecated(&self, version: &VersionDefinition) -> bool {
// First, iterate over all fields. The `any` function will return true
// if any of the function invocations return true. If a field doesn't
// have a chain, we can safely default to false (unversioned fields
// cannot be deprecated). Then we retrieve the status of the field and
// ensure it is deprecated.
self.fields.iter().any(|f| {
f.changes.as_ref().is_some_and(|c| {
c.value_is(&version.inner, |a| {
matches!(
a,
ItemStatus::Deprecation { .. }
| ItemStatus::NoChange {
previously_deprecated: true,
..
}
)
})
})
})
}
}
// Kubernetes-specific token generation
impl Struct {
pub(crate) fn generate_kube_attribute(
&self,
version: &VersionDefinition,
) -> Option<TokenStream> {
match &self.common.options.kubernetes_options {
Some(kubernetes_options) => {
// Required arguments
let group = &kubernetes_options.group;
let version = version.inner.to_string();
let kind = kubernetes_options
.kind
.as_ref()
.map_or(self.common.idents.kubernetes.to_string(), |kind| {
kind.clone()
});
// Optional arguments
let singular = kubernetes_options
.singular
.as_ref()
.map(|s| quote! { , singular = #s });
let plural = kubernetes_options
.plural
.as_ref()
.map(|p| quote! { , plural = #p });
let namespaced = kubernetes_options
.namespaced
.then_some(quote! { , namespaced });
let crates = kubernetes_options.crates.to_token_stream();
let status = kubernetes_options
.status
.as_ref()
.map(|s| quote! { , status = #s });
let shortnames: TokenStream = kubernetes_options
.shortnames
.iter()
.map(|s| quote! { , shortname = #s })
.collect();
Some(quote! {
// The end-developer needs to derive CustomResource and JsonSchema.
// This is because we don't know if they want to use a re-exported or renamed import.
#[kube(
// These must be comma separated (except the last) as they always exist:
group = #group, version = #version, kind = #kind
// These fields are optional, and therefore the token stream must prefix each with a comma:
#singular #plural #namespaced #crates #status #shortnames
)]
})
}
None => None,
}
}
pub(crate) fn generate_kubernetes_item(
&self,
version: &VersionDefinition,
) -> Option<(IdentString, String, TokenStream)> {
match &self.common.options.kubernetes_options {
Some(options) if !options.skip_merged_crd => {
let kube_core_path = &*options.crates.kube_core;
let enum_variant_ident = version.inner.as_variant_ident();
let enum_variant_string = version.inner.to_string();
let struct_ident = &self.common.idents.kubernetes;
let module_ident = &version.ident;
let qualified_path: Path = parse_quote!(#module_ident::#struct_ident);
let merge_crds_fn_call = quote! {
<#qualified_path as #kube_core_path::CustomResourceExt>::crd()
};
Some((enum_variant_ident, enum_variant_string, merge_crds_fn_call))
}
_ => None,
}
}
pub(crate) fn generate_kubernetes_merge_crds(
&self,
enum_variant_idents: &[IdentString],
enum_variant_strings: &[String],
fn_calls: &[TokenStream],
vis: &Visibility,
is_nested: bool,
) -> Option<TokenStream> {
match &self.common.options.kubernetes_options {
Some(kubernetes_options) if !kubernetes_options.skip_merged_crd => {
let enum_ident = &self.common.idents.kubernetes;
// Only add the #[automatically_derived] attribute if this impl is used outside of a
// module (in standalone mode).
let automatically_derived =
is_nested.not().then(|| quote! {#[automatically_derived]});
// Get the crate paths
let k8s_openapi_path = &*kubernetes_options.crates.k8s_openapi;
let kube_core_path = &*kubernetes_options.crates.kube_core;
Some(quote! {
#automatically_derived
#vis enum #enum_ident {
#(#enum_variant_idents),*
}
#automatically_derived
impl ::std::fmt::Display for #enum_ident {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::result::Result<(), ::std::fmt::Error> {
match self {
#(Self::#enum_variant_idents => f.write_str(#enum_variant_strings)),*
}
}
}
#automatically_derived
impl #enum_ident {
/// Generates a merged CRD containing all versions and marking `stored_apiversion` as stored.
pub fn merged_crd(
stored_apiversion: Self
) -> ::std::result::Result<#k8s_openapi_path::apiextensions_apiserver::pkg::apis::apiextensions::v1::CustomResourceDefinition, #kube_core_path::crd::MergeError> {
#kube_core_path::crd::merge_crds(vec![#(#fn_calls),*], &stored_apiversion.to_string())
}
}
})
}
_ => None,
}
}
}