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
//! Macro to specialize on the type of an expression.
//!
//! This crate implements *auto(de)ref specialization*:
//! A trick to do specialization in non-generic contexts on stable Rust.
//!
//! For the details of this technique, see:
//!  - [*Autoref-based stable specialization* by David Tolnay][autoref]
//!  - [*Generalized Autoref-Based Specialization* by Lukas Kalbertodt][autoderef]
//!
//! [autoref]: https://github.com/dtolnay/case-studies/blob/master/autoref-specialization/README.md
//! [autoderef]: http://lukaskalbertodt.github.io/2019/12/05/generalized-autoref-based-specialization.html
//!
//! # What it can and cannot do
//!
//! The auto(de)ref technique—and therefore this macro—is useless in generic
//! functions, as Rust resolves the specialization based on the bounds defined
//! on the generic context, not based on the actual type when instantiated.
//! (See [the example below](#in-a-generic-function) for a demonstration of
//! this.)
//!
//! In non-generic contexts, it's also mostly useless, as you probably already
//! know the exact type of all variables.
//!
//! The only place where using this can make sense is in the implementation of
//! macros that need to have different behaviour depending on the type of a
//! value passed to it. For example, a macro that prints the `Debug` output of
//! a value, but falls back to a default when it doesn't implement `Debug`.
//! (See [the example below](#in-a-macro) for a demonstration of
//! that.)
//!
//! # How to use it
//!
//! The basic syntax of the macro is:
//!
//! ```text
//! spez! {
//!     for <expression>;
//!     match <type> { <body> }
//!     [match <type> { <body> }]
//!     [...]
//! }
//! ```
//!
//! The examples below show more details.
//!
//! ## Simple specialization
//!
//! In the most simple case, you use this macro to match specific types:
//!
//! ```
//! # use spez::spez;
//! let x = 0;
//! spez! {
//!     for x;
//!     match i32 {
//!         println!("x is a 32-bit integer!");
//!     }
//!     match &str {
//!         println!("x is a string slice!");
//!         assert!(false);
//!     }
//! }
//! ```
//!
//! ## Return types
//!
//! Values can be returned from the matches, but have to be explicitly
//! specified for each `match`. They do not have to be the same for every
//! `match`.
//!
//! ```
//! # use spez::spez;
//! let x = 0;
//! let result = spez! {
//!     for x;
//!     match i32 -> &'static str {
//!         "x is a 32-bit integer!"
//!     }
//!     match &str -> i32 {
//!         123
//!     }
//! };
//! assert_eq!(result, "x is a 32-bit integer!");
//! ```
//!
//! ## Generic matches
//!
//! Generic matches are also possible. Generic variables can be defined
//! on the `match`, and a `where` clause can be added after the type.
//!
//! The matches are tried in order. The first matches get priority over later
//! ones, even if later ones are perfect matches.
//!
//! ```
//! # use spez::spez;
//! let x = 123i32;
//! let result = spez! {
//!     for x;
//!     match<T> T where i8: From<T> -> i32 {
//!         0
//!     }
//!     match<T: std::fmt::Debug> T -> i32 {
//!         1
//!     }
//!     match i32 -> i32 {
//!         2
//!     }
//! };
//! assert_eq!(result, 1);
//! ```
//!
//! # Consuming the input
//!
//! The input (after the `for`) is consumed and made available to the `match`
//! bodies.
//!
//! (If you don't want to consume the input, take a reference and also prepend
//! a `&` to the types you're matching.)
//!
//! ```
//! # use spez::spez;
//! # use core::ops::Deref;
//! let x = Box::new(123);
//! let result = spez! {
//!     for x;
//!     match<T: Deref<Target = i32>> T -> i32 {
//!         *x
//!     }
//!     match i32 -> i32 {
//!         x
//!     }
//! };
//! assert_eq!(result, 123);
//! ```
//!
//! # Expressions as input
//!
//! Not just variable names, but full expressions can be given as input.
//! However, if you want to refer to them from the match bodies, you need to
//! prepend `name =` to give the input a name.
//!
//! ```
//! # use spez::spez;
//! let result = spez! {
//!     for 1 + 1;
//!     match i32 -> i32 { 0 }
//!     match i64 -> i32 { 1 }
//! };
//! assert_eq!(result, 0);
//! ```
//!
//! ```
//! # use spez::spez;
//! let result = spez! {
//!     for x = 1 + 1;
//!     match i32 -> i32 { x }
//!     match i64 -> i32 { 1 }
//! };
//! assert_eq!(result, 2);
//! ```
//!
//! # Capturing variables
//!
//! Unfortunately, you can't refer to variables of the scope around the `spez! {}` macro:
//!
//! ```compile_fail
//! let a = 1;
//! let result = spez! {
//!     for x = 1;
//!     match i32 {
//!         println!("{}", a); // ERROR
//!     }
//! };
//! ```
//!
//! # In a generic function
//!
//! As mentioned above, the macro is of not much use in generic context, as the
//! specialization is resolved based on the bounds rather than on the actual
//! type in the instantiation of the generic function:
//!
//! ```
//! # use spez::spez;
//! # use std::fmt::Debug;
//! fn f<T: Debug>(v: T) -> &'static str {
//!     spez! {
//!         for v;
//!         match i32 -> &'static str {
//!             ":)"
//!         }
//!         match<T: Debug> T -> &'static str {
//!             ":("
//!         }
//!         match<T> T -> &'static str {
//!             ":(("
//!         }
//!     }
//! }
//! assert_eq!(f(0i32), ":(");
//! ```
//!
//! # In a macro
//!
//! This is a demonstration of a macro that prints the `Debug` output of a
//! value, but falls back to `"<object of type ...>"` if it doesn't implement
//! `Debug`.
//!
//! ```
//! # use spez::spez;
//! # use std::fmt::Debug;
//! macro_rules! debug {
//!     ($e:expr) => {
//!         spez! {
//!             for x = $e;
//!             match<T: Debug> T {
//!                 println!("{:?}", x);
//!             }
//!             match<T> T {
//!                 println!("<object of type {}>", std::any::type_name::<T>());
//!             }
//!         }
//!     }
//! }
//! debug!(123);
//! # struct NoDebugType;
//! debug!(NoDebugType);
//! ```

extern crate proc_macro;

mod parse;

use parse::Args;
use proc_macro::TokenStream;
use proc_macro2::Span;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;

/// Specialize based on the type of an expression.
///
/// See the [crate level documentation](index.html).
#[proc_macro]
pub fn spez(tokens: TokenStream) -> TokenStream {
	spez_impl(syn::parse_macro_input!(tokens)).into()
}

fn refs(n: usize) -> TokenStream2 {
	let mut refs = TokenStream2::new();
	for _ in 0..n {
		refs.extend(quote![&]);
	}
	refs
}

fn spez_impl(args: Args) -> TokenStream2 {
	let mut traits = TokenStream2::new();

	let param_def = match args.param {
		Some(param) => quote! {
			let #param = self.0.take().unwrap();
			let _ = #param; // Suppress unused variable warning.
		},
		None => quote! {},
	};

	let n_arms = args.arms.len();

	for (i, arm) in args.arms.into_iter().enumerate() {
		let name = syn::Ident::new(&format!("Match{}", i + 1), Span::call_site());
		let body = arm.body;
		let ty = arm.ty;
		let generics = &arm.generics;
		let where_clause = &arm.generics.where_clause;
		let refs = refs(n_arms - i - 1);
		let return_type = match arm.return_type {
			Some(return_type) => quote! { #return_type },
			None => quote! { () },
		};

		traits.extend(quote! {
			trait #name {
				type Return;
				fn spez(&self) -> Self::Return;
			}
			impl #generics #name for #refs Match<#ty> #where_clause {
				type Return = #return_type;
				fn spez(&self) -> Self::Return {
					#param_def
					#body
				}
			}
		});
	}

	let expr = args.expr;
	let refs = refs(n_arms);

	quote! {
		{
			struct Match<T>(core::cell::Cell<Option<T>>);
			#traits
			(#refs Match(core::cell::Cell::new(Some(#expr)))).spez()
		}
	}
}