-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathmod.rs
More file actions
482 lines (424 loc) · 18.7 KB
/
Copy pathmod.rs
File metadata and controls
482 lines (424 loc) · 18.7 KB
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
use std::{collections::BTreeMap, ops::Deref};
use darling::{Error, FromMeta, Result, util::SpannedValue};
use k8s_version::Version;
use proc_macro2::Span;
use quote::format_ident;
use syn::{Attribute, Path, Type, spanned::Spanned};
use crate::{
codegen::{VersionDefinition, item::ItemStatus},
utils::ItemIdents,
};
mod field;
pub use field::*;
mod variant;
pub use variant::*;
/// These attributes are meant to be used in super structs, which add
/// [`Field`](syn::Field) or [`Variant`](syn::Variant) specific attributes via
/// darling's flatten feature. This struct only provides shared attributes.
///
/// ### Shared Item Rules
///
/// - An item can only ever be added once at most. An item not marked as 'added'
/// is part of the container in every version until changed or deprecated.
/// - An item can be changed many times. That's why changes are stored in a
/// [`Vec`].
/// - An item can only be deprecated once. A field or variant not marked as
/// 'deprecated' will be included up until the latest version.
#[derive(Debug, FromMeta)]
pub struct CommonItemAttributes {
/// This parses the `added` attribute on items (fields or variants). It can
/// only be present at most once.
pub added: Option<AddedAttributes>,
/// This parses the `changed` attribute on items (fields or variants). It
/// can be present 0..n times.
#[darling(multiple, rename = "changed")]
pub changes: Vec<ChangedAttributes>,
/// This parses the `deprecated` attribute on items (fields or variants). It
/// can only be present at most once.
pub deprecated: Option<DeprecatedAttributes>,
}
// This impl block ONLY contains validation. The main entrypoint is the associated 'validate'
// function. In addition to validate functions which are called directly during darling's parsing,
// it contains functions which can only be called after the initial parsing and validation because
// they need additional context, namely the list of versions defined on the container or module.
impl CommonItemAttributes {
pub fn validate(&self, item_idents: impl ItemIdents, item_attrs: &[Attribute]) -> Result<()> {
let mut errors = Error::accumulator();
errors.handle(self.validate_action_combinations(&item_idents));
errors.handle(self.validate_action_order(&item_idents));
errors.handle(self.validate_item_name(&item_idents));
errors.handle(self.validate_added_action());
errors.handle(self.validate_changed_action(&item_idents));
errors.handle(self.validate_item_attributes(item_attrs));
errors.finish()
}
pub fn validate_versions(&self, versions: &[VersionDefinition]) -> Result<()> {
let mut errors = Error::accumulator();
if let Some(added) = &self.added {
if !versions.iter().any(|v| v.inner == *added.since) {
errors.push(Error::custom(
"the `added` action uses a version which is not declared via `#[versioned(version)]`",
).with_span(&added.since.span()));
}
}
for change in &self.changes {
if !versions.iter().any(|v| v.inner == *change.since) {
errors.push(Error::custom(
"the `changed` action uses a version which is not declared via `#[versioned(version)]`"
).with_span(&change.since.span()));
}
}
if let Some(deprecated) = &self.deprecated {
if !versions.iter().any(|v| v.inner == *deprecated.since) {
errors.push(Error::custom(
"the `deprecated` action uses a version which is not declared via `#[versioned(version)]`",
).with_span(&deprecated.since.span()));
}
}
errors.finish()
}
/// This associated function is called by the top-level validation function
/// and validates that each item uses a valid combination of actions.
/// Invalid combinations are:
///
/// - `added` and `deprecated` using the same version: A field or variant
/// cannot be marked as added in a particular version and then marked as
/// deprecated immediately after. Fields and variants must be included for
/// at least one version before being marked deprecated.
/// - `added` and `changed` using the same version: The same reasoning from
/// above applies here as well. Fields and variants must be included for
/// at least one version before being changed.
/// - `changed` and `deprecated` using the same version: Again, the same
/// rules from above apply here as well.
fn validate_action_combinations(&self, item_idents: &impl ItemIdents) -> Result<()> {
match (&self.added, &self.changes, &self.deprecated) {
(Some(added), _, Some(deprecated)) if *added.since == *deprecated.since => Err(
Error::custom("cannot be marked as `added` and `deprecated` in the same version")
.with_span(item_idents.original()),
),
(Some(added), changed, _) if changed.iter().any(|r| *r.since == *added.since) => Err(
Error::custom("cannot be marked as `added` and `changed` in the same version")
.with_span(item_idents.original()),
),
(_, changed, Some(deprecated))
if changed.iter().any(|r| *r.since == *deprecated.since) =>
{
Err(Error::custom(
"cannot be marked as `deprecated` and `changed` in the same version",
)
.with_span(item_idents.original()))
}
_ => Ok(()),
}
}
/// This associated function is called by the top-level validation function
/// and validates that actions use a chronologically sound chain of
/// versions.
///
/// The following rules apply:
///
/// - `deprecated` must use a greater version than `added`: This function
/// ensures that these versions are chronologically sound, that means,
/// that the version of the deprecated action must be greater than the
/// version of the added action.
/// - All `changed` actions must use a greater version than `added` but a
/// lesser version than `deprecated`.
fn validate_action_order(&self, item_idents: &impl ItemIdents) -> Result<()> {
let added_version = self.added.as_ref().map(|a| *a.since);
let deprecated_version = self.deprecated.as_ref().map(|d| *d.since);
// First, validate that the added version is less than the deprecated
// version.
// NOTE (@Techassi): Is this already covered by the code below?
if let (Some(added_version), Some(deprecated_version)) = (added_version, deprecated_version)
{
if added_version > deprecated_version {
return Err(Error::custom(format!(
"cannot marked as `added` in version `{added_version}` while being marked as `deprecated` in an earlier version `{deprecated_version}`"
)).with_span(item_idents.original()));
}
}
// Now, iterate over all changes and ensure that their versions are
// between the added and deprecated version.
if !self.changes.iter().all(|r| {
added_version.is_none_or(|a| a < *r.since)
&& deprecated_version.is_none_or(|d| d > *r.since)
}) {
return Err(Error::custom(
"all changes must use versions higher than `added` and lower than `deprecated`",
)
.with_span(item_idents.original()));
}
Ok(())
}
/// This associated function is called by the top-level validation function
/// and validates that items use correct names depending on attached
/// actions.
///
/// The following naming rules apply:
///
/// - Fields or variants marked as deprecated need to include the
/// deprecation prefix in their name. The prefix must not be included for
/// fields or variants which are not deprecated.
fn validate_item_name(&self, item_idents: &impl ItemIdents) -> Result<()> {
let starts_with_deprecated = item_idents.starts_with_deprecation_prefix();
if self.deprecated.is_some() && !starts_with_deprecated {
return Err(Error::custom(format!(
"marked as `deprecated` and thus must include the `{deprecation_prefix}` prefix",
deprecation_prefix = item_idents.deprecation_prefix()
))
.with_span(item_idents.original()));
}
if self.deprecated.is_none() && starts_with_deprecated {
return Err(Error::custom(format!(
"not marked as `deprecated` and thus must not include the `{deprecation_prefix}` prefix",
deprecation_prefix = item_idents.deprecation_prefix()
)).with_span(item_idents.original()));
}
Ok(())
}
/// This associated function is called by the top-level validation function
/// and validates that parameters provided to the `added` actions are
/// valid.
fn validate_added_action(&self) -> Result<()> {
// NOTE (@Techassi): Can the path actually be empty?
if let Some(added) = &self.added {
if added.default_fn.segments.is_empty() {
return Err(Error::custom("`default_fn` cannot be empty")
.with_span(&added.default_fn.span()));
}
}
Ok(())
}
/// This associated function is called by the top-level validation function
/// and validates that parameters provided to the `changed` actions are
/// valid.
fn validate_changed_action(&self, item_ident: &impl ItemIdents) -> Result<()> {
let mut errors = Error::accumulator();
for change in &self.changes {
if change.from_name.is_none() && change.from_type.is_none() {
errors.push(Error::custom(
"both `from_name` and `from_type` are unset. Is this `changed()` action needed?"
).with_span(&change.since.span()));
}
// This ensures that `from_name` doesn't include the deprecation prefix.
if let Some(from_name) = change.from_name.as_ref() {
if from_name.starts_with(item_ident.deprecation_prefix()) {
errors.push(
Error::custom(
"the previous name must not start with the deprecation prefix",
)
.with_span(&from_name.span()),
);
}
}
if change.from_type.is_none() {
// The upgrade_with argument only makes sense to use when the
// type changed
if let Some(upgrade_func) = change.upgrade_with.as_ref() {
errors.push(
Error::custom(
"the `upgrade_with` argument must be used in combination with `from_type`",
)
.with_span(&upgrade_func.span()),
);
}
// The downgrade_with argument only makes sense to use when the
// type changed
if let Some(downgrade_func) = change.downgrade_with.as_ref() {
errors.push(
Error::custom(
"the `downgrade_with` argument must be used in combination with `from_type`",
)
.with_span(&downgrade_func.span()),
);
}
}
}
errors.finish()
}
/// This associated function is called by the top-level validation function
/// and validates that disallowed item attributes are not used.
///
/// The following naming rules apply:
///
/// - `deprecated` must not be set on items. Instead, use the `deprecated()`
/// action of the `#[versioned()]` macro.
fn validate_item_attributes(&self, item_attrs: &[Attribute]) -> Result<()> {
for attr in item_attrs {
for segment in &attr.path().segments {
if segment.ident == "deprecated" {
return Err(Error::custom("deprecation must be done using `#[versioned(deprecated(since = \"VERSION\"))]`")
.with_span(&attr.span()));
}
}
}
Ok(())
}
}
impl CommonItemAttributes {
pub fn into_changeset(
self,
idents: &impl ItemIdents,
ty: Type,
) -> Option<BTreeMap<Version, ItemStatus>> {
// TODO (@Techassi): Use Change instead of ItemStatus
if let Some(deprecated) = self.deprecated {
let deprecated_ident = idents.original();
// When the item is deprecated, any change which occurred beforehand
// requires access to the item ident to infer the item ident for
// the latest change.
let mut ident = idents.cleaned().clone();
let mut ty = ty;
let mut actions = BTreeMap::new();
actions.insert(
*deprecated.since,
ItemStatus::Deprecation {
previous_ident: ident.clone(),
ident: deprecated_ident.clone(),
note: deprecated.note.as_deref().cloned(),
},
);
for change in self.changes.iter().rev() {
let from_ident = if let Some(from) = change.from_name.as_deref() {
format_ident!("{from}").into()
} else {
ident.clone()
};
// TODO (@Techassi): This is an awful lot of cloning, can we get
// rid of it?
let from_ty = change
.from_type
.as_ref()
.map(|sv| sv.deref().clone())
.unwrap_or(ty.clone());
actions.insert(
*change.since,
ItemStatus::Change {
downgrade_with: change.downgrade_with.as_deref().cloned(),
upgrade_with: change.upgrade_with.as_deref().cloned(),
from_ident: from_ident.clone(),
from_type: Box::new(from_ty.clone()),
to_ident: ident,
to_type: Box::new(ty),
},
);
ident = from_ident;
ty = from_ty;
}
// After the last iteration above (if any) we use the ident for the
// added action if there is any.
if let Some(added) = self.added {
actions.insert(
*added.since,
ItemStatus::Addition {
default_fn: added.default_fn.deref().clone(),
ident,
ty: Box::new(ty),
},
);
}
Some(actions)
} else if !self.changes.is_empty() {
let mut ident = idents.original().clone();
let mut ty = ty;
let mut actions = BTreeMap::new();
for change in self.changes.iter().rev() {
let from_ident = if let Some(from) = change.from_name.as_deref() {
format_ident!("{from}").into()
} else {
ident.clone()
};
// TODO (@Techassi): This is an awful lot of cloning, can we get
// rid of it?
let from_ty = change
.from_type
.as_ref()
.map(|sv| sv.deref().clone())
.unwrap_or(ty.clone());
actions.insert(
*change.since,
ItemStatus::Change {
downgrade_with: change.downgrade_with.as_deref().cloned(),
upgrade_with: change.upgrade_with.as_deref().cloned(),
from_ident: from_ident.clone(),
from_type: Box::new(from_ty.clone()),
to_ident: ident,
to_type: Box::new(ty),
},
);
ident = from_ident;
ty = from_ty;
}
// After the last iteration above (if any) we use the ident for the
// added action if there is any.
if let Some(added) = self.added {
actions.insert(
*added.since,
ItemStatus::Addition {
default_fn: added.default_fn.deref().clone(),
ident,
ty: Box::new(ty),
},
);
}
Some(actions)
} else {
if let Some(added) = self.added {
let mut actions = BTreeMap::new();
actions.insert(
*added.since,
ItemStatus::Addition {
default_fn: added.default_fn.deref().clone(),
ident: idents.original().clone(),
ty: Box::new(ty),
},
);
return Some(actions);
}
None
}
}
}
/// For the added() action
///
/// Example usage:
/// - `added(since = "...")`
/// - `added(since = "...", default_fn = "custom_fn")`
#[derive(Clone, Debug, FromMeta)]
pub struct AddedAttributes {
pub since: SpannedValue<Version>,
#[darling(rename = "default", default = "default_default_fn")]
pub default_fn: SpannedValue<Path>,
}
fn default_default_fn() -> SpannedValue<Path> {
SpannedValue::new(
syn::parse_str("::std::default::Default::default")
.expect("internal error: path must parse"),
Span::call_site(),
)
}
/// For the changed() action
///
/// Example usage:
/// - `changed(since = "...", from_name = "...")`
/// - `changed(since = "...", from_name = "...", from_type="...")`
/// - `changed(since = "...", from_name = "...", from_type="...", upgrade_with = "...")`
/// - `changed(since = "...", from_name = "...", from_type="...", downgrade_with = "...")`
#[derive(Clone, Debug, FromMeta)]
pub struct ChangedAttributes {
pub since: SpannedValue<Version>,
pub from_name: Option<SpannedValue<String>>,
pub from_type: Option<SpannedValue<Type>>,
pub upgrade_with: Option<SpannedValue<Path>>,
pub downgrade_with: Option<SpannedValue<Path>>,
}
/// For the deprecated() action
///
/// Example usage:
/// - `deprecated(since = "...")`
/// - `deprecated(since = "...", note = "...")`
#[derive(Clone, Debug, FromMeta)]
pub struct DeprecatedAttributes {
pub since: SpannedValue<Version>,
pub note: Option<SpannedValue<String>>,
}