-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathimp.rs
More file actions
793 lines (711 loc) · 25.1 KB
/
imp.rs
File metadata and controls
793 lines (711 loc) · 25.1 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
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
use super::error_store::{ErrorSink, ErrorStore};
use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned, ToTokens};
use syn::{
parse_quote, parse_quote_spanned, parse_str, spanned::Spanned,
visit::Visit, Attribute, Data, DataStruct, DeriveInput, Expr, Field,
Fields, GenericParam, Generics, Index, Lifetime, LifetimeParam, Path,
Token, WhereClause, WherePredicate,
};
pub struct DeriveDiffableOutput {
pub out: Option<TokenStream>,
pub errors: Vec<syn::Error>,
}
impl ToTokens for DeriveDiffableOutput {
fn to_tokens(&self, tokens: &mut TokenStream) {
tokens.extend(self.out.clone());
tokens.extend(self.errors.iter().map(|error| error.to_compile_error()));
}
}
pub fn derive_diffable(input: syn::DeriveInput) -> DeriveDiffableOutput {
let mut error_store = ErrorStore::new();
match &input.data {
Data::Enum(_) => {
// Implement all Enums as `Leaf`s
let out = make_leaf(&input, AttrPosition::Enum, error_store.sink());
DeriveDiffableOutput {
out: Some(out),
errors: error_store.into_inner(),
}
}
Data::Struct(s) => {
// This might be None if there are errors.
let out = make_struct_impl(&input, s, error_store.sink());
DeriveDiffableOutput { out, errors: error_store.into_inner() }
}
Data::Union(_) => {
// Implement all unions as `Leaf`s
let out =
make_leaf(&input, AttrPosition::Union, error_store.sink());
DeriveDiffableOutput {
out: Some(out),
errors: error_store.into_inner(),
}
}
}
}
// TODO: allow the crate name to be passed in as a macro argument
fn daft_crate() -> Path {
parse_quote! { ::daft }
}
fn daft_lifetime() -> LifetimeParam {
// Use an underscore to avoid clashing with a user-defined `'daft` lifetime.
LifetimeParam::new(Lifetime::new("'__daft", Span::call_site()))
}
// We need to add our lifetime parameter 'daft and ensure any other parameters
// live as long as `daft`
fn add_lifetime_to_generics(
input: &DeriveInput,
daft_lt: &LifetimeParam,
) -> Generics {
let mut new_generics = input.generics.clone();
new_generics
.lifetimes_mut()
.for_each(|lt| lt.bounds.push(daft_lt.lifetime.clone()));
new_generics.type_params_mut().for_each(|lt| {
lt.bounds.push(syn::TypeParamBound::Lifetime(daft_lt.lifetime.clone()))
});
// Add the 'daft lifetime to the beginning of the parameter list -- the
// exact order is not hugely important, but doing this makes tests simpler
// (they can just check the first element).
new_generics.params.insert(0, GenericParam::from(daft_lt.clone()));
new_generics
}
// Implement `Diffable` as a `Leaf`.
fn make_leaf(
input: &DeriveInput,
position: AttrPosition,
errors: ErrorSink<'_, syn::Error>,
) -> TokenStream {
// The input should not have any daft attributes.
for attr in &input.attrs {
if attr.path().is_ident("daft") {
let res = attr.parse_nested_meta(|meta| {
if meta.path.is_ident("leaf") {
// Accept this for leaf structs, but not for anything else.
if position == AttrPosition::LeafStruct {
return Ok(());
}
errors.push(meta.error(format!(
"this is unnecessary: the Diffable \
implementation {} is always a leaf",
position.as_purpose_str(),
)));
} else {
errors.push(meta.error(format!(
"daft attributes are not allowed {}",
position.as_locative_str(),
)));
}
Ok(())
});
if let Err(err) = res {
errors.push(err);
}
}
}
// Variants should not have any daft attributes.
let mut v = BanDaftAttrsVisitor { position, errors: errors.new_child() };
v.visit_data(&input.data);
// Even though errors might have occurred above, we *do* generate the
// implementation. That allows rust-analyzer to still understand that the
// `Diffable` impl exists.
let ident = &input.ident;
let daft_crate = daft_crate();
let daft_lt = daft_lifetime();
// The "where Self: #daft_lt" condition appears to be enough to satisfy
// Rust's borrow checker, so we don't need to add further constraints via
// `add_lifetime_to_generics`.
let (impl_gen, ty_gen, where_clause) = &input.generics.split_for_impl();
quote! {
impl #impl_gen #daft_crate::Diffable for #ident #ty_gen #where_clause
{
type Diff<#daft_lt> = #daft_crate::Leaf<&#daft_lt Self> where Self: #daft_lt;
fn diff<#daft_lt>(&#daft_lt self, other: &#daft_lt Self) -> Self::Diff<#daft_lt> {
#daft_crate::Leaf {before: self, after: other}
}
}
}
}
struct BanDaftAttrsVisitor<'a> {
position: AttrPosition,
errors: ErrorSink<'a, syn::Error>,
}
impl Visit<'_> for BanDaftAttrsVisitor<'_> {
fn visit_attribute(&mut self, attr: &Attribute) {
if attr.path().is_ident("daft") {
self.errors.push(syn::Error::new_spanned(
attr,
format!(
"daft attributes are not allowed {}",
self.position.as_locative_str(),
),
));
}
}
fn visit_variant(&mut self, v: &syn::Variant) {
let old_position = self.position;
self.position = self.position.visit_variant();
syn::visit::visit_variant(self, v);
self.position = old_position;
}
fn visit_field(&mut self, f: &syn::Field) {
let old_position = self.position;
self.position = self.position.visit_field();
syn::visit::visit_field(self, f);
self.position = old_position;
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum AttrPosition {
// Catch-all in case something unexpected happens with the visitor.
General,
LeafStruct,
LeafStructField,
Enum,
Variant,
VariantField,
Union,
UnionField,
}
impl AttrPosition {
fn visit_variant(self) -> Self {
match self {
Self::Enum => Self::Variant,
Self::General
| Self::LeafStruct
| Self::LeafStructField
| Self::Variant
| Self::VariantField
| Self::Union
| Self::UnionField => Self::General,
}
}
fn visit_field(self) -> Self {
match self {
Self::LeafStruct => Self::LeafStructField,
Self::Variant => Self::VariantField,
Self::Union => Self::UnionField,
Self::General
| Self::LeafStructField
| Self::Enum
| Self::VariantField
| Self::UnionField => Self::General,
}
}
// purpose = prepositional phrase to indicate what something applies to,
// e.g. "the implementation for enums is always"
fn as_purpose_str(self) -> &'static str {
match self {
Self::General => "for this type",
Self::LeafStruct => "for structs annotated with #[daft(leaf)]",
Self::LeafStructField => {
"for fields on structs annotated with #[daft(leaf)]"
}
Self::Enum => "for enums",
Self::Variant => "for enum variants",
Self::VariantField => "for enum variant fields",
Self::Union => "for unions",
Self::UnionField => "for union fields",
}
}
// "locative" = indicating location: "not allowed on enums", etc.
fn as_locative_str(self) -> &'static str {
match self {
Self::General => "here",
Self::LeafStruct => "on structs annotated with #[daft(leaf)]",
Self::LeafStructField => {
"on fields of structs annotated with #[daft(leaf)]"
}
Self::Enum => "on enums",
Self::Variant => "on enum variants",
Self::VariantField => "on enum variant fields",
Self::Union => "on unions",
Self::UnionField => "on union fields",
}
}
}
fn make_struct_impl(
input: &DeriveInput,
s: &DataStruct,
errors: ErrorSink<'_, syn::Error>,
) -> Option<TokenStream> {
let Some(struct_config) =
StructConfig::parse_from(&input.attrs, errors.new_child())
else {
// An error occurred parsing the struct configuration -- don't generate
// anything.
return None;
};
match struct_config.mode {
StructMode::Default => make_diff_struct(input, s, errors.new_child())
.map(|(generated_struct, diff_fields)| {
let diff_impl = make_diff_impl(input, &diff_fields);
// Uncomment for some debugging
// eprintln!("{generated_struct}");
// eprintln!("{diff_impl}");
quote! {
#generated_struct
#diff_impl
}
}),
StructMode::Leaf => {
Some(make_leaf(input, AttrPosition::LeafStruct, errors.new_child()))
}
}
}
/// Create the `Diff` struct
fn make_diff_struct(
input: &DeriveInput,
s: &DataStruct,
errors: ErrorSink<'_, syn::Error>,
) -> Option<(TokenStream, DiffFields)> {
// The name of the original type
let vis = &input.vis;
// The name of the generated type
let name = parse_str::<Path>(&format!("{}Diff", input.ident)).unwrap();
// Copy over the non-exhaustive attribute from the original struct. (Do we
// need to copy over other attributes?)
let non_exhaustive =
input.attrs.iter().find(|attr| attr.path().is_ident("non_exhaustive"));
let daft_lt = daft_lifetime();
// We are creating a new type, so use only generics with our new lifetime
// and bounds.
//
// Most of the other generics users use `split_for_impl`, but that is geared
// specifically for trait implementations, not type definitions. For type
// definitions, we use the original `Generics`.
//
// The `ToTokens` implementation for `Generics` does not print the `where`
// clause, so we also include that separately.
let new_generics = add_lifetime_to_generics(input, &daft_lt);
let where_clause = &new_generics.where_clause;
let Some(diff_fields) =
DiffFields::new(&s.fields, where_clause.as_ref(), errors.new_child())
else {
// An error occurred parsing fields -- don't generate the diff struct.
return None;
};
// --- No more errors past this point ---
let struct_def = match &s.fields {
Fields::Named(_) => quote! {
#non_exhaustive
#vis struct #name #new_generics #where_clause #diff_fields
},
Fields::Unnamed(_) => quote! {
#non_exhaustive
#vis struct #name #new_generics #diff_fields #where_clause;
},
Fields::Unit => quote! {
// This is kinda silly
#non_exhaustive
#vis struct #name #new_generics {} #where_clause
},
};
// Generate PartialEq, Eq, and Debug implementations for the diff struct. We
// can't rely on `#[derive] because we want to put bounds on the
// Diffable::Diff types, not on the original types.
let (impl_gen, ty_gen, _) = &new_generics.split_for_impl();
let debug_impl = {
let where_clause = diff_fields.where_clause_with_trait_bound(
&parse_quote! { ::core::fmt::Debug },
);
let members = diff_fields.fields.members();
let finish = if non_exhaustive.is_some() {
quote! { .finish_non_exhaustive() }
} else {
quote! { .finish() }
};
let debug_body = match &s.fields {
Fields::Named(_) => {
quote! {
f.debug_struct(stringify!(#name))
#(
.field(stringify!(#members), &self.#members)
)*
#finish
}
}
Fields::Unnamed(_) => quote! {
f.debug_tuple(stringify!(#name))
#(
.field(&self.#members)
)*
#finish
},
Fields::Unit => quote! {
f.debug_struct(stringify!(#name))
#finish
},
};
quote! {
impl #impl_gen ::core::fmt::Debug for #name #ty_gen #where_clause {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
#debug_body
}
}
}
};
let partial_eq_impl = {
let where_clause = diff_fields.where_clause_with_trait_bound(
&parse_quote! { ::core::cmp::PartialEq },
);
let members = diff_fields.fields.members();
let partial_eq_body: Expr = parse_quote! {
#(self.#members == other.#members) && *
};
quote! {
impl #impl_gen ::core::cmp::PartialEq for #name #ty_gen #where_clause {
fn eq(&self, other: &Self) -> bool {
#partial_eq_body
}
}
}
};
let eq_impl = {
let where_clause = diff_fields
.where_clause_with_trait_bound(&parse_quote! { ::core::cmp::Eq });
quote! {
impl #impl_gen ::core::cmp::Eq for #name #ty_gen #where_clause {}
}
};
Some((
quote! {
#struct_def
#debug_impl
#partial_eq_impl
#eq_impl
},
diff_fields,
))
}
/// Impl `Diffable` for the original struct
fn make_diff_impl(
input: &DeriveInput,
diff_fields: &DiffFields,
) -> TokenStream {
// The name of the original type
let ident = &input.ident;
// The name of the generated type
let name = parse_str::<Path>(&format!("{}Diff", input.ident)).unwrap();
let diffs =
generate_field_diffs(&diff_fields.fields, &diff_fields.field_configs);
let daft_crate = daft_crate();
let daft_lt = daft_lifetime();
let new_generics = add_lifetime_to_generics(input, &daft_lt);
let (impl_gen, ty_gen, _) = &input.generics.split_for_impl();
let (_, new_ty_gen, where_clause) = &new_generics.split_for_impl();
quote! {
impl #impl_gen #daft_crate::Diffable for #ident #ty_gen
#where_clause
{
type Diff<#daft_lt> = #name #new_ty_gen where Self: #daft_lt;
fn diff<#daft_lt>(&#daft_lt self, other: &#daft_lt Self) -> #name #new_ty_gen {
Self::Diff {
#diffs
}
}
}
}
}
/// For a `Diff` struct generated by this derive macro, tracks the fields that
/// will be put into that struct.
///
/// This also tracks the `where` clause.
///
/// The goal of this wrapper is to provide helpers to iterate over the fields
/// and members.
struct DiffFields {
fields: Fields,
// Configuration for each field -- a vector with the same length as `self.fields`.
field_configs: Vec<FieldConfig>,
// The base where clause for the diff struct.
where_clause: WhereClause,
}
impl DiffFields {
/// None means there was an error parsing a config.
fn new(
fields: &Fields,
where_clause: Option<&WhereClause>,
errors: ErrorSink<'_, syn::Error>,
) -> Option<Self> {
let (fields, field_configs) = match fields {
Fields::Named(fields) => {
let (named, configs) = fields
.named
.iter()
.filter_map(|field| {
Self::diff_field(field, errors.new_child())
})
.unzip();
(
Fields::Named(syn::FieldsNamed {
brace_token: fields.brace_token,
named,
}),
configs,
)
}
Fields::Unnamed(fields) => {
let (unnamed, configs) = fields
.unnamed
.iter()
.filter_map(|field| {
Self::diff_field(field, errors.new_child())
})
.unzip();
(
Fields::Unnamed(syn::FieldsUnnamed {
paren_token: fields.paren_token,
unnamed,
}),
configs,
)
}
Fields::Unit => (Fields::Unit, Vec::new()),
};
// Initialize an empty where clause if none was provided.
let where_clause =
where_clause.cloned().unwrap_or_else(|| WhereClause {
where_token: <Token![where]>::default(),
predicates: Default::default(),
});
if errors.has_errors() {
None
} else {
Some(Self { fields, field_configs, where_clause })
}
}
/// Return a field for a diff with the appropriate type.
///
/// If the type is ignored, or if there's an error parsing configuration,
/// return None.
fn diff_field(
f: &Field,
errors: ErrorSink<'_, syn::Error>,
) -> Option<(Field, FieldConfig)> {
let Some(config) =
FieldConfig::parse_from(&f.attrs, errors.new_child())
else {
// None means there's an error parsing a config -- return None here,
// we'll emit errors at the top level.
return None;
};
if config.mode == FieldMode::Ignore {
// Skip over this field if there's an ignore.
return None;
}
// Always use the daft lifetime for the diff -- associations between the
// daft lifetime and existing parameters (both lifetime and type
// parameters) are created in `add_lifetime_to_generics`, e.g. `'a:
// '__daft`, or `T: '__daft`.
let lt = daft_lifetime();
let daft_crate = daft_crate();
let ty = &f.ty;
let mut f = f.clone();
f.ty = if config.mode == FieldMode::Leaf {
parse_quote_spanned! {f.span()=>
#daft_crate::Leaf<&#lt #ty>
}
} else {
parse_quote_spanned! {f.span()=>
<#ty as #daft_crate::Diffable>::Diff<#lt>
}
};
// Drop all attributes for now. We may want to carry some over in the
// future.
f.attrs = vec![];
Some((f, config))
}
/// Returns an iterator over field types.
fn types(&self) -> impl Iterator<Item = &syn::Type> {
self.fields.iter().map(|f| &f.ty)
}
/// Returns an expanded where clause where the fields have had a trait bound
/// applied to them.
fn where_clause_with_trait_bound(
&self,
trait_bound: &syn::TraitBound,
) -> WhereClause {
let predicates = self.types().map(|ty| -> WherePredicate {
parse_quote_spanned! {ty.span()=>
#ty: #trait_bound
}
});
let mut where_clause = self.where_clause.clone();
where_clause.predicates.extend(predicates);
where_clause
}
}
impl ToTokens for DiffFields {
fn to_tokens(&self, tokens: &mut TokenStream) {
self.fields.to_tokens(tokens);
}
}
/// Generate a call to `diff` for each field of the original struct that isn't
/// ignored.
fn generate_field_diffs(
fields: &Fields,
// Should be the same length as `fields`.
field_configs: &[FieldConfig],
) -> TokenStream {
let daft_crate = daft_crate();
let field_diffs =
fields.iter().zip(field_configs).enumerate().map(|(i, (f, config))| {
let field_name = match &f.ident {
Some(ident) => quote! { #ident },
None => {
let ident: Index = i.into();
quote! { #ident }
}
};
if config.mode == FieldMode::Leaf {
quote_spanned! {f.span()=>
#field_name: #daft_crate::Leaf {
before: &self.#field_name,
after: &other.#field_name
}
}
} else {
quote_spanned! {f.span()=>
#field_name: #daft_crate::Diffable::diff(
&self.#field_name,
&other.#field_name
)
}
}
});
quote! { #(#field_diffs),* }
}
#[derive(Debug)]
struct StructConfig {
mode: StructMode,
}
impl StructConfig {
fn parse_from(
attrs: &[Attribute],
errors: ErrorSink<'_, syn::Error>,
) -> Option<Self> {
let mut mode = StructMode::Default;
for attr in attrs {
{
if attr.path().is_ident("daft") {
let res = attr.parse_nested_meta(|meta| {
if meta.path.is_ident("leaf") {
match mode {
StructMode::Default => {
mode = StructMode::Leaf;
}
StructMode::Leaf => {
errors.push(meta.error(
"#[daft(leaf)] specified multiple times",
));
}
}
} else {
errors.push(meta.error(
"unknown attribute \
(supported attributes: leaf)",
));
}
Ok(())
});
if let Err(err) = res {
errors.push(err);
}
}
}
}
if errors.has_errors() {
None
} else {
Some(Self { mode })
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum StructMode {
// The default mode: do a recursive diff for this struct.
Default,
// Use a `Leaf` for this struct.
Leaf,
}
#[derive(Debug)]
struct FieldConfig {
mode: FieldMode,
}
impl FieldConfig {
fn parse_from(
attrs: &[Attribute],
errors: ErrorSink<'_, syn::Error>,
) -> Option<Self> {
let mut mode = FieldMode::Default;
for attr in attrs {
if attr.path().is_ident("daft") {
let res = attr.parse_nested_meta(|meta| {
if meta.path.is_ident("leaf") {
// #[daft(leaf)]
match mode {
FieldMode::Default => {
mode = FieldMode::Leaf;
}
FieldMode::Leaf => {
errors.push(meta.error(
"#[daft(leaf)] specified multiple times",
));
}
_ => {
errors.push(meta.error(
"#[daft(leaf)] conflicts with \
other attributes",
));
}
}
} else if meta.path.is_ident("ignore") {
// #[daft(ignore)]
match mode {
FieldMode::Default => {
mode = FieldMode::Ignore;
}
FieldMode::Ignore => {
errors.push(meta.error(
"#[daft(ignore)] specified multiple times",
));
}
_ => {
errors.push(meta.error(
"#[daft(ignore)] conflicts with \
other attributes",
));
}
}
} else {
errors.push(meta.error(
"unknown attribute \
(supported attributes: leaf, ignore)",
));
}
Ok(())
});
// We don't return an error from our callback, but syn might.
if let Err(err) = res {
errors.push(err);
}
}
}
if errors.has_errors() {
None
} else {
Some(Self { mode })
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FieldMode {
// The default mode: do a recursive diff for this field.
Default,
// Use a `Leaf` for this field.
Leaf,
// Ignore this field.
Ignore,
}