forked from redbadger/difficient
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
1603 lines (1513 loc) · 56.3 KB
/
Copy pathlib.rs
File metadata and controls
1603 lines (1513 loc) · 56.3 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
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
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
extern crate proc_macro;
use std::str::FromStr;
use darling::{
FromDeriveInput, FromField, FromMeta, FromVariant,
ast::{Data, Fields, Style},
};
use heck::{ToKebabCase, ToLowerCamelCase, ToSnakeCase};
use proc_macro2::TokenStream;
use quote::{ToTokens, format_ident, quote};
use syn::{DeriveInput, Generics, Ident};
#[derive(Debug, FromField)]
#[darling(attributes(diffable, serde), allow_unknown_fields)]
struct StructLike {
ident: Option<syn::Ident>,
ty: syn::Type,
#[darling(default)]
atomic: bool,
#[darling(default)]
skip: bool,
rename: Option<String>,
}
#[derive(Debug, FromVariant)]
#[darling(attributes(serde), allow_unknown_fields)]
struct EnumData {
ident: syn::Ident,
fields: Fields<StructLike>,
rename: Option<String>, // TODO
rename_all: Option<String>,
}
/// Used for attributes on structs or enums
#[derive(FromMeta, Debug, Default)]
#[darling(allow_unknown_fields)]
struct ContainerSerdeAttrs {
rename_all: Option<String>,
tag: Option<String>,
content: Option<String>,
#[darling(default)]
untagged: bool,
#[darling(default)]
transparent: bool,
}
impl ContainerSerdeAttrs {
fn variant_tag(&self) -> SerdeVariantTag {
if let Some(tag) = self.tag.as_ref() {
if let Some(c) = self.content.as_ref() {
SerdeVariantTag::Adjacent {
tag: tag.clone(),
content: c.clone(),
}
} else {
SerdeVariantTag::Internal { tag: tag.clone() }
}
} else if self.untagged {
SerdeVariantTag::Untagged
} else {
SerdeVariantTag::External
}
}
}
#[derive(Debug, Clone, PartialEq)]
enum SerdeVariantTag {
External,
Internal { tag: String },
Adjacent { tag: String, content: String },
Untagged,
}
enum SerdeRenameAllCase {
Lower,
Upper,
Snake,
Camel,
Pascal,
ScreamingSnake,
Kebab,
ScreamingKebab,
}
impl FromStr for SerdeRenameAllCase {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
use SerdeRenameAllCase as S;
let ok = match s {
"lowercase" => S::Lower,
"UPPERCASE" => S::Upper,
"PascalCase" => S::Pascal,
"camelCase" => S::Camel,
"snake_case" => S::Snake,
"SCREAMING_SNAKE_CASE" => S::ScreamingSnake,
"kebab-case" => S::Kebab,
"SCREAMING-KEBAB-CASE" => S::ScreamingKebab,
other => return Err(format!("bad rename: {other}")),
};
Ok(ok)
}
}
impl SerdeRenameAllCase {
fn do_rename(&self, ident: &Ident) -> String {
use SerdeRenameAllCase as S;
match self {
S::Snake => ident.to_string().to_snake_case(),
S::Camel => ident.to_string().to_lower_camel_case(),
S::Kebab => ident.to_string().to_kebab_case(),
S::Lower => ident.to_string().to_lowercase(),
S::Upper | S::Pascal | S::ScreamingSnake | S::ScreamingKebab => {
todo!("Difficient does not support case: {{self:?}}")
}
}
}
}
impl ToTokens for SerdeVariantTag {
fn to_tokens(&self, tokens: &mut TokenStream) {
let tok = match self {
SerdeVariantTag::External => quote! { difficient::SerdeVariantTag::External },
SerdeVariantTag::Internal { tag } => {
quote! { difficient::SerdeVariantTag::Internal { tag: #tag.to_string() } }
}
SerdeVariantTag::Adjacent { tag, content } => {
quote! { difficient::SerdeVariantTag::Adjacent {
tag: #tag.to_string(), content: #content.to_string()
} }
}
SerdeVariantTag::Untagged => {
quote! { difficient::SerdeVariantTag::Untagged }
}
};
tokens.extend(tok);
}
}
#[derive(Debug, FromDeriveInput)]
#[darling(attributes(diffable, serde))]
struct DeriveDiffable {
ident: syn::Ident,
vis: syn::Visibility,
data: Data<EnumData, StructLike>,
generics: Generics,
#[darling(default)]
visit_transparent: bool,
#[darling(default)]
atomic: bool,
#[darling(flatten)]
serde: ContainerSerdeAttrs,
}
impl DeriveDiffable {
fn derive(&self, serde_feature: bool, derive_visitor: bool) -> TokenStream {
assert!(
self.generics.params.is_empty(),
"derive(Diffable) does not support generic parameters"
);
let name = &self.ident;
// short-circuit branch for top-level atomic
if self.atomic {
let has_any_skipped_fields = match &self.data {
Data::Enum(variants) => variants.iter().any(|ed| ed.fields.iter().any(|f| f.skip)),
Data::Struct(fields) => fields.iter().any(|f| f.skip),
};
assert!(!has_any_skipped_fields, "cannot skip fields in atomic diff");
return quote! {
impl<'a> difficient::Diffable<'a> for #name {
type Diff = difficient::AtomicDiff<'a, Self>;
fn diff(&self, other: &'a Self) -> Self::Diff {
Self::Diff::new(self, other)
}
}
};
}
let diff_ty = format_ident!("{}Diff", self.ident);
let vis = &self.vis;
let serde_derive = serde_feature.then(|| quote! { #[derive(serde::Serialize)] });
let serde_container_rename_all: Option<SerdeRenameAllCase> = self
.serde
.rename_all
.as_deref()
.and_then(|s| s.parse::<SerdeRenameAllCase>().ok());
match &self.data {
Data::Enum(variants) => {
let tag = self.serde.variant_tag();
enum_impl(
variants,
&tag,
name,
&diff_ty,
vis,
serde_derive.as_ref(),
serde_container_rename_all.as_ref(),
derive_visitor,
self.visit_transparent || self.serde.transparent,
)
}
Data::Struct(fields) => struct_impl(
fields,
name,
&diff_ty,
vis,
serde_derive.as_ref(),
serde_container_rename_all.as_ref(),
derive_visitor,
self.visit_transparent || self.serde.transparent,
),
}
}
}
impl ToTokens for DeriveDiffable {
fn to_tokens(&self, tokens: &mut TokenStream) {
let serde_feature = cfg!(feature = "serde_impl");
let derive_visitor = cfg!(feature = "visitor_impl");
tokens.extend(self.derive(serde_feature, derive_visitor));
}
}
#[expect(
clippy::too_many_arguments,
reason = "TODO Consider refactoring or configuring the lint"
)]
#[expect(
clippy::too_many_lines,
reason = "TODO Consider refactoring or configuring the lint"
)]
fn enum_impl(
variants: &[EnumData],
variant_tag: &SerdeVariantTag,
name: &Ident,
diff_ty: &Ident,
vis: &syn::Visibility,
serde_derive: Option<&TokenStream>,
serde_container_rename_all: Option<&SerdeRenameAllCase>,
derive_visitor: bool,
transparent: bool,
) -> TokenStream {
let var_name: Vec<&Ident> = variants.iter().map(|ed| &ed.ident).collect();
let is_fieldless = variants.iter().all(|ed| ed.fields.is_empty());
let lifetime = if is_fieldless {
quote! {}
} else {
quote! { <'a> }
};
let var_diff_def = variants.iter().map(|var| {
let ty: Vec<_> = var.fields.iter().map(|data| &data.ty).collect();
let field_diff_ty: Vec<_> = var
.fields
.iter()
.zip(ty.iter())
// totally ignore fields that are annotated with `#[diffable(skip)]`
.filter(|(f, _)| !f.skip)
.map(|(f, ty)| {
if f.atomic {
quote! {
difficient::AtomicDiff<'a, #ty>
}
} else {
quote! {
<#ty as difficient::Diffable<'a>>::Diff
}
}
})
.collect();
match var.fields.style {
Style::Unit => quote! {},
Style::Tuple => {
quote! {
(
#( #field_diff_ty, )*
)
}
}
Style::Struct => {
let field = var
.fields
.iter()
.filter(|f| !f.skip)
.map(|data| &data.ident)
.collect::<Vec<_>>();
quote! {
{
#( #field: #field_diff_ty, )*
}
}
}
}
});
let enum_definition = quote! {
#[derive(Debug, Clone, PartialEq)]
#[allow(non_camel_case_types, non_snake_case, dead_code, reason = "Macro")]
#[automatically_derived]
#serde_derive
#vis enum #diff_ty #lifetime {
#(
#var_name #var_diff_def,
)*
}
};
let variant_diff_impl = variants.iter().zip(var_name.iter()).map(|(var, var_name)| {
let pattern_match_left = pattern_match(&var.fields, "left", true);
let pattern_match_right = pattern_match(&var.fields, "right", true);
let diff_impl = variant_diff_body(diff_ty, var_name, &var.fields);
quote! {
(Self::#var_name #pattern_match_left, Self::#var_name #pattern_match_right) => {
#diff_impl
}
}
});
let diffable_impl = quote! {
impl<'a> difficient::Diffable<'a> for #name {
type Diff = difficient::DeepDiff<'a, Self, #diff_ty #lifetime>;
#[allow(non_snake_case, reason = "Macro")]
fn diff(&self, other: &'a Self) -> Self::Diff {
use difficient::Replace as _;
match (self, other) {
#(
#variant_diff_impl
),*
_ => difficient::DeepDiff::Replaced(other)
}
}
}
};
let apply_body = variants
.iter()
.zip(var_name.iter())
.map(|(var, var_name)| {
let pat_l = prefixed_idents(&var.fields, "left", false);
let pat_r = prefixed_idents(&var.fields, "right", false);
let pattern_match_left = pattern_match(&var.fields, "left", false);
let pattern_match_right = pattern_match(&var.fields, "right", true);
quote! {
(Self::#var_name #pattern_match_left, #name::#var_name #pattern_match_right) => {
#( #pat_l.apply_to_base(#pat_r, errs); )*
}
}
})
.collect::<Vec<_>>();
let apply_impl = quote! {
impl #lifetime difficient::Apply for #diff_ty #lifetime {
type Parent = #name;
fn apply_to_base(&self, source: &mut Self::Parent, errs: &mut Vec<difficient::ApplyError>) {
match (self, source) {
#( #apply_body )*
_ => errs.push(difficient::ApplyError::MismatchingEnum),
}
}
}
};
let visit_enum_variant_impl = variants.iter().zip(var_name.iter()).map(|(var, var_name)| {
let ident = get_idents(&var.fields);
let num_non_skipped_fields = var.fields.iter().filter(|f| !f.skip).count();
#[expect(clippy::map_unwrap_or, reason = "more readable this way")]
let serde_var_rename = var.rename.as_ref().map(|r| quote! { Some(#r) }).unwrap_or_else(||
if let Some(r) = serde_container_rename_all.as_ref().map(|r| r.do_rename(var_name)) {
quote! { Some(#r) } }
else {
quote! { None }
});
match var.fields.style {
Style::Tuple => {
if num_non_skipped_fields == 0 {
return quote! {
Self:: #var_name () => {}
}
}
let position = 0..(var.fields.len());
let var_name_str = var_name.to_string();
if transparent {
// if tagged with `diffable(visit_transparent)`, we do not emit any
// enter/exit events information and just continue inwards
quote! {
Self:: #var_name ( #( #ident, )* ) => {
#(
if !#ident.is_unchanged() {
#ident.accept(visitor);
}
)*
}
}
} else {
quote! {
Self:: #var_name ( #( #ident, )* ) => {
visitor.enter(difficient::Enter::Variant{
name: #var_name_str, serde_rename: #serde_var_rename, serde_tag: #variant_tag
});
#(
if !#ident.is_unchanged() {
visitor.enter(difficient::Enter::PositionalField(#position));
#ident.accept(visitor);
visitor.exit();
}
)*
visitor.exit();
}
}
}
}
Style::Struct => {
if num_non_skipped_fields == 0 {
return quote! {
Self:: #var_name {} => {}
}
}
let var_name_str = var_name.to_string();
let ident_str = ident.iter().map(std::string::ToString::to_string);
let var_rename_all: Option<SerdeRenameAllCase> = var.rename_all.as_ref().map(|r| r.parse().unwrap());
let serde_field_rename: Vec<_> = var.fields
.iter()
.map(|f| {
if let Some(n) = f.rename.as_ref() {
quote! { Some(#n) }
} else if let Some(r) = var_rename_all.as_ref() {
let re = r.do_rename(f.ident.as_ref().unwrap());
quote! { Some(#re) }
} else {
quote! { None }
}
})
.collect();
quote! {
Self:: #var_name { #( #ident, )* } => {
visitor.enter(difficient::Enter::Variant{
name: #var_name_str, serde_rename: #serde_var_rename, serde_tag: #variant_tag
});
#(
if !#ident.is_unchanged() {
visitor.enter(difficient::Enter::NamedField {
name: #ident_str, serde_rename: #serde_field_rename
});
#ident.accept(visitor);
visitor.exit();
}
)*
visitor.exit();
}
}
}
Style::Unit => quote! {
Self:: #var_name => {}
}
}
});
let visitor_impl = derive_visitor.then(|| {
quote! {
impl #lifetime difficient::AcceptVisitor for #diff_ty #lifetime {
fn accept<V: difficient::Visitor>(&self, visitor: &mut V) {
use difficient::Replace as _;
match self {
#( #visit_enum_variant_impl ),*
}
}
}
}
});
quote! {
#enum_definition
#diffable_impl
#apply_impl
#visitor_impl
}
}
#[expect(
clippy::too_many_arguments,
reason = "TODO Consider refactoring or configuring the lint"
)]
#[expect(
clippy::too_many_lines,
reason = "TODO Consider refactoring or configuring the lint"
)]
fn struct_impl(
fields: &Fields<StructLike>,
name: &Ident,
diff_ty: &Ident,
vis: &syn::Visibility,
serde_derive: Option<&TokenStream>,
serde_rename_all: Option<&SerdeRenameAllCase>,
derive_visitor: bool,
transparent: bool,
) -> TokenStream {
let ty = fields.iter().map(|data| &data.ty).collect::<Vec<_>>();
let num_skipped_fields = fields.iter().filter(|f| f.skip).count();
let num_non_skipped_fields = fields.iter().filter(|f| !f.skip).count();
assert!(
!(transparent && num_non_skipped_fields != 1),
"visit_transparent only makes sense when applied to newtypes"
);
if matches!(fields.style, Style::Unit) || num_non_skipped_fields == 0 {
// short-circuit return
return quote! {
impl<'a> difficient::Diffable<'a> for #name {
type Diff = difficient::Id<Self>;
fn diff(&self, other: &'a Self) -> Self::Diff {
difficient::Id::new()
}
}
};
}
let field = get_idents(fields);
let field_diff_ty: Vec<_> = fields
.iter()
.zip(ty.iter())
// totally ignore fields that are annotated with `#[diffable(skip)]`
.filter(|(f, _)| !f.skip)
.map(|(f, ty)| {
if f.atomic {
quote! {
difficient::AtomicDiff<'a, #ty>
}
} else {
quote! {
<#ty as difficient::Diffable<'a>>::Diff
}
}
})
.collect();
let source_accessor = get_accessors(fields, false);
let diff_accessor = get_accessors(fields, true);
let diff_ty_def = match fields.style {
Style::Tuple => {
quote! {
#vis struct #diff_ty<'a>(
#(
#field_diff_ty,
)*
);
}
}
Style::Struct => {
quote! {
#vis struct #diff_ty<'a> {
#(
#field: #field_diff_ty,
)*
}
}
}
Style::Unit => unreachable!(),
};
let patch_ctor = match fields.style {
Style::Tuple => quote! {
#diff_ty( #( #field, )* )
},
Style::Struct => quote! {
#diff_ty{ #( #field ),* }
},
Style::Unit => unreachable!(),
};
let field_diff_impl: Vec<_> = fields
.iter()
.zip(source_accessor.iter())
.map(|(f, accessor)| {
if f.atomic {
quote! {
difficient::AtomicDiff::new(&self.#accessor, &other.#accessor)
}
} else {
quote! {
self.#accessor.diff(&other.#accessor)
}
}
})
.collect();
// if there is only one field on the struct, we do not allow replacement, only
// patching. This is to make the patches as targeted as possible
let (struct_diff_type, replaced_impl) = if num_skipped_fields > 0 || num_non_skipped_fields == 1
{
(
quote! {
difficient::PatchOnlyDiff<#diff_ty<'a>>
},
quote! {
Self::Diff::Patched(#patch_ctor)
},
)
} else {
(
quote! {
difficient::DeepDiff<'a, Self, #diff_ty<'a>>
},
quote! {
Self::Diff::Replaced(other)
},
)
};
let diffable_impl = quote! {
impl<'a> difficient::Diffable<'a> for #name {
type Diff = #struct_diff_type;
#[allow(non_snake_case, reason = "Macro")]
fn diff(&self, other: &'a Self) -> Self::Diff {
use difficient::Replace as _;
#(
let #field = #field_diff_impl;
)*
if #( #field.is_unchanged() && )* true {
Self::Diff::Unchanged
} else if #( #field.is_replaced() && )* true {
#replaced_impl
} else {
Self::Diff::Patched(#patch_ctor)
}
}
}
};
let apply_impl = quote! {
impl<'a> difficient::Apply for #diff_ty<'a> {
type Parent = #name;
#[allow(non_snake_case, reason = "Macro")]
fn apply_to_base(&self, source: &mut Self::Parent, errs: &mut Vec<difficient::ApplyError>) {
#( self.#diff_accessor.apply_to_base(&mut source.#source_accessor, errs); )*
}
}
};
let struct_field_visit_impl = {
let ident = get_idents(fields);
match fields.style {
Style::Tuple => {
let position = 0..(fields.len());
if transparent {
// if tagged with `diffable(visit_transparent)`, we do not emit any
// enter/exit events information and just continue inwards
quote! {
let Self ( #( #ident, )* ) = self;
#(
if !#ident.is_unchanged() {
#ident.accept(visitor);
}
)*
}
} else {
quote! {
let Self ( #( #ident, )* ) = self;
#(
if !#ident.is_unchanged() {
visitor.enter(difficient::Enter::PositionalField(#position));
#ident.accept(visitor);
visitor.exit();
}
)*
}
}
}
Style::Struct => {
let ident_str = ident.iter().map(std::string::ToString::to_string);
let serde_rename: Vec<_> = fields
.iter()
.filter(|f| !f.skip)
.map(|f| {
if let Some(n) = f.rename.as_ref() {
quote! { Some(#n) }
} else if let Some(r) = serde_rename_all.as_ref() {
let re = r.do_rename(f.ident.as_ref().unwrap());
quote! { Some(#re) }
} else {
quote! { None }
}
})
.collect();
assert_eq!(ident_str.len(), serde_rename.len());
if transparent {
// if tagged with `diffable(visit_transparent)`, we do not emit any
// enter/exit events information and just continue inwards
quote! {
let Self { #( #ident, )* } = self;
#(
if !#ident.is_unchanged() {
#ident.accept(visitor);
}
)*
}
} else {
quote! {
let Self { #( #ident, )* } = self;
#(
if !#ident.is_unchanged() {
visitor.enter(difficient::Enter::NamedField{
name: #ident_str, serde_rename: #serde_rename
});
#ident.accept(visitor);
visitor.exit();
}
)*
}
}
}
Style::Unit => quote! {},
}
};
let visitor_impl = derive_visitor.then(|| {
quote! {
impl<'a> difficient::AcceptVisitor for #diff_ty <'a> {
fn accept<V: difficient::Visitor>(&self, visitor: &mut V) {
use difficient::Replace as _;
#struct_field_visit_impl
}
}
}
});
quote! {
#[derive(Debug, Clone, PartialEq)]
#[allow(non_camel_case_types, non_snake_case, dead_code, reason = "Macro")]
#[automatically_derived]
#serde_derive
#diff_ty_def
#diffable_impl
#apply_impl
#visitor_impl
}
}
fn variant_diff_body(
diff_ty: &Ident,
variant_name: &Ident,
fields: &Fields<StructLike>,
) -> TokenStream {
let num_non_skipped_fields = fields.iter().filter(|f| !f.skip).count();
let ident = get_idents(fields);
let patch_ctor = match fields.style {
Style::Tuple => quote! {
// round brackets
#diff_ty::#variant_name(
# ( #ident, )*
)
},
Style::Struct => quote! {
// curly brackets
#diff_ty::#variant_name {
# ( #ident, )*
}
},
Style::Unit => quote! {},
};
if num_non_skipped_fields == 0 {
return quote! {
// no fields -> by definition they are unchanged
difficient::DeepDiff::Unchanged
};
}
match fields.style {
Style::Unit => unreachable!(), // dealt with above, unit types have zero fields
Style::Tuple | Style::Struct => {
let left_ident = prefixed_idents(fields, "left", false);
let right_ident = prefixed_idents(fields, "right", false);
let field_diff_impl: Vec<_> = fields
.iter()
// totally ignore fields that are annotated with `#[diffable(skip)]`
.filter(|f| !f.skip)
.zip(ident.iter())
.zip(left_ident.iter())
.zip(right_ident.iter())
.map(|(((f, ident), left), right)| {
if f.atomic {
quote! {
let #ident = difficient::AtomicDiff::new(#left, #right);
}
} else {
quote! {
let #ident = #left.diff(#right);
}
}
})
.collect();
// We have a decision to make here. Suppose we have an enum where
// the enum variant has *not* changed but every field of the variant has.
// Should we send a Patch or a Replaced? Our reasoning is that replacing
// the enum variant is a more destructive operation than necessary (the
// variant and the fields of the variant are separate bits of data) and
// therefore we decide that we should always send a Patch not a Replaced
// in such cases
quote! {
#(
#field_diff_impl
)*
if #( #ident.is_unchanged() && )* true {
difficient::DeepDiff::Unchanged
} else {
difficient::DeepDiff::Patched(#patch_ctor)
}
}
}
}
}
fn pattern_match(fields: &Fields<StructLike>, prefix: &str, include_skipped: bool) -> TokenStream {
let pattern = prefixed_idents(fields, prefix, include_skipped);
match fields.style {
Style::Unit => quote! {},
Style::Tuple => {
quote! {
(
#( #pattern, )*
)
}
}
Style::Struct => {
let id = fields
.iter()
.filter(|f| !f.skip || include_skipped)
.map(|data| &data.ident)
.collect::<Vec<_>>();
quote! {
{
#( #id: #pattern, )*
}
}
}
}
}
// tokens for field idents
fn get_idents(fields: &Fields<StructLike>) -> Vec<Ident> {
fields
.iter()
.enumerate()
.filter(|(_, f)| !f.skip)
.map(|(ix, struct_like)| {
if let Some(field_name) = &struct_like.ident {
field_name.clone()
} else {
// if the field has no name (tuple-like), fall back to 'f0', 'f1' etc
format_ident!("f{ix}")
}
})
.collect()
}
// as above but with a given prefix, useful for pattern matching
fn prefixed_idents(fields: &Fields<StructLike>, prefix: &str, include_skipped: bool) -> Vec<Ident> {
fields
.iter()
.enumerate()
.filter(|(_, f)| !f.skip || include_skipped)
.map(|(ix, struct_like)| {
if struct_like.skip {
format_ident!("_")
} else if let Some(field_name) = &struct_like.ident {
format_ident!("{prefix}_{field_name}")
} else {
format_ident!("{prefix}_{ix}")
}
})
.collect()
}
// the tokens to access fields from parent struct ('self.my_field', or 'self.0')
// `monotonic_index` will force the indexes to increment monotonically even if
// some of the fields are skipped (relevant for tuple structs)
fn get_accessors(fields: &Fields<StructLike>, monotonic_index: bool) -> Vec<TokenStream> {
let mut monotonic_count = monotonic_index.then_some(0);
fields
.iter()
.enumerate()
.filter(|(_, f)| !f.skip)
.map(|(ix, struct_like)| {
if let Some(field_name) = &struct_like.ident {
quote! { #field_name }
} else {
let ix = monotonic_count.unwrap_or(ix);
monotonic_count = monotonic_count.map(|ix| ix + 1);
let ix = syn::Index::from(ix);
quote! { #ix }
}
})
.collect()
}
#[expect(clippy::missing_panics_doc, reason = "Macro implementation")]
#[proc_macro_derive(Diffable, attributes(diffable, serde))]
pub fn derive_diffable(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
let ast: DeriveInput = syn::parse(tokens).unwrap();
let diff = DeriveDiffable::from_derive_input(&ast).unwrap();
quote! { #diff }.into()
}
#[cfg(test)]
mod tests {
#![expect(clippy::too_many_lines, reason = "tests")]
use super::*;
#[test]
fn test_derive_struct() {
let input = r#"
#[derive(Diffable)]
#[serde(rename_all = "camelCase", some_fake_field)]
struct SimpleStruct {
x: i32,
#[serde(rename = "yyy")]
y: String,
#[diffable(atomic)]
z_for_zelda: Vec<Fake>,
}
"#;
let parsed = syn::parse_str(input).unwrap();
let diff = DeriveDiffable::from_derive_input(&parsed).unwrap();
let expect = quote! {
#[derive(Debug, Clone, PartialEq)]
#[allow(non_camel_case_types, non_snake_case, dead_code, reason = "Macro")]
#[automatically_derived]
#[derive(serde::Serialize)]
struct SimpleStructDiff<'a> {
x: <i32 as difficient::Diffable<'a>>::Diff,
y: <String as difficient::Diffable<'a>>::Diff,
z_for_zelda: difficient::AtomicDiff<'a, Vec<Fake>>,
}
impl<'a> difficient::Diffable<'a> for SimpleStruct {
type Diff = difficient::DeepDiff<'a, Self, SimpleStructDiff<'a>>;
#[allow(non_snake_case, reason = "Macro")]
fn diff(&self, other: &'a Self) -> Self::Diff {
use difficient::Replace as _;
let x = self.x.diff(&other.x);
let y = self.y.diff(&other.y);
let z_for_zelda = difficient::AtomicDiff::new(&self.z_for_zelda, &other.z_for_zelda);
if x.is_unchanged() && y.is_unchanged() && z_for_zelda.is_unchanged() && true {
Self::Diff::Unchanged
} else if x.is_replaced() && y.is_replaced() && z_for_zelda.is_replaced() && true {
Self::Diff::Replaced(other)
} else {
Self::Diff::Patched(SimpleStructDiff { x, y, z_for_zelda })
}
}
}
impl<'a> difficient::Apply for SimpleStructDiff<'a> {
type Parent = SimpleStruct;
#[allow(non_snake_case, reason = "Macro")]
fn apply_to_base(
&self,
source: &mut Self::Parent,
errs: &mut Vec<difficient::ApplyError>,
) {
self.x.apply_to_base(&mut source.x, errs);
self.y.apply_to_base(&mut source.y, errs);
self.z_for_zelda.apply_to_base(&mut source.z_for_zelda, errs);
}
}
impl<'a> difficient::AcceptVisitor for SimpleStructDiff<'a> {
fn accept<V: difficient::Visitor>(&self, visitor: &mut V) {
use difficient::Replace as _;
let Self { x, y, z_for_zelda } = self;
if !x.is_unchanged() {
visitor
.enter(difficient::Enter::NamedField {
name: "x",
serde_rename: Some("x"),
});
x.accept(visitor);
visitor.exit();
}
if !y.is_unchanged() {
visitor