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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
//! Utilities to allow for some specialization using stable Rust.
//!
//! This crate provides two mechanisms for specialization:
//! * Using the [`IsNot`] trait. This can be used when the data-type that you want to syllogism for
//!   is a concrete type.
//! * Using the [`Specialize`] trait.
//!
//! When using the `IsNot` trait, in order to syllogism for a data type `T1` and handle another
//! data type `T2` in a generic way, `T2` needs to implement `IsNot<T1>`.
//!
//! When using the `Specialize` trait, in order to syllogism for a data type `T1` and handle
//! another data type `T2` in a generic way, both `T1` and `T2` need to implement `Specialize<T1>`.
//!
//! You may need many impl blocks for implementing the `IsNot` and the `Specialize` trait.
//! In order to facilitate you to do so, you can use the [`define_compatibility`] macro.
//!
//! The syllogism-macro crate defines some procedural macros that help with these implementations,
//! also when not all compatible data types are defined in the same crate.
//!
//!
//! Specialization using the `IsNot` trait
//! --------------------------------------
//!
//! Using the `IsNot` trait is straightforward if you want to syllogism
//! for a concrete data type.
//!
//! ```
//! use syllogism::IsNot;
//!
//! trait GenericTrait<T> {
//!     // ...
//! }
//!
//! struct SpecialDataType { /* ... */ }
//!
//! struct GenericDataType1 { /* ... */ }
//! impl IsNot<SpecialDataType> for GenericDataType1 {}
//!
//! struct GenericDataType2 { /* ... */ }
//! impl IsNot<SpecialDataType> for GenericDataType2 {}
//!
//! struct MyStruct {
//!     // ...
//! }
//!
//! impl GenericTrait<SpecialDataType> for MyStruct {
//!     // The special implementation
//! }
//!  
//! // This can be used for the data types `GenericDataType1` and `GenericDataType2`.
//! impl<T> GenericTrait<T> for MyStruct
//! where T: IsNot<SpecialDataType> {
//!     // The generic implementation
//! }
//! ```
//!
//! You can also have specialization for more than one type:
//! ```
//! use syllogism::IsNot;
//! # trait GenericTrait<T> {}
//! # struct MyStruct {}
//! #
//! # struct SpecialDataType1 {}
//! # struct SpecialDataType2 {}
//!
//! // One special implementation:
//! impl GenericTrait<SpecialDataType1> for MyStruct {
//!     // ...
//! }
//!
//! // Another special implementation:
//! impl GenericTrait<SpecialDataType2> for MyStruct {
//!     // ...
//! }
//!
//! // The generic implementation.
//! impl<T> GenericTrait<T> for MyStruct
//! where T: IsNot<SpecialDataType1> + IsNot<SpecialDataType2>{
//!     // ...
//! }
//! ```
//!
//! Specialization using the `Specialize` trait
//! -------------------------------------------
//! If the data type for which you want to syllogism is a type parameter,
//! you cannot use the `IsNot` trait because the compiler cannot know if
//! a type (even not in a dependent crate) will implement `IsNot<Self>`.
//! Not implementing `IsNot<Self>` is just a convention,
//! it is not compiler-enforced and the compiler cannot see
//! this. To work around this, you can use the [`Specialize`] trait:
//!
//! ```
//! use syllogism::{Specialize, Distinction};
//!
//! trait GenericTrait<T> {
//!     fn some_method(&self, param: T);
//! }
//! struct MyStruct<T> {
//!     // ...
//! #    t: T
//! }
//!
//! struct SpecialDataType { /* ... */ }
//! impl Specialize<SpecialDataType> for SpecialDataType {
//!     fn specialize(self) -> Distinction<SpecialDataType, Self> {
//!          Distinction::Special(self)
//!     }
//! }
//!
//! struct GenericDataType1 { /* ... */ }
//! impl Specialize<SpecialDataType> for GenericDataType1 {
//!     fn specialize(self) -> Distinction<SpecialDataType, Self> {
//!          Distinction::Generic(self)
//!     }
//! }
//! struct GenericDataType2 { /* ... */ }
//! impl Specialize<SpecialDataType> for GenericDataType2 {
//!     // Similar to the implementation of Specialize for `GenericDataType1`.
//! #    fn specialize(self) -> Distinction<SpecialDataType, Self> {
//! #         Distinction::Generic(self)
//! #    }
//! }
//!
//! // Can be used for each `T` in `SpecialDataType`, `GenericDataType1` and `GenericDataType2`.
//! impl<T> GenericTrait<T> for MyStruct<T>
//! where T: Specialize<SpecialDataType> {
//!     fn some_method(&self, param: T) {
//!         match param.specialize() {
//!             Distinction::Special(special) => {
//!                 // The special implementation.
//!             },
//!             Distinction::Generic(generic) => {
//!                 // The generic implementation.
//!             }
//!         }
//!     }
//! }
//! ```
//!
//! Using the `Specialize` trait is limited to methods that take the parameter by value
//! (as oposed to by reference).
//!
//! Implementing `IsNot` and `Serialize` across crate boundaries
//! ------------------------------------------------------------
//! As discussed before, for any data types `T1` and `T2` that you want to syllogism for
//! or that are used in the general case, you may want to implement
//! * `impl IsNot<T2> for T1 {}` (1) and
//! * `impl IsNot<T1> for T2 {}` (2).
//!
//! Because of the orphan rules, (1) can only be implemented in the crate that defines `T1` and
//! (2) can only be implemented in the crate that defines `T2`.
//! In order to loosen the coupling and dependency between the crates, for each crate, a trait is
//! defined ("`NotInCrateX`") and a blanket impl combines the crates together:
//!
//! ```
//! // In some crate
//!
//! pub trait NotInCrate1 {}
//! pub trait NotInCrate2 {}
//! ```
//! These macros are then imported in `crate1` and `crate2` and used as follows:
//! ```
//! // In crate1
//! # trait NotInCrate1 {}
//! # trait NotInCrate2 {}
//! use syllogism::{IsNot};
//!
//! struct T1 {
//!     // ...
//! }
//!
//! impl<T> IsNot<T> for T1
//! where T: NotInCrate1
//! {}
//!
//! impl NotInCrate2 for T1 {}
//! ```
//! and
//! ```
//! // In crate2
//! # trait NotInCrate1 {}
//! # trait NotInCrate2 {}
//! use syllogism::{IsNot};
//!
//! struct T2 {
//!     // ...
//! }
//!
//! impl<T> IsNot<T> for T2
//! where T: NotInCrate2
//! {}
//!
//! impl NotInCrate1 for T2 {}
//! ```
//!
//! Now if there are many crates at play, you need more trait impls:
//! ```
//! // In crate1:
//! # trait NotInCrate1 {}
//! # trait NotInCrate2 {}
//! # trait NotInCrate3 {}
//! use syllogism::{IsNot};
//!
//! struct T1 {
//!     // ...
//! }
//!
//! impl<T> IsNot<T> for T1
//! where T: NotInCrate1
//! {}
//!
//! impl NotInCrate2 for T1 {}
//! impl NotInCrate3 for T1 {}
//! // ...
//! ```
//!
//! In order to help you with these impls, you can use the [`define_compatibility`] macro
//! to define the `NotInCrateX` traits and to automatically generate macros for implementing
//! `NotInCrate2`, `NotInCrate3`, ... .
//!
//! [`IsNot`]: ./trait.IsNot.html
//! [`Specialize`]: ./trait.Specialize.html
//! [`define_compatibility`]: ./macro.define_compatibility.html

/// A trait to inform the compiler that two data types are distinct.
///
/// This allows you to use specialization up to some extend.
/// See the [crate level documentation] for more info.
///
/// A data type should never implement `IsNot<Self>`.
///
/// Implementing `IsNot` correctly for each pair of data types at hand can be
/// error prone. E.g. if there are three data types at play, `T1`, `T2`, `T3`.
/// If you want to allow specialization for any of these data types, giving the other two the
/// "default" treatment, then you need six implementations of the `IsNot` trait:
/// ```
/// use syllogism::IsNot;
/// # struct T1 {}
/// # struct T2 {}
/// # struct T3 {}
///
/// impl IsNot<T2> for T1 {}
/// impl IsNot<T3> for T1 {}
/// impl IsNot<T1> for T2 {}
/// impl IsNot<T3> for T2 {}
/// impl IsNot<T1> for T3 {}
/// impl IsNot<T2> for T3 {}
/// ```
/// The `syllogism-macro` crate provides procedural macros to generate these `impl`s for you,
/// and also offers some techniques that allow extending the set of data types across crate
/// boundaries. We refer to the documentation of the `syllogism-macro` crate for more information.
///
/// [crate level documentation]: ./index.html
pub trait IsNot<T> {}

/// An enum that allows to distinguish between the special case and the generic case.
///
/// To be used together with the `Specialize` trait.
/// See the [documentation of the `Specialize` trait] for more information.
///
/// [documentation of the `Specialize` trait]: ./trait.Specialize.html
pub enum Distinction<S, G> {
    Special(S),
    Generic(G),
}

/// A trait allowing to distinguish between the special case and the generic case at run time.
///
/// See the [crate level documentation] for more info.
///
/// Below we describe various methods for implementing the `Specialize` trait.
/// The easiest way however is probably to use the `syllogism-macro` crate.
///
/// Implementing `Specialize` using the `IsNot` trait
/// -------------------------------------------------
/// One shortcut you can take if the data type has no type parameters is to use the `IsNot` trait,
/// assuming you already need to implement this.
/// ```
/// use syllogism::{IsNot, Specialize, Distinction};
///
/// struct T1 { /* ... */ }
/// struct T2 { /* ... */ }
/// struct T3 { /* ... */ }
///
/// impl IsNot<T2> for T1 {}
/// impl IsNot<T3> for T1 {}
/// impl IsNot<T1> for T2 {}
/// impl IsNot<T3> for T2 {}
/// impl IsNot<T1> for T3 {}
/// impl IsNot<T2> for T3 {}
///
/// impl<T> Specialize<T> for T1
/// where T: IsNot<T1>
/// {
///     fn specialize(self) -> Distinction<T, Self> {
///         Distinction::Generic(self)
///     }
/// }
///
/// impl Specialize<T1> for T1 {
///     fn specialize(self) -> Distinction<T1, Self> {
///         Distinction::Special(self)
///     }
/// }
///
/// // And similar for `T2` and `T3`.
/// ```
///
/// Implementing `Specialize` for types with a type parameter using the `Specialize` trait
/// --------------------------------------------------------------------------------------
/// When a type has a type parameter, in some circumstances,
/// you can not use the `IsNot` trait to implement
/// the `Specialize` trait: the following code will fail to compile
/// ```compile_fail
/// use syllogism::{IsNot, Specialize, Distinction};
///
/// struct T1<T> {
///     t: T
///     // ...
/// }
///
/// impl<T, U> IsNot<T1<T>> for T1<U> where T: IsNot<U> {}
///
/// impl<T, U> Specialize<T1<T>> for T1<U> where T: IsNot<U>{
///     fn specialize(self) -> Distinction<T, Self> {
///         Distinction::Generic(self)
///     }
/// }
/// impl<T> Specialize<T1<T>> for T1<T> {
///     fn specialize(self) -> Distinction<T1<T>, Self> {
///         Distinction::Special(self)
///     }
/// }
/// ```
/// The reason for this compile failure is that a type `Ts` _may_ implement `IsNot<Ts>` and
/// in that case, `T1<Ts>` implements `IsNot<T1<Ts>>` and the impl blocks overlap.
///
/// This can be solved by using the `Specialize` trait again:
/// ```
/// use syllogism::{IsNot, Specialize, Distinction};
///
/// struct T1<T> {
///     t: T,
///     other_field: u8
/// }
///
/// impl<T, U> IsNot<T1<T>> for T1<U>
/// where T: IsNot<U> {
/// }
///
/// impl<T, U> Specialize<T1<T>> for T1<U>
/// where U: Specialize<T>
/// {
///     fn specialize(self) -> Distinction<T1<T>, Self> {
///         let T1{
///             t,
///             other_field
///         } = self; // deconstructing `let`
///
///         match t.specialize() {
///             Distinction::Special(special) => {
///                 Distinction::Special(T1{t: special, other_field})
///             },
///             Distinction::Generic(generic) => {
///                 Distinction::Generic(T1{t: generic, other_field})
///             }
///         }
///     }
/// }
/// ```
/// Implementing `Specialize` using macros
/// --------------------------------------
/// Implementing `Specialize` correctly for each pair of data types at hand can be
/// error prone. E.g. if there are three data types at play, `T1`, `T2`, `T3`.
/// If you want to allow specialization for any of these data types, giving the other two the
/// "default" treatment, then you need nine implementations of the `Specialize` trait:
/// ```
/// use syllogism::{Specialize, Distinction};
///
/// struct T1 { /* ... */ }
/// struct T2 { /* ... */ }
/// struct T3 { /* ... */ }
///
/// impl Specialize<T1> for T1 {
///     fn specialize(self) -> Distinction<T1, Self> {
///         Distinction::Special(self)
///     }
/// }
///
/// impl Specialize<T2> for T1 {
///     fn specialize(self) -> Distinction<T2, Self> {
///         Distinction::Generic(self)
///     }
/// }
///
/// impl Specialize<T3> for T1 {
///     // similar
/// #    fn specialize(self) -> Distinction<T3, Self> {
/// #        Distinction::Generic(self)
/// #    }
/// }
///
/// impl Specialize<T1> for T2 {
///     // similar
/// #    fn specialize(self) -> Distinction<T1, Self> {
/// #        Distinction::Generic(self)
/// #    }
/// }
/// impl Specialize<T2> for T2 {
///     // similar
/// #    fn specialize(self) -> Distinction<T2, Self> {
/// #        Distinction::Special(self)
/// #    }
/// }
/// impl Specialize<T3> for T2 {
///     // similar
/// #    fn specialize(self) -> Distinction<T3, Self> {
/// #        Distinction::Generic(self)
/// #    }
/// }
///
/// impl Specialize<T1> for T3 {
///     // similar
/// #    fn specialize(self) -> Distinction<T1, Self> {
/// #        Distinction::Generic(self)
/// #    }
/// }
/// impl Specialize<T2> for T3 {
///     // similar
/// #    fn specialize(self) -> Distinction<T2, Self> {
/// #        Distinction::Generic(self)
/// #    }
/// }
/// impl Specialize<T3> for T3 {
///     // similar
/// #    fn specialize(self) -> Distinction<T3, Self> {
/// #        Distinction::Generic(self)
/// #    }
/// }
/// ```
///
/// The `syllogism-macro` crate provides procedural macros to generate these `impl`s for you,
/// and also offers some techniques that allow extending the set of data types across crate
/// boundaries. We refer to the documentation of that crate for more information.
///
/// [crate level documentation]: ./index.html
pub trait Specialize<T>: Sized {
    fn specialize(self) -> Distinction<T, Self>;
}

/// A macro to define traits and other macros that help to implement `IsNot` and `Specialize`
/// across crates.
///
/// The macro expects the dollar symbol (for technical reasons),
/// followed by a comma-separated list of (trait, macro) pairs.
/// The macro expands to definitions of these traits and macros.
/// Each trait and macro may be preceded by a meta attribute (e.g. a doc comment in the form
/// of #[doc="..."]).
///
/// # Note
/// The trailing comma after the last pair is mandatory.
///
/// # Notes on meta attributes
/// Meta attributes are only inserted at the declaration of the traits and the macros, so
/// `#[cfg(...)]` attributes do not work.
/// 
/// Meta attributes may be doc comments starting with `///`, as illustrated in the example below.
///
///  
/// # Example
/// ```
/// # #[macro_use] extern crate syllogism;
/// define_compatibility!(
///     $
///     (
///         /// Lorem ipsum
///         NotInCrate1, 
///
///         #[doc(hidden)]
///         macro_for_crate1
///     ),
///     (NotInCrate2, macro_for_crate2),
///     (NotInCrate3, macro_for_crate3),
/// );
/// ```
/// This expands to the following:
/// ```
/// /// Lorem ipsum
/// trait NotInCrate1 {}
/// trait NotInCrate2 {}
/// trait NotInCrate3 {}
///
/// #[doc(hidden)]
/// macro_rules! macro_for_crate1 {
///     // See below for more information.
/// #    () => {}
/// }
/// macro_rules! macro_for_crate2 {
///     // See below for more information.
/// #    () => {}
/// }
/// macro_rules! macro_for_crate3 {
///     // See below for more information.
/// #    () => {}
/// }
/// ```
/// The generated macros can in turn be used in the following way:
/// ```
/// # #[macro_use] extern crate syllogism;
/// # define_compatibility!(
/// #    $
/// #    (NotInCrate1, macro_for_crate1),
/// #    (NotInCrate2, macro_for_crate2),
/// #    (NotInCrate3, macro_for_crate3),
/// # );
/// struct MyStruct {
///     // ...
/// }
///
/// struct MyGenericStruct<T> {
/// #   t: T
///     // ...
/// }
///
/// macro_for_crate1!(impl trait for MyStruct {});
/// macro_for_crate1!(impl<T> trait for MyGenericStruct<T> {});
/// ```
/// This expands to the following:
/// ```
/// # struct MyStruct { }
/// # struct MyGenericStruct<T> {t: T}
/// # trait NotInCrate2 {}
/// # trait NotInCrate3 {}
/// impl NotInCrate2 for MyStruct {}
/// impl NotInCrate3 for MyStruct {}
///
/// impl<T> NotInCrate2 for MyGenericStruct<T> {}
/// impl<T> NotInCrate3 for MyGenericStruct<T> {}
/// ```
// This macro iterates over a number of (trait, macro) pairs.
// The (trait, macro) pairs are split in the following sets:
//
// head     (a number of (trait, macro) pairs)
// current  (one (trait, macro) pair)
// tail     (a number of (trait, macro) pairs)
//
// Initially, head is an empty list.
// The iteration works by chewing off one (trait, macro) pair from the tail.
#[macro_export]
macro_rules! define_compatibility {
    (
        $dollar:tt
        (
            $(#[$trait_head_meta:meta])* $trait_head:ident, 
            $(#[$macro_head_meta:meta])* $macro_head:ident
        ),
        $(
            (
                $(#[$trait_tail_meta:meta])* $trait_tail:ident, 
                $(#[$macro_tail_meta:meta])* $macro_tail:ident
            ),
        )*
    ) => {
        $crate::define_compatibility!(
            @inner
            $dollar
            () // empty head.
            @($(#[$trait_head_meta])* $trait_head, $(#[$macro_head_meta])* $macro_head)
            @($(($(#[$trait_tail_meta])* $trait_tail, $(#[$macro_tail_meta])* $macro_tail),)*)
        );
    };
    // Below: the last step in the iteration, when there is
    // no next (trait, macro) pair anymore
    (
        @inner
        $dollar:tt
        (
            $(($(#[$trait_head_meta:meta])* $trait_head:ident, 
            $(#[$macro_head_meta:meta])* $macro_head:ident),)*
        )
        @(
            $(#[$trait_current_meta:meta])* $trait_current:ident, 
            $(#[$macro_current_meta:meta])* $macro_current:ident
        )
        @()
    ) => {
        $(#[$trait_current_meta])*
        pub trait $trait_current {}
        
        $(#[$macro_current_meta])*
        #[macro_export]
        macro_rules! $macro_current {
            (
                $dollar (
                    impl$dollar(
                        <$dollar($dollar ph:tt)? $dollar(,$dollar pt:tt)*>
                    )?
                    trait for $dollar typ:ty {}
                )*
            ) => {
                $(
                    $dollar(
                        impl$dollar(
                            <$dollar($dollar ph)? $dollar(,$dollar pt)*>
                        )?
                        $trait_head for $dollar typ {}
                    )*
                )*
            }
        }
    };
    // The main step of the iteration.
    (
        @inner
        $dollar:tt
        (
            $(
                (
                    $(#[$trait_head_meta:meta])* $trait_head:ident, 
                    $(#[$macro_head_meta:meta])* $macro_head:ident
                ),
            )*
        )
        @(
            $(#[$trait_current_meta:meta])* $trait_current:ident, 
            $(#[$macro_current_meta:meta])* $macro_current:ident
        )
        @(
            (   // First pair of the tail.
                $(#[$trait_next_meta:meta])* $trait_next:ident, 
                $(#[$macro_next_meta:meta])* $macro_next:ident
            ),
            $(
                (
                    $(#[$trait_tail_meta:meta])* $trait_tail:ident, 
                    $(#[$macro_tail_meta:meta])* $macro_tail:ident
                ),
            )*
        )
    ) => {
        $(#[$trait_current_meta])*
        pub trait $trait_current {}
        
        $(#[$macro_current_meta])*
        #[macro_export]
        macro_rules! $macro_current {
            (
                $dollar (
                    impl$dollar(
                        <$dollar($dollar ph:tt)? $dollar (,$dollar pt:tt)*>
                    )?
                trait for $dollar typ:ty {}
                )
            *) => {
                $(
                    $dollar(
                        impl$dollar(
                            <$dollar($dollar ph)? $dollar(,$dollar pt)*>
                        )?
                    $trait_head for $dollar typ {}
                    )*
                )*

                $(
                    $dollar(
                        impl$dollar(
                            <$dollar($dollar ph)? $dollar(,$dollar pt)*>
                        )?
                    $trait_tail for $dollar typ {}
                    )*
                )*

                $dollar(
                    impl$dollar(
                        <$dollar($dollar ph)? $dollar(,$dollar pt)*>
                    )?
                    $trait_next for $dollar typ {}
                )*
            }
        }
        $crate::define_compatibility!(
            @inner
            $dollar
            (   // Add the current to the head.
                $(
                    (
                        $(#[$trait_head_meta])* $trait_head, 
                        $(#[$macro_head_meta])* $macro_head
                    ),
                )* 
                (
                    $(#[$trait_current_meta])* $trait_current, 
                    $(#[$macro_current_meta])* $macro_current
                ),
            )
            @(  // This is the new "current"
                $(#[$trait_next_meta])* $trait_next, 
                $(#[$macro_next_meta])* $macro_next
            )
            @(
                $(
                    (
                        $(#[$trait_tail_meta])* $trait_tail, 
                        $(#[$macro_tail_meta])* $macro_tail
                    ),
                )*
            )
        );
    }
}

#[cfg(test)]
mod tests {
    #[macro_use]
    mod def {
        define_compatibility!($ 
            (#[doc(hidden)] NotInCrate1, #[doc="abc"] #[doc="def"] macro_for_crate1), 
            (#[doc="ghi"] NotInCrate2, #[doc="jkl"] macro_for_crate2), 
            (#[doc="mno"] #[doc="pqr"] NotInCrate3, #[doc="stu"] #[doc="vwx"] macro_for_crate3), );
    }
    use def::{NotInCrate1, NotInCrate2, NotInCrate3};
    struct S1 {}
    struct S1A<A> {
        _a: A,
    }
    struct S2 {}
    struct S3 {}

    #[allow(dead_code)]
    struct S4<A, B> {
        _a: A,
        _b: B,
    }

    #[allow(dead_code)]
    struct S5<'a> {
        _x: &'a u8,
    }

    macro_for_crate1!(
        impl trait for S1 {}
        impl<A> trait for S1A<A> {}
        impl<A, B> trait for S4<A, B> {}
        impl<'a> trait for S5<'a> {}
    );
    macro_for_crate2!(impl trait for S2 {});
    macro_for_crate3!(impl trait for S3 {});

    fn not_in_crate1<T: NotInCrate1>() {}
    fn not_in_crate2<T: NotInCrate2>() {}
    fn not_in_crate3<T: NotInCrate3>() {}

    #[test]
    fn compatibility_traits_defined() {
        not_in_crate1::<S2>();
        not_in_crate1::<S3>();

        not_in_crate2::<S1>();
        not_in_crate2::<S1A<u8>>();
        not_in_crate2::<S3>();

        not_in_crate3::<S1>();
        not_in_crate3::<S1A<u8>>();
        not_in_crate3::<S2>();
    }
}