Debian Codegraph @

core/proc-macros/src/content_hash.rs

raw
1 use proc_macro2::Ident;
2 use proc_macro2::TokenStream;
3 use quote::format_ident;
4 use quote::quote;
5 use quote::quote_spanned;
6 use syn::Data;
7 use syn::Field;
8 use syn::Fields;
9 use syn::GenericParam;
10 use syn::Generics;
11 use syn::Index;
12 use syn::Type;
13 use syn::parse_quote;
14 use syn::spanned::Spanned as _;
15
16 pub fn add_trait_bounds(mut generics: Generics) -> Generics {
17 for param in &mut generics.params {
18 if let GenericParam::Type(type_param) = param {
19 type_param
20 .bounds
21 .push(parse_quote!(::jj_core::content_hash::ContentHash));
22 }
23 }
24 generics
25 }
26
27 pub fn generate_hash_impl(data: &Data) -> TokenStream {
28 match data {
29 Data::Struct(data) => match &data.fields {
30 Fields::Named(fields) => {
31 let hash_statements = fields.named.iter().map(|f| {
32 let field_name = &f.ident;
33 let ty = &f.ty;
34 quote_spanned! {ty.span()=>
35 <#ty as ::jj_core::content_hash::ContentHash>::hash(
36 &self.#field_name, state);
37 }
38 });
39 quote! {
40 #(#hash_statements)*
41 }
42 }
43 Fields::Unnamed(fields) => {
44 let hash_statements = fields.unnamed.iter().enumerate().map(|(i, f)| {
45 let index = Index::from(i);
46 let ty = &f.ty;
47 quote_spanned! {ty.span() =>
48 <#ty as ::jj_core::content_hash::ContentHash>::hash(&self.#index, state);
49 }
50 });
51 quote! {
52 #(#hash_statements)*
53 }
54 }
55 Fields::Unit => {
56 quote! {}
57 }
58 },
59 // Generates a match statement with a match arm and hash implementation
60 // for each of the variants in the enum.
61 Data::Enum(data) => {
62 let match_hash_statements = data.variants.iter().enumerate().map(|(i, v)| {
63 let variant_id = &v.ident;
64 match &v.fields {
65 Fields::Named(fields) => {
66 let bindings = enum_bindings(fields.named.iter());
67 let hash_statements =
68 hash_statements_for_enum_fields(i, fields.named.iter());
69 quote_spanned! {v.span() =>
70 Self::#variant_id{ #(#bindings),* } => {
71 #(#hash_statements)*
72 }
73 }
74 }
75 Fields::Unnamed(fields) => {
76 let bindings = enum_bindings(fields.unnamed.iter());
77 let hash_statements =
78 hash_statements_for_enum_fields(i, fields.unnamed.iter());
79 quote_spanned! {v.span() =>
80 Self::#variant_id( #(#bindings),* ) => {
81 #(#hash_statements)*
82 }
83 }
84 }
85 Fields::Unit => {
86 let ix = index_to_ordinal(i);
87 quote_spanned! {v.span() =>
88 Self::#variant_id => {
89 ::jj_core::content_hash::ContentHash::hash(&#ix, state);
90 }
91 }
92 }
93 }
94 });
95 quote! {
96 match self {
97 #(#match_hash_statements)*
98 }
99 }
100 }
101 Data::Union(_) => unimplemented!("ContentHash cannot be derived for unions."),
102 }
103 }
104
105 // The documentation for `ContentHash` specifies that the hash impl for each
106 // enum variant should hash the ordinal number of the enum variant as a little
107 // endian u32 before hashing the variant's fields, if any.
108 fn index_to_ordinal(ix: usize) -> u32 {
109 u32::try_from(ix).expect("The number of enum variants overflows a u32.")
110 }
111
112 fn enum_bindings_with_type<'a>(fields: impl IntoIterator<Item = &'a Field>) -> Vec<(Type, Ident)> {
113 fields
114 .into_iter()
115 .enumerate()
116 .map(|(i, f)| {
117 // If the field is named, use the name, otherwise generate a placeholder name.
118 (
119 f.ty.clone(),
120 f.ident.clone().unwrap_or(format_ident!("field_{}", i)),
121 )
122 })
123 .collect::<Vec<_>>()
124 }
125
126 fn enum_bindings<'a>(fields: impl IntoIterator<Item = &'a Field>) -> Vec<Ident> {
127 enum_bindings_with_type(fields)
128 .into_iter()
129 .map(|(_, b)| b)
130 .collect()
131 }
132
133 fn hash_statements_for_enum_fields<'a>(
134 index: usize,
135 fields: impl IntoIterator<Item = &'a Field>,
136 ) -> Vec<TokenStream> {
137 let ix = index_to_ordinal(index);
138 let typed_bindings = enum_bindings_with_type(fields);
139 let mut hash_statements = Vec::with_capacity(typed_bindings.len() + 1);
140 hash_statements.push(quote! {::jj_core::content_hash::ContentHash::hash(&#ix, state);});
141 for (ty, b) in &typed_bindings {
142 hash_statements.push(quote_spanned! {b.span() =>
143 <#ty as ::jj_core::content_hash::ContentHash>::hash(#b, state);
144 });
145 }
146
147 hash_statements
148 }