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

extern crate proc_macro;
//#[macro_use]
extern crate quote;
extern crate syn;
extern crate synstructure;

use syn::{parse_macro_input, DeriveInput};
use syn::spanned::Spanned;
use quote::{quote, quote_spanned};


// Look https://github.com/dtolnay/syn/blob/master/examples/heapsize/heapsize_derive/src/lib.rs for a more recent similar derive.

//WITH proc_macro
// #[proc_macro_derive(Quantifiable)]
// pub fn quantifiable_macro_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
// 	//let ast = syn::parse(input).unwrap();
// 	let mut ast = syn::parse_macro_input(&input.to_string()).unwrap();
// 	//let mut ast = syn::parse_macro_input!(input);
// 	let style = synstructure::BindStyle::Ref.into();
// 	//Collect all the fields into a total_memory method.
// 	let total_memory_body = synstructure::each_field(&mut ast, &style, |binding| {
// 			Some(quote! {
// 					sum += ::quantify::Quantifiable::total_memory(#binding);
// 					})
// 			});
// 	//Collect all the fields into a forecast_total_memory method.
// 	let forecast_total_memory_body = synstructure::each_field(&mut ast, &style, |binding| {
// 			Some(quote! {
// 					sum += ::quantify::Quantifiable::forecast_total_memory(#binding);
// 					})
// 			});
// 	//The name of the type for which we are implementing Quantifiable.
// 	let name = &ast.ident;
// 	let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
// 	let mut where_clause = where_clause.clone();
// 	//We added the where condition member_name:Quantifiable for each member.
// 	for param in &ast.generics.ty_params {
// 		where_clause.predicates.push(syn::WherePredicate::BoundPredicate(syn::WhereBoundPredicate {
// 			bound_lifetimes: Vec::new(),
// 			bounded_ty: syn::Ty::Path(None, param.ident.clone().into()),
// 			//bounds: vec![syn::TypeParamBound::Trait(
// 			bounds: vec![syn::TyParamBound::Trait(
// 				syn::PolyTraitRef {
// 					bound_lifetimes: Vec::new(),
// 					trait_ref: syn::parse_path("::quantifiable::Quantifiable").unwrap(),
// 				},
// 				syn::TraitBoundModifier::None
// 			)],
// 		}))
// 		//where_clause.predicates.push(syn::WherePredicate::Type(syn::PredicateType {
// 		//	lifetimes: None,
// 		//	bounded_ty: syn::Ty::Path(None, param.ident.clone().into()),
// 		//	bounds: syn::parse_path("::quantifiable::Quantifiable").unwrap(),
// 		//}))
// 	}
// 	//Build the token sequence.
// 	let tokens = quote! {
// 		impl #impl_generics ::quantify::Quantifiable for #name #ty_generics #where_clause {
// #[inline]
// #[allow(unused_variables, unused_mut, unreachable_code)]
// 			fn total_memory(&self) -> usize {
// 				let mut sum = 0;
// 				match *self {
// 					#total_memory_body
// 				}
// 				sum
// 			}
// 			fn print_memory_breakdown(&self)
// 			{
// 				unimplemented!();
// 			}
// 			fn forecast_total_memory(&self) -> usize
// 			{
// 				let mut sum = 0;
// 				match *self {
// 					#forecast_total_memory_body
// 				}
// 				sum
// 			}
// 		}
// 	};
// 	//tokens
// 	tokens.to_string().parse().unwrap()
// }

//WITH proc_macro2 and syn-1.0
// https://doc.rust-lang.org/proc_macro/index.html
// https://docs.rs/proc-macro2/1.0.24/proc_macro2/index.html
// https://docs.rs/syn/1.0.44/syn/index.html
#[proc_macro_derive(Quantifiable)]
pub fn quantifiable_macro_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
	//let ast = syn::parse(input).unwrap();
	//let mut ast = syn::parse_macro_input(&input.to_string()).unwrap();
	//let input = proc_macro2::TokenStream::from(input);
	let ast = parse_macro_input!(input as DeriveInput);
	//let mut ast = syn::parse_macro_input!(input);
	//let style = synstructure::BindStyle::Ref.into();
	//Collect all the fields into a total_memory method.
	//let total_memory_body = synstructure::each_field(&mut ast, &style, |binding| {
	//		Some(quote! {
	//				sum += ::quantify::Quantifiable::total_memory(#binding);
	//				})
	//		});
	////Collect all the fields into a forecast_total_memory method.
	//let forecast_total_memory_body = synstructure::each_field(&mut ast, &style, |binding| {
	//		Some(quote! {
	//				sum += ::quantify::Quantifiable::forecast_total_memory(#binding);
	//				})
	//		});
	let total_memory_body = quantifiable_total_memory_expression(&ast.data);
	let forecast_total_memory_body = quantifiable_forecast_total_memory_expression(&ast.data);
	//The name of the type for which we are implementing Quantifiable.
	let name = &ast.ident;
	let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
	let where_clause = where_clause.clone();
	//We added the where condition member_name:Quantifiable for each member.
	// for param in &ast.generics.ty_params {
	// 	where_clause.predicates.push(syn::WherePredicate::BoundPredicate(syn::WhereBoundPredicate {
	// 		bound_lifetimes: Vec::new(),
	// 		bounded_ty: syn::Ty::Path(None, param.ident.clone().into()),
	// 		//bounds: vec![syn::TypeParamBound::Trait(
	// 		bounds: vec![syn::TyParamBound::Trait(
	// 			syn::PolyTraitRef {
	// 				bound_lifetimes: Vec::new(),
	// 				trait_ref: syn::parse_path("::quantifiable::Quantifiable").unwrap(),
	// 			},
	// 			syn::TraitBoundModifier::None
	// 		)],
	// 	}))
	// 	//where_clause.predicates.push(syn::WherePredicate::Type(syn::PredicateType {
	// 	//	lifetimes: None,
	// 	//	bounded_ty: syn::Ty::Path(None, param.ident.clone().into()),
	// 	//	bounds: syn::parse_path("::quantifiable::Quantifiable").unwrap(),
	// 	//}))
	// }
	//Build the token sequence.
	let tokens = quote! {
		impl #impl_generics crate::quantify::Quantifiable for #name #ty_generics #where_clause {
#[inline]
#[allow(unused_variables, unused_mut, unreachable_code)]
			fn total_memory(&self) -> usize {
				#total_memory_body
			}
			fn print_memory_breakdown(&self)
			{
				unimplemented!();
			}
			fn forecast_total_memory(&self) -> usize
			{
				#forecast_total_memory_body
			}
		}
	};
	//tokens
	//tokens.to_string().parse().unwrap()
	proc_macro::TokenStream::from(tokens)
}

///Create an expression for the total_memory method.
fn quantifiable_total_memory_expression(data: &syn::Data) -> proc_macro2::TokenStream
{
	match *data
	{
		syn::Data::Struct(ref data) =>
		{
			match data.fields
			{
				syn::Fields::Named(ref fields) => 
				{
					//An struct with named fields. Blah{name1:type1, name2:type2, ...}
					let fit=fields.named.iter().map(|field|{
						let name=&field.ident;
						quote_spanned!{ field.span() =>
							crate::quantify::Quantifiable::total_memory(&self.#name)
						}
					});
					quote!{ 0 #(+ #fit)* }
				}
				syn::Fields::Unnamed(ref fields) =>
				{
					let fit=fields.unnamed.iter().enumerate().map(|(i,field)|{
						let index=syn::Index::from(i);
						quote_spanned!{ field.span() =>
							crate::quantify::Quantifiable::total_memory(&self.#index)
						}
					});
					quote!{ 0 #(+ #fit)* }
				}
				syn::Fields::Unit => quote!(0),
			}
		},
		syn::Data::Enum(ref data) =>
		{
			//https://docs.rs/syn/1.0.44/syn/struct.DataEnum.html
			let vit = data.variants.iter().map(|variant|{
				let vname = &variant.ident;
				match variant.fields
				{
					syn::Fields::Named(ref fields) => 
					{
						//An struct with named fields. Blah{name1:type1, name2:type2, ...}
						let fit=fields.named.iter().map(|field|{
							let name=&field.ident;
							quote_spanned!{ field.span() =>
								crate::quantify::Quantifiable::total_memory(#name)
							}
						});
						let sum =quote!{ 0 #(+ #fit)* };
						let fit=fields.named.iter().map(|field|{
							let name=&field.ident;
							quote_spanned!{ field.span() =>
								#name
							}
						});
						let args = quote!{ #(#fit,)* };
						quote_spanned!{ variant.span() =>
							Self::#vname{#args} => #sum,
						}
					},
					syn::Fields::Unnamed(ref fields) =>
					{
						let fit=fields.unnamed.iter().enumerate().map(|(i,field)|{
							//let index=syn::Index::from(i);
							let arg=quote::format_ident!("u{}",i);
							quote_spanned!{ field.span() =>
								crate::quantify::Quantifiable::total_memory(#arg)
							}
						});
						let sum = quote!{ 0 #(+ #fit)* };
						let fit=fields.unnamed.iter().enumerate().map(|(i,field)|{
							//let index=syn::Index::from(i);
							let arg=quote::format_ident!("u{}",i);
							quote_spanned!{ field.span() =>
								#arg
							}
						});
						let args = quote!{ #(#fit,)* };
						quote_spanned!{ variant.span() =>
							Self::#vname(#args) => #sum,
						}
					},
					syn::Fields::Unit =>
					{
						//quote!(0),
						quote!(Self::#vname => 0,)
					},
				}
			});
			//FIXME: should be max instead of plus.
			let tokens=quote!{ match self { #( #vit)* } };
			//quote!{compile_error!(stringify!{#tokens});#tokens}
			tokens
		},
		syn::Data::Union(_) => unimplemented!(),
	}
}

fn quantifiable_forecast_total_memory_expression(data: &syn::Data) -> proc_macro2::TokenStream
{
	match *data
	{
		syn::Data::Struct(ref data) =>
		{
			match data.fields
			{
				syn::Fields::Named(ref fields) => 
				{
					//An struct with named fields. Blah{name1:type1, name2:type2, ...}
					let fit=fields.named.iter().map(|field|{
						let name=&field.ident;
						quote_spanned!{ field.span() =>
							crate::quantify::Quantifiable::forecast_total_memory(&self.#name)
						}
					});
					quote!{ 0 #(+ #fit)* }
				}
				syn::Fields::Unnamed(ref fields) =>
				{
					let fit=fields.unnamed.iter().enumerate().map(|(i,field)|{
						let index=syn::Index::from(i);
						quote_spanned!{ field.span() =>
							crate::quantify::Quantifiable::forecast_total_memory(&self.#index)
						}
					});
					quote!{ 0 #(+ #fit)* }
				}
				syn::Fields::Unit => quote!(0),
			}
		},
		syn::Data::Enum(ref data) =>
		{
			//https://docs.rs/syn/1.0.44/syn/struct.DataEnum.html
			let vit = data.variants.iter().map(|variant|{
				let vname = &variant.ident;
				match variant.fields
				{
					syn::Fields::Named(ref fields) => 
					{
						//An struct with named fields. Blah{name1:type1, name2:type2, ...}
						let fit=fields.named.iter().map(|field|{
							let name=&field.ident;
							quote_spanned!{ field.span() =>
								crate::quantify::Quantifiable::total_memory(#name)
							}
						});
						let sum =quote!{ 0 #(+ #fit)* };
						let fit=fields.named.iter().map(|field|{
							let name=&field.ident;
							quote_spanned!{ field.span() =>
								#name
							}
						});
						let args = quote!{ #(#fit,)* };
						quote_spanned!{ variant.span() =>
							Self::#vname{#args} => #sum,
						}
					},
					syn::Fields::Unnamed(ref fields) =>
					{
						let fit=fields.unnamed.iter().enumerate().map(|(i,field)|{
							//let index=syn::Index::from(i);
							let arg=quote::format_ident!("u{}",i);
							quote_spanned!{ field.span() =>
								crate::quantify::Quantifiable::total_memory(#arg)
							}
						});
						let sum = quote!{ 0 #(+ #fit)* };
						let fit=fields.unnamed.iter().enumerate().map(|(i,field)|{
							//let index=syn::Index::from(i);
							let arg=quote::format_ident!("u{}",i);
							quote_spanned!{ field.span() =>
								#arg
							}
						});
						let args = quote!{ #(#fit,)* };
						quote_spanned!{ variant.span() =>
							Self::#vname(#args) => #sum,
						}
					},
					syn::Fields::Unit =>
					{
						//quote!(0),
						quote!(Self::#vname => 0,)
					},
				}
			});
			//FIXME: should be max instead of plus.
			let tokens=quote!{ match self { #( #vit)* } };
			//quote!{compile_error!(stringify!{#tokens});#tokens}
			tokens
		},
		syn::Data::Union(_) => unimplemented!(),
	}
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}