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
//! Attribute macro that automatically implements a symmetric trait
//!
//! # Motivation
//! There is a class of binary operators known as symmetric operators.
//! Formally, let `F: D x D -> V` be a binary operator, `F` is symmetric if
//! `F(a, b) = F(b, a)` for any `(a, b)`.
//!
//! Such pattern arises naturally in computational geometry. For example,
//! `is_intersected(a: Shape1<Transform>, b: Shape2<Transform>) -> bool`
//! decides whether two transformed shapes intersects. Or
//! `distance(a: Shape1<Transform>, b: Shape2<Transform>) -> f32` computes
//! the distance between two transformed shapes. Both functions could be seen
//! as symmetric binary operators. More importantly, the types of the arguments
//! can be heterogeneous. We can have `point.distance(circle)` for example.
//!
//! It is very tempting to represent an operator with a trait:
//! ```no_run
//! trait Distance<Other> {
//!     fn distance(&self, other: &Other) -> f64;
//! }
//! ```
//! And given different shapes:
//! ```no_run
//! struct Point2D {
//!     x: f64,
//!     y: f64,
//! }
//!
//! struct Disk {
//!     center: Point2D,
//!     radius: f64
//! }
//! ```
//! We can have
//! ```no_run
//! # trait Distance<Other> {
//! #     fn distance(&self, other: &Other) -> f64;
//! # }
//! # struct Point2D {
//! #     x: f64,
//! #     y: f64,
//! # }
//! # struct Disk {
//! #     center: Point2D,
//! #     radius: f64
//! # }
//! impl Distance<Point2D> for Point2D {
//!     fn distance(&self, other: &Point2D) -> f64 {
//!         let dx = self.x - other.x;
//!         let dy = self.y - other.y;
//!         (dx * dx + dy * dy).sqrt()
//!     }
//! }
//!
//! impl Distance<Disk> for Point2D {
//!     fn distance(&self, other: &Disk) -> f64 {
//!         let p_diff = self.distance(&other.center);
//!         if p_diff.le(&other.radius) {
//!             0.0_f64
//!         } else {
//!             p_diff - other.radius
//!         }
//!     }
//! }
//! ```
//! It is very helpful to also have `impl Distance<Point2D> for Disk`, but we
//! cannot use generic implementation due to conflicting implementation.
//! ```compile_fail
//! # trait Distance<Other> {
//! #     fn distance(&self, other: &Other) -> f64;
//! # }
//! # struct Point2D {
//! #     x: f64,
//! #     y: f64,
//! # }
//! # struct Disk {
//! #     center: Point2D,
//! #     radius: f64
//! # }
//! # impl Distance<Point2D> for Point2D {
//! #     fn distance(&self, other: &Point2D) -> f64 {
//! #         let dx = self.x - other.x;
//! #         let dy = self.y - other.y;
//! #         (dx * dx + dy * dy).sqrt()
//! #     }
//! # }
//! # impl Distance<Disk> for Point2D {
//! #     fn distance(&self, other: &Disk) -> f64 {
//! #         let p_diff = self.distance(&other.center);
//! #         if p_diff.le(&other.radius) {
//! #             0.0_f64
//! #         } else {
//! #             p_diff - other.radius
//! #         }
//! #     }
//! # }
//! // Conflicting implementation because this generic implementation makes
//! // Disk: Distance<Point2D>, which in turn implements
//! // Distance<Disk> for Point2D again.
//! impl<T, U> Distance<U> for T
//! where
//!     U: Distance<T>, {
//!     fn distance(&self, other: &U) -> f64 {
//!         other.distance(self)
//!     }
//! }
//! ```
//! So one has to manually implement:
//! ```no_run
//! # trait Distance<Other> {
//! #     fn distance(&self, other: &Other) -> f64;
//! # }
//! # struct Point2D {
//! #     x: f64,
//! #     y: f64,
//! # }
//! # struct Disk {
//! #     center: Point2D,
//! #     radius: f64
//! # }
//! # impl Distance<Point2D> for Point2D {
//! #     fn distance(&self, other: &Point2D) -> f64 {
//! #         let dx = self.x - other.x;
//! #         let dy = self.y - other.y;
//! #         (dx * dx + dy * dy).sqrt()
//! #     }
//! # }
//! # impl Distance<Disk> for Point2D {
//! #     fn distance(&self, other: &Disk) -> f64 {
//! #         let p_diff = self.distance(&other.center);
//! #         if p_diff.le(&other.radius) {
//! #             0.0_f64
//! #         } else {
//! #             p_diff - other.radius
//! #         }
//! #     }
//! # }
//! impl Distance<Point2D> for Disk {
//!     fn distance(&self, other: &Point2D) -> f64 {
//!         other.distance(self)
//!     }
//! }
//! ```
//! This crates tries to address this problem by introducing an attribute
//! macro to automatically implement the symmetric case.
//!
//! # Note
//! There are several constraints for a trait to be deemed symmetric:
//! * The trait must be generic, with the first non-lifetime parameter being the
//!   type for the symmetry.
//!   
//!   e.g.
//!   ```no_run
//!   trait SymmetricTrait<'a, Other, MoreType> {
//!       fn operator(&self, other: &Other) -> MoreType;
//!   }
//!   trait NotSymmetricTrait<'a, MoreType, Other> {
//!       fn operator(&self, other: &Other) -> MoreType;
//!   }
//!   ```
//! * All the methods in the trait must take exactly 2 arguments, where the
//!   first argument is `self` and the other argument is of the type for the
//!   symmetry. The two arguments must have the same family in the sense that
//!   they should both or neither be reference or mutable.
//!   
//!   e.g.
//!   ```no_run
//!   # type SomeType = i32;
//!   trait SymmetricTrait<Other> {
//!       fn operator_1(&self, other: &Other) -> SomeType;
//!       fn operator_2(self, other: Other) -> SomeType;
//!       fn operator_3(&mut self, other: &mut Other) -> SomeType;
//!   }
//!   trait NotSymmetricTrait<Other> {
//!       // reference mismatch
//!       fn operator_1(&self, other: Other) -> SomeType;
//!       // mutability mismatch
//!       fn operator_2(&self, other: &mut Other) -> SomeType;
//!       // incorrect arguments order
//!       fn operator_3(other: &mut Other, this: &mut Self) -> SomeType;
//!       // incorrect number of arguments
//!       fn operator_4(&self, other: &Other, more_other: &Other) -> SomeType;
//!   }
//!   ```
//! Associated types in a trait are allowed, and they will be transformed as:
//! ```no_run
//! # struct A {}
//! # struct B {}
//! trait TraitWithType<Other> {
//!     type SomeType;
//! }
//! impl TraitWithType<B> for A {
//!     type SomeType = i32;
//! }
//! // #[symmetric] will expands to
//! impl TraitWithType<A> for B {
//!     type SomeType = <A as TraitWithType<B>>::SomeType;
//! }
//! ```
//!  
//! # Example
//! ```
//! use symm_impl::symmetric;
//!
//! trait Distance<Other> {
//!     fn distance(&self, other: &Other) -> f64;
//! }
//! struct Point2D {
//!     x: f64,
//!     y: f64,
//! }
//! struct Disk {
//!     center: Point2D,
//!     radius: f64
//! }
//! impl Distance<Point2D> for Point2D {
//!     fn distance(&self, other: &Point2D) -> f64 {
//!         let dx = self.x - other.x;
//!         let dy = self.y - other.y;
//!         (dx * dx + dy * dy).sqrt()
//!     }
//! }
//! #[symmetric]
//! impl Distance<Disk> for Point2D {
//!     fn distance(&self, other: &Disk) -> f64 {
//!         let p_diff = self.distance(&other.center);
//!         if p_diff.le(&other.radius) {
//!             0.0_f64
//!         } else {
//!             p_diff - other.radius
//!         }
//!     }
//! }
//! /* Expands to
//! impl Distance<Point2D> for Disk {
//!     #[allow(unused_mut)]
//!     #[inline]
//!     fn distance(&self, other: &Point2D) -> f64 {
//!         <Point2D as Distance<Disk>>::distance(other, self)
//!     }
//! }
//! */
//!
//! let p = Point2D { x: 5.0, y: 4.0 };
//! let c = Disk {
//!     center: Point2D { x: 1.0, y: -2.0 },
//!     radius: 3.0,
//! };
//! assert_eq!(p.distance(&c), c.distance(&p));
//! ```

use std::{iter::FromIterator, mem};

use proc_macro2::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree};
use quote::quote;
use syn::{
    parse::Parser, parse_macro_input, parse_quote, spanned::Spanned, Attribute, Block, FnArg,
    GenericArgument, ImplItem, ItemImpl, Pat, PatIdent, PathArguments, Type,
};

/// See module-level documentation
#[proc_macro_attribute]
pub fn symmetric(
    _attr: proc_macro::TokenStream,
    item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    let ast = parse_macro_input!(item as ItemImpl);

    let mirrored_ast = mirror(ast.clone());

    let expanded = quote! {
        #ast

        #mirrored_ast
    };

    proc_macro::TokenStream::from(expanded)
}

/// Take a syntax tree of impl and generate the mirror implementation for a
/// symmetric trait.
fn mirror(mut ast: ItemImpl) -> TokenStream {
    if ast.trait_.is_none() {
        // not a trait implementation
        return to_compile_error(
            "#[symmetric] can only be used on trait implementation".to_string(),
            Span::call_site(),
        );
    }
    let trait_ = ast.trait_.as_mut().unwrap();
    if let Some(bang) = trait_.0 {
        // negative marker trait
        return to_compile_error(
            "#[symmetric] cannot be used on negative trait bound".to_string(),
            bang.span.clone(),
        );
    }
    // it is guaranteed that trait_.1 is a non-empty path sequence since this is a trait impl
    let original_trait = trait_.1.clone();
    let last_segment = trait_.1.segments.last_mut().unwrap();
    let trait_generics = match &mut last_segment.arguments {
        PathArguments::AngleBracketed(generics) => generics,
        _ => {
            // no generics arguments
            return to_compile_error("expected a generic trait".to_string(), trait_.1.span());
        }
    };

    // deduce the "other" type for this trait
    let other_type = trait_generics.args.iter_mut().find_map(|arg| {
        if let GenericArgument::Type(type_arg) = arg {
            Some(type_arg)
        } else {
            None
        }
    });
    if other_type.is_none() {
        // no type arguments
        return to_compile_error(
            "symmetric trait must contain at least 1 type argument".to_string(),
            trait_generics.span(),
        );
    }
    let other_type = other_type.unwrap();

    // deduce the "self" type for this trait
    let self_type = ast.self_ty.as_mut();

    // go through items inside the block
    // 1. For every associated type, make it
    //    type SomeType = <other_type as Trait>::SomeType
    // 2. For every method, make sure it is of one of the following
    //     * f(&self, other: &other_type)
    //     * f(&mut self, other: &mut other_type)
    //     * f(self, other: other_type)
    //     * f(mut self, mut other: other_type)
    //    If there are lifetime decorations, they must be the same.
    //    replace other_type with self_type
    //    replace the body with:
    //    Trait::f(other, self)
    // 3. Leave everything else intact
    for item in ast
        .items
        .iter_mut()
        .filter(|item| matches!(item, ImplItem::Method(_) | ImplItem::Type(_)))
    {
        match item {
            ImplItem::Method(method) => {
                if let Some(variadic) = &method.sig.variadic {
                    // variadic method
                    return to_compile_error(
                        "method in a symmetric trait cannot be variadic".to_string(),
                        variadic.span(),
                    );
                }

                // verify the input arguments of the method

                if method.sig.inputs.len() != 2 {
                    // wrong number of arguments
                    return to_compile_error(
                        "expected 2 arguments".to_string(),
                        method.sig.inputs.span(),
                    );
                }

                let mut iter = method.sig.inputs.iter_mut();
                let self_arg = iter.next().unwrap();
                let other_arg = iter.next().unwrap();

                // self_arg must be one of the 4 form
                let self_arg = match self_arg {
                    FnArg::Receiver(receiver) => receiver,
                    _ => {
                        return to_compile_error(
                            "expected a receiver".to_string(),
                            self_arg.span(),
                        );
                    }
                };

                let other_arg = match other_arg {
                    FnArg::Typed(typed_arg) => typed_arg,
                    FnArg::Receiver(_) => unreachable!(),
                };

                let other_ident = if let Some((_, lifetime)) = &self_arg.reference {
                    // both should be reference with the same lifetime
                    match other_arg.ty.as_mut() {
                        Type::Reference(reference) => {
                            if self_arg.mutability != reference.mutability {
                                return to_compile_error(
                                    "mismatched mutability".to_string(),
                                    other_arg.span(),
                                );
                            }
                            if lifetime != &reference.lifetime {
                                return to_compile_error(
                                    "mismatched lifetime".to_string(),
                                    other_arg.span(),
                                );
                            }
                            // replace the underlying type for other_arg
                            reference.elem = Box::new(self_type.clone());

                            let pat_ident = PatIdent {
                                attrs: Vec::new(),
                                by_ref: None,
                                mutability: None,
                                ident: Ident::new("other", other_arg.span()),
                                subpat: None,
                            };
                            other_arg.pat = Box::new(Pat::Ident(pat_ident));
                            match other_arg.pat.as_ref() {
                                Pat::Ident(ident) => &ident.ident,
                                _ => unreachable!(),
                            }
                        }
                        _ => {
                            return to_compile_error(
                                "expected a reference".to_string(),
                                other_arg.span(),
                            );
                        }
                    }
                } else {
                    // replace other_arg by plain pattern
                    let pat_ident = PatIdent {
                        attrs: Vec::new(),
                        by_ref: None,
                        mutability: None,
                        ident: Ident::new("other", other_arg.span()),
                        subpat: None,
                    };
                    other_arg.pat = Box::new(Pat::Ident(pat_ident));
                    // replace the type of other_arg
                    other_arg.ty = Box::new(self_type.clone());
                    match other_arg.pat.as_ref() {
                        Pat::Ident(ident) => &ident.ident,
                        _ => unreachable!(),
                    }
                };

                // replace method body
                let method_name = &method.sig.ident;
                let new_block: Block = parse_quote! {
                    {
                        <#self_type as #original_trait>::#method_name(#other_ident, self)
                    }
                };
                method.block = new_block;
                method.attrs.append(
                    &mut Attribute::parse_outer
                        .parse_str("#[allow(unused_mut)]")
                        .unwrap(),
                );
                method
                    .attrs
                    .append(&mut Attribute::parse_outer.parse_str("#[inline]").unwrap());
            }
            ImplItem::Type(associated_type) => {
                // replace associated type
                let type_ident = &associated_type.ident;
                let delegated_type: Type = parse_quote! {
                    <#self_type as #original_trait>::#type_ident
                };
                associated_type.ty = delegated_type;
            }
            // keep as-is
            _ => (),
        }
    }

    // perform swapping of the types on impl
    mem::swap(other_type, self_type);

    quote! {
        #ast
    }
}

fn to_compile_error(message: String, span: Span) -> TokenStream {
    TokenStream::from_iter(vec![
        TokenTree::Ident(Ident::new("compile_error", span)),
        TokenTree::Punct({
            let mut punct = Punct::new('!', Spacing::Alone);
            punct.set_span(span);
            punct
        }),
        TokenTree::Group({
            let mut group = Group::new(Delimiter::Brace, {
                TokenStream::from_iter(vec![TokenTree::Literal({
                    let mut string = Literal::string(&message);
                    string.set_span(span);
                    string
                })])
            });
            group.set_span(span);
            group
        }),
    ])
}