Debian Codegraph @

src/internals/imp.rs

raw symbols SCIP
1 use super::error_store::{ErrorSink, ErrorStore};
2 use proc_macro2::{Span, TokenStream};
3 use quote::{quote, quote_spanned, ToTokens};
4 use syn::{
5 parse_quote, parse_quote_spanned, parse_str, spanned::Spanned,
6 visit::Visit, Attribute, Data, DataStruct, DeriveInput, Expr, Field,
7 Fields, GenericParam, Generics, Index, Lifetime, LifetimeParam, Path,
8 Token, WhereClause, WherePredicate,
9 };
10
11 pub struct DeriveDiffableOutput {
12 pub out: Option<TokenStream>,
13 pub errors: Vec<syn::Error>,
14 }
15
16 impl ToTokens for DeriveDiffableOutput {
17 fn to_tokens(&self, tokens: &mut TokenStream) {
18 tokens.extend(self.out.clone());
19 tokens.extend(self.errors.iter().map(|error| error.to_compile_error()));
20 }
21 }
22
23 pub fn derive_diffable(input: syn::DeriveInput) -> DeriveDiffableOutput {
24 let mut error_store = ErrorStore::new();
25
26 match &input.data {
27 Data::Enum(_) => {
28 // Implement all Enums as `Leaf`s
29 let out = make_leaf(&input, AttrPosition::Enum, error_store.sink());
30 DeriveDiffableOutput {
31 out: Some(out),
32 errors: error_store.into_inner(),
33 }
34 }
35 Data::Struct(s) => {
36 // This might be None if there are errors.
37 let out = make_struct_impl(&input, s, error_store.sink());
38 DeriveDiffableOutput { out, errors: error_store.into_inner() }
39 }
40
41 Data::Union(_) => {
42 // Implement all unions as `Leaf`s
43 let out =
44 make_leaf(&input, AttrPosition::Union, error_store.sink());
45 DeriveDiffableOutput {
46 out: Some(out),
47 errors: error_store.into_inner(),
48 }
49 }
50 }
51 }
52
53 // TODO: allow the crate name to be passed in as a macro argument
54 fn daft_crate() -> Path {
55 parse_quote! { ::daft }
56 }
57
58 fn daft_lifetime() -> LifetimeParam {
59 // Use an underscore to avoid clashing with a user-defined `'daft` lifetime.
60 LifetimeParam::new(Lifetime::new("'__daft", Span::call_site()))
61 }
62
63 // We need to add our lifetime parameter 'daft and ensure any other parameters
64 // live as long as `daft`
65 fn add_lifetime_to_generics(
66 input: &DeriveInput,
67 daft_lt: &LifetimeParam,
68 ) -> Generics {
69 let mut new_generics = input.generics.clone();
70 new_generics
71 .lifetimes_mut()
72 .for_each(|lt| lt.bounds.push(daft_lt.lifetime.clone()));
73 new_generics.type_params_mut().for_each(|lt| {
74 lt.bounds.push(syn::TypeParamBound::Lifetime(daft_lt.lifetime.clone()))
75 });
76
77 // Add the 'daft lifetime to the beginning of the parameter list -- the
78 // exact order is not hugely important, but doing this makes tests simpler
79 // (they can just check the first element).
80 new_generics.params.insert(0, GenericParam::from(daft_lt.clone()));
81 new_generics
82 }
83
84 // Implement `Diffable` as a `Leaf`.
85 fn make_leaf(
86 input: &DeriveInput,
87 position: AttrPosition,
88 errors: ErrorSink<'_, syn::Error>,
89 ) -> TokenStream {
90 // The input should not have any daft attributes.
91 for attr in &input.attrs {
92 if attr.path().is_ident("daft") {
93 let res = attr.parse_nested_meta(|meta| {
94 if meta.path.is_ident("leaf") {
95 // Accept this for leaf structs, but not for anything else.
96 if position == AttrPosition::LeafStruct {
97 return Ok(());
98 }
99
100 errors.push_critical(meta.error(format!(
101 "this is unnecessary: the Diffable \
102 implementation {} is always a leaf",
103 position.as_purpose_str(),
104 )));
105 } else {
106 errors.push_critical(meta.error(format!(
107 "daft attributes are not allowed {}",
108 position.as_locative_str(),
109 )));
110 }
111
112 Ok(())
113 });
114 if let Err(err) = res {
115 errors.push_critical(err);
116 }
117 }
118 }
119
120 // Variants should not have any daft attributes.
121 let mut v = BanDaftAttrsVisitor { position, errors: errors.new_child() };
122 v.visit_data(&input.data);
123
124 // Even though errors might have occurred above, we *do* generate the
125 // implementation. That allows rust-analyzer to still understand that the
126 // `Diffable` impl exists.
127
128 let ident = &input.ident;
129 let daft_crate = daft_crate();
130 let daft_lt = daft_lifetime();
131
132 // The "where Self: #daft_lt" condition appears to be enough to satisfy
133 // Rust's borrow checker, so we don't need to add further constraints via
134 // `add_lifetime_to_generics`.
135 let (impl_gen, ty_gen, where_clause) = &input.generics.split_for_impl();
136
137 quote! {
138 impl #impl_gen #daft_crate::Diffable for #ident #ty_gen #where_clause
139 {
140 type Diff<#daft_lt> = #daft_crate::Leaf<&#daft_lt Self> where Self: #daft_lt;
141
142 fn diff<#daft_lt>(&#daft_lt self, other: &#daft_lt Self) -> Self::Diff<#daft_lt> {
143 #daft_crate::Leaf {before: self, after: other}
144 }
145 }
146 }
147 }
148
149 struct BanDaftAttrsVisitor<'a> {
150 position: AttrPosition,
151 errors: ErrorSink<'a, syn::Error>,
152 }
153
154 impl Visit<'_> for BanDaftAttrsVisitor<'_> {
155 fn visit_attribute(&mut self, attr: &Attribute) {
156 if attr.path().is_ident("daft") {
157 self.errors.push_critical(syn::Error::new_spanned(
158 attr,
159 format!(
160 "daft attributes are not allowed {}",
161 self.position.as_locative_str(),
162 ),
163 ));
164 }
165 }
166
167 fn visit_variant(&mut self, v: &syn::Variant) {
168 let old_position = self.position;
169 self.position = self.position.visit_variant();
170 syn::visit::visit_variant(self, v);
171 self.position = old_position;
172 }
173
174 fn visit_field(&mut self, f: &syn::Field) {
175 let old_position = self.position;
176 self.position = self.position.visit_field();
177 syn::visit::visit_field(self, f);
178 self.position = old_position;
179 }
180 }
181
182 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
183 enum AttrPosition {
184 // Catch-all in case something unexpected happens with the visitor.
185 General,
186 LeafStruct,
187 LeafStructField,
188 Enum,
189 Variant,
190 VariantField,
191 Union,
192 UnionField,
193 }
194
195 impl AttrPosition {
196 fn visit_variant(self) -> Self {
197 match self {
198 Self::Enum => Self::Variant,
199 Self::General
200 | Self::LeafStruct
201 | Self::LeafStructField
202 | Self::Variant
203 | Self::VariantField
204 | Self::Union
205 | Self::UnionField => Self::General,
206 }
207 }
208
209 fn visit_field(self) -> Self {
210 match self {
211 Self::LeafStruct => Self::LeafStructField,
212 Self::Variant => Self::VariantField,
213 Self::Union => Self::UnionField,
214 Self::General
215 | Self::LeafStructField
216 | Self::Enum
217 | Self::VariantField
218 | Self::UnionField => Self::General,
219 }
220 }
221
222 // purpose = prepositional phrase to indicate what something applies to,
223 // e.g. "the implementation for enums is always"
224 fn as_purpose_str(self) -> &'static str {
225 match self {
226 Self::General => "for this type",
227 Self::LeafStruct => "for structs annotated with #[daft(leaf)]",
228 Self::LeafStructField => {
229 "for fields on structs annotated with #[daft(leaf)]"
230 }
231 Self::Enum => "for enums",
232 Self::Variant => "for enum variants",
233 Self::VariantField => "for enum variant fields",
234 Self::Union => "for unions",
235 Self::UnionField => "for union fields",
236 }
237 }
238
239 // "locative" = indicating location: "not allowed on enums", etc.
240 fn as_locative_str(self) -> &'static str {
241 match self {
242 Self::General => "here",
243 Self::LeafStruct => "on structs annotated with #[daft(leaf)]",
244 Self::LeafStructField => {
245 "on fields of structs annotated with #[daft(leaf)]"
246 }
247 Self::Enum => "on enums",
248 Self::Variant => "on enum variants",
249 Self::VariantField => "on enum variant fields",
250 Self::Union => "on unions",
251 Self::UnionField => "on union fields",
252 }
253 }
254 }
255
256 fn make_struct_impl(
257 input: &DeriveInput,
258 s: &DataStruct,
259 errors: ErrorSink<'_, syn::Error>,
260 ) -> Option<TokenStream> {
261 let Some(struct_config) =
262 StructConfig::parse_from(&input.attrs, errors.new_child())
263 else {
264 // An error occurred parsing the struct configuration -- don't generate
265 // anything.
266 return None;
267 };
268
269 match struct_config.mode {
270 StructMode::Default => make_diff_struct(input, s, errors.new_child())
271 .map(|(generated_struct, diff_fields)| {
272 let diff_impl = make_diff_impl(input, &diff_fields);
273 // Uncomment for some debugging
274 // eprintln!("{generated_struct}");
275 // eprintln!("{diff_impl}");
276 quote! {
277 #generated_struct
278 #diff_impl
279 }
280 }),
281 StructMode::Leaf => {
282 Some(make_leaf(input, AttrPosition::LeafStruct, errors.new_child()))
283 }
284 }
285 }
286
287 /// Create the `Diff` struct
288 fn make_diff_struct(
289 input: &DeriveInput,
290 s: &DataStruct,
291 errors: ErrorSink<'_, syn::Error>,
292 ) -> Option<(TokenStream, DiffFields)> {
293 // The name of the original type
294 let vis = &input.vis;
295
296 // The name of the generated type
297 let name = parse_str::<Path>(&format!("{}Diff", input.ident)).unwrap();
298
299 // Copy over the non-exhaustive attribute from the original struct. (Do we
300 // need to copy over other attributes?)
301 let non_exhaustive =
302 input.attrs.iter().find(|attr| attr.path().is_ident("non_exhaustive"));
303
304 let daft_lt = daft_lifetime();
305
306 // We are creating a new type, so use only generics with our new lifetime
307 // and bounds.
308 //
309 // Most of the other generics users use `split_for_impl`, but that is geared
310 // specifically for trait implementations, not type definitions. For type
311 // definitions, we use the original `Generics`.
312 //
313 // The `ToTokens` implementation for `Generics` does not print the `where`
314 // clause, so we also include that separately.
315 let new_generics = add_lifetime_to_generics(input, &daft_lt);
316 let where_clause = &new_generics.where_clause;
317
318 let Some(diff_fields) =
319 DiffFields::new(&s.fields, where_clause.as_ref(), errors.new_child())
320 else {
321 // An error occurred parsing fields -- don't generate the diff struct.
322 return None;
323 };
324
325 // --- No more errors past this point ---
326
327 let struct_def = match &s.fields {
328 Fields::Named(_) => quote! {
329 #non_exhaustive
330 #vis struct #name #new_generics #where_clause #diff_fields
331
332 },
333 Fields::Unnamed(_) => quote! {
334 #non_exhaustive
335 #vis struct #name #new_generics #diff_fields #where_clause;
336 },
337 Fields::Unit => quote! {
338 // This is kinda silly
339 #non_exhaustive
340 #vis struct #name #new_generics {} #where_clause
341 },
342 };
343
344 // Generate PartialEq, Eq, and Debug implementations for the diff struct. We
345 // can't rely on `#[derive] because we want to put bounds on the
346 // Diffable::Diff types, not on the original types.
347 let (impl_gen, ty_gen, _) = &new_generics.split_for_impl();
348
349 let debug_impl = {
350 let where_clause = diff_fields.where_clause_with_trait_bound(
351 &parse_quote! { ::core::fmt::Debug },
352 );
353 let members = diff_fields.fields.members();
354
355 let finish = if non_exhaustive.is_some() {
356 quote! { .finish_non_exhaustive() }
357 } else {
358 quote! { .finish() }
359 };
360
361 let debug_body = match &s.fields {
362 Fields::Named(_) => {
363 quote! {
364 f.debug_struct(stringify!(#name))
365 #(
366 .field(stringify!(#members), &self.#members)
367 )*
368 #finish
369 }
370 }
371 Fields::Unnamed(_) => quote! {
372 f.debug_tuple(stringify!(#name))
373 #(
374 .field(&self.#members)
375 )*
376 #finish
377 },
378 Fields::Unit => quote! {
379 f.debug_struct(stringify!(#name))
380 #finish
381 },
382 };
383 quote! {
384 impl #impl_gen ::core::fmt::Debug for #name #ty_gen #where_clause {
385 fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
386 #debug_body
387 }
388 }
389 }
390 };
391
392 let partial_eq_impl = {
393 let where_clause = diff_fields.where_clause_with_trait_bound(
394 &parse_quote! { ::core::cmp::PartialEq },
395 );
396 let members = diff_fields.fields.members();
397
398 let partial_eq_body: Expr = parse_quote! {
399 #(self.#members == other.#members) && *
400 };
401
402 quote! {
403 impl #impl_gen ::core::cmp::PartialEq for #name #ty_gen #where_clause {
404 fn eq(&self, other: &Self) -> bool {
405 #partial_eq_body
406 }
407 }
408 }
409 };
410
411 let eq_impl = {
412 let where_clause = diff_fields
413 .where_clause_with_trait_bound(&parse_quote! { ::core::cmp::Eq });
414
415 quote! {
416 impl #impl_gen ::core::cmp::Eq for #name #ty_gen #where_clause {}
417 }
418 };
419
420 Some((
421 quote! {
422 #struct_def
423 #debug_impl
424 #partial_eq_impl
425 #eq_impl
426 },
427 diff_fields,
428 ))
429 }
430
431 /// Impl `Diffable` for the original struct
432 fn make_diff_impl(
433 input: &DeriveInput,
434 diff_fields: &DiffFields,
435 ) -> TokenStream {
436 // The name of the original type
437 let ident = &input.ident;
438
439 // The name of the generated type
440 let name = parse_str::<Path>(&format!("{}Diff", input.ident)).unwrap();
441 let diffs =
442 generate_field_diffs(&diff_fields.fields, &diff_fields.field_configs);
443
444 let daft_crate = daft_crate();
445 let daft_lt = daft_lifetime();
446 let new_generics = add_lifetime_to_generics(input, &daft_lt);
447
448 let (impl_gen, ty_gen, _) = &input.generics.split_for_impl();
449 let (_, new_ty_gen, where_clause) = &new_generics.split_for_impl();
450
451 quote! {
452 impl #impl_gen #daft_crate::Diffable for #ident #ty_gen
453 #where_clause
454 {
455 type Diff<#daft_lt> = #name #new_ty_gen where Self: #daft_lt;
456
457 fn diff<#daft_lt>(&#daft_lt self, other: &#daft_lt Self) -> #name #new_ty_gen {
458 Self::Diff {
459 #diffs
460 }
461 }
462 }
463 }
464 }
465
466 /// For a `Diff` struct generated by this derive macro, tracks the fields that
467 /// will be put into that struct.
468 ///
469 /// This also tracks the `where` clause.
470 ///
471 /// The goal of this wrapper is to provide helpers to iterate over the fields
472 /// and members.
473 struct DiffFields {
474 fields: Fields,
475 // Configuration for each field -- a vector with the same length as `self.fields`.
476 field_configs: Vec<FieldConfig>,
477 // The base where clause for the diff struct.
478 where_clause: WhereClause,
479 }
480
481 impl DiffFields {
482 /// None means there was an error parsing a config.
483 fn new(
484 fields: &Fields,
485 where_clause: Option<&WhereClause>,
486 errors: ErrorSink<'_, syn::Error>,
487 ) -> Option<Self> {
488 let (fields, field_configs) = match fields {
489 Fields::Named(fields) => {
490 let (named, configs) = fields
491 .named
492 .iter()
493 .filter_map(|field| {
494 Self::diff_field(field, errors.new_child())
495 })
496 .unzip();
497 (
498 Fields::Named(syn::FieldsNamed {
499 brace_token: fields.brace_token,
500 named,
501 }),
502 configs,
503 )
504 }
505 Fields::Unnamed(fields) => {
506 let (unnamed, configs) = fields
507 .unnamed
508 .iter()
509 .filter_map(|field| {
510 Self::diff_field(field, errors.new_child())
511 })
512 .unzip();
513 (
514 Fields::Unnamed(syn::FieldsUnnamed {
515 paren_token: fields.paren_token,
516 unnamed,
517 }),
518 configs,
519 )
520 }
521 Fields::Unit => (Fields::Unit, Vec::new()),
522 };
523
524 // Initialize an empty where clause if none was provided.
525 let where_clause =
526 where_clause.cloned().unwrap_or_else(|| WhereClause {
527 where_token: <Token![where]>::default(),
528 predicates: Default::default(),
529 });
530
531 if errors.has_critical_errors() {
532 None
533 } else {
534 Some(Self { fields, field_configs, where_clause })
535 }
536 }
537
538 /// Return a field for a diff with the appropriate type.
539 ///
540 /// If the type is ignored, or if there's an error parsing configuration,
541 /// return None.
542 fn diff_field(
543 f: &Field,
544 errors: ErrorSink<'_, syn::Error>,
545 ) -> Option<(Field, FieldConfig)> {
546 let Some(config) =
547 FieldConfig::parse_from(&f.attrs, errors.new_child())
548 else {
549 // None means there's an error parsing a config -- return None here,
550 // we'll emit errors at the top level.
551 return None;
552 };
553 if config.mode == FieldMode::Ignore {
554 // Skip over this field if there's an ignore.
555 return None;
556 }
557
558 // Always use the daft lifetime for the diff -- associations between the
559 // daft lifetime and existing parameters (both lifetime and type
560 // parameters) are created in `add_lifetime_to_generics`, e.g. `'a:
561 // '__daft`, or `T: '__daft`.
562 let lt = daft_lifetime();
563 let daft_crate = daft_crate();
564 let ty = &f.ty;
565 let mut f = f.clone();
566
567 f.ty = if config.mode == FieldMode::Leaf {
568 parse_quote_spanned! {f.span()=>
569 #daft_crate::Leaf<&#lt #ty>
570 }
571 } else {
572 parse_quote_spanned! {f.span()=>
573 <#ty as #daft_crate::Diffable>::Diff<#lt>
574 }
575 };
576
577 // Drop all attributes for now. We may want to carry some over in the
578 // future.
579 f.attrs = vec![];
580
581 Some((f, config))
582 }
583
584 /// Returns an iterator over field types.
585 fn types(&self) -> impl Iterator<Item = &syn::Type> {
586 self.fields.iter().map(|f| &f.ty)
587 }
588
589 /// Returns an expanded where clause where the fields have had a trait bound
590 /// applied to them.
591 fn where_clause_with_trait_bound(
592 &self,
593 trait_bound: &syn::TraitBound,
594 ) -> WhereClause {
595 let predicates = self.types().map(|ty| -> WherePredicate {
596 parse_quote_spanned! {ty.span()=>
597 #ty: #trait_bound
598 }
599 });
600
601 let mut where_clause = self.where_clause.clone();
602 where_clause.predicates.extend(predicates);
603
604 where_clause
605 }
606 }
607
608 impl ToTokens for DiffFields {
609 fn to_tokens(&self, tokens: &mut TokenStream) {
610 self.fields.to_tokens(tokens);
611 }
612 }
613
614 /// Generate a call to `diff` for each field of the original struct that isn't
615 /// ignored.
616 fn generate_field_diffs(
617 fields: &Fields,
618 // Should be the same length as `fields`.
619 field_configs: &[FieldConfig],
620 ) -> TokenStream {
621 let daft_crate = daft_crate();
622 let field_diffs =
623 fields.iter().zip(field_configs).enumerate().map(|(i, (f, config))| {
624 let field_name = match &f.ident {
625 Some(ident) => quote! { #ident },
626 None => {
627 let ident: Index = i.into();
628 quote! { #ident }
629 }
630 };
631 if config.mode == FieldMode::Leaf {
632 quote_spanned! {f.span()=>
633 #field_name: #daft_crate::Leaf {
634 before: &self.#field_name,
635 after: &other.#field_name
636 }
637 }
638 } else {
639 quote_spanned! {f.span()=>
640 #field_name: #daft_crate::Diffable::diff(
641 &self.#field_name,
642 &other.#field_name
643 )
644 }
645 }
646 });
647 quote! { #(#field_diffs),* }
648 }
649
650 #[derive(Debug)]
651 struct StructConfig {
652 mode: StructMode,
653 }
654
655 impl StructConfig {
656 fn parse_from(
657 attrs: &[Attribute],
658 errors: ErrorSink<'_, syn::Error>,
659 ) -> Option<Self> {
660 let mut mode = StructMode::Default;
661
662 for attr in attrs {
663 {
664 if attr.path().is_ident("daft") {
665 let res = attr.parse_nested_meta(|meta| {
666 if meta.path.is_ident("leaf") {
667 match mode {
668 StructMode::Default => {
669 mode = StructMode::Leaf;
670 }
671 StructMode::Leaf => {
672 errors.push_warning(meta.error(
673 "#[daft(leaf)] specified multiple times",
674 ));
675 }
676 }
677 } else {
678 errors.push_critical(meta.error(
679 "unknown attribute \
680 (supported attributes: leaf)",
681 ));
682 }
683
684 Ok(())
685 });
686
687 if let Err(err) = res {
688 errors.push_critical(err);
689 }
690 }
691 }
692 }
693
694 if errors.has_critical_errors() {
695 None
696 } else {
697 Some(Self { mode })
698 }
699 }
700 }
701
702 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
703 enum StructMode {
704 // The default mode: do a recursive diff for this struct.
705 Default,
706 // Use a `Leaf` for this struct.
707 Leaf,
708 }
709
710 #[derive(Debug)]
711 struct FieldConfig {
712 mode: FieldMode,
713 }
714
715 impl FieldConfig {
716 fn parse_from(
717 attrs: &[Attribute],
718 errors: ErrorSink<'_, syn::Error>,
719 ) -> Option<Self> {
720 let mut mode = FieldMode::Default;
721
722 for attr in attrs {
723 if attr.path().is_ident("daft") {
724 let res = attr.parse_nested_meta(|meta| {
725 if meta.path.is_ident("leaf") {
726 // #[daft(leaf)]
727 match mode {
728 FieldMode::Default => {
729 mode = FieldMode::Leaf;
730 }
731 FieldMode::Leaf => {
732 errors.push_warning(meta.error(
733 "#[daft(leaf)] specified multiple times",
734 ));
735 }
736 _ => {
737 errors.push_critical(meta.error(
738 "#[daft(leaf)] conflicts with \
739 other attributes",
740 ));
741 }
742 }
743 } else if meta.path.is_ident("ignore") {
744 // #[daft(ignore)]
745 match mode {
746 FieldMode::Default => {
747 mode = FieldMode::Ignore;
748 }
749 FieldMode::Ignore => {
750 errors.push_warning(meta.error(
751 "#[daft(ignore)] specified multiple times",
752 ));
753 }
754 _ => {
755 errors.push_critical(meta.error(
756 "#[daft(ignore)] conflicts with \
757 other attributes",
758 ));
759 }
760 }
761 } else {
762 errors.push_critical(meta.error(
763 "unknown attribute \
764 (supported attributes: leaf, ignore)",
765 ));
766 }
767
768 Ok(())
769 });
770 // We don't return an error from our callback, but syn might.
771 if let Err(err) = res {
772 errors.push_critical(err);
773 }
774 }
775 }
776
777 if errors.has_critical_errors() {
778 None
779 } else {
780 Some(Self { mode })
781 }
782 }
783 }
784
785 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
786 enum FieldMode {
787 // The default mode: do a recursive diff for this field.
788 Default,
789 // Use a `Leaf` for this field.
790 Leaf,
791 // Ignore this field.
792 Ignore,
793 }