tisel 0.1.1

Effective type-based pseudodynamic dispatch to impls, enums and typeid
Documentation
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
//! [cisness]: `cisness`
//! [cisness-livewitness]: `cisness::LiveWitness`
//! [any]: `core::any::Any`
//! [typematch-macro]: `typematch`
#![doc = include_str!("../README.md")]
#![cfg_attr(not(test), no_std)]

#[doc(hidden)]
pub mod _reexports;

#[doc(hidden)]
pub mod _macro;

#[doc(hidden)]
pub mod _deduce_witness;

/// Switch over `k` types (or type-id-expressions), and get witness values. Also works for single
/// ones.
///
/// A `type-id-expression` is something this macro defines, and it looks like one of the following (in parsing priority order):
/// * `anyref (<name> = <expression producing &dyn Any>)` or `anyref name`
///    match on the type stored inside a [`core::any::Any`] shared reference. In this
///    case, the type witness you'll get is:
///    * (with type constraint) - the shared reference to the type you're matching it on, from
///      inside the `&dyn Any`
///    * (without type constraint) - the `&dyn Any`
/// * `anymut (<name> = <expression producing &mut dyn Any>)` or `anymut name` -
///    similar to `anyref`, but everything is with exclusive references instead of shared
///    references
/// * `val <name> [:<type>]?` or `val (<name> [:<type>]? = <expression producing value>)`:
///    Match on the given value, by value (with optional type-ascription, which helps make things
///    less ambiguous). In this case the witness you'll get is:
///    * (with type constraint) - the value itself, as the checked type, and by-value.
///    * (without type constraint) - the value, but without any automatic type-check-validating
///      conversions
/// * `out <type>` - this is like `<type>`, but it flips the direction of the witness you get. This
///    is useful for the common case of wanting to match on a generic output type, and avoids
///    littering your code with [`cisness::LiveWitness::inverse`]. The witness you get for this
///    typeid-gen-expr is:
///    * (with type constraint) - a [`cisness::LiveWitness`] claiming equality between the type
///      constraint and the type being matched on. This allows you to easily convert any values of
///      the constraint type into values of the matched type (if you want to do the other way, use
///      `<type>` or [`cisness::LiveWitness::inverse`]).
///    * (without type constraint) - the [`core::any::TypeId`] of the matched type.
/// * `type <type>` - exact same as `<type>`, but this explicitly forces it to be treated like that,
///    in case you have a type that has a name collision with one of the prefixes.
/// * `<type>` - match on the given type itself, without any need for a specific or single value.
///   In this case, the witness you'll get is as follows:
///   * (with type constraint) - a [`cisness::LiveWitness`] claiming equality between the type
///     being matched on and the type constraint. This lets you do things like convert values
///     specifically of the type constraint into values of the type being matched on (and vice
///     versa), for type validation, because the [`cisness::LiveWitness`] declares that it will
///     never be used on a codepath where it's two type parameters are not actually the same.
///   * (without type constraint) - the [`core::any::TypeId`] of the matched type.
///
/// Naturally, this requires the types being compared to be [`core::any::Any`] - the
/// [`cisness::LiveWitness`] created, right now, will then let you work with references or mutable
/// references to the compared types as well as the owned version of the type.
/// [Hopefully this capability will be expanded greatly in future][future-ideas]
///
/// The syntax of each typematcher pattern is slightly distinct from normal patterns. It looks
/// like: `[@_]? [type Alias = [@_]?]? [<type constraints>]|*? [as witness_name]?` - note that the
/// "capture like" thing is on the right instead of the left. This helps significantly to avoid
/// parsing ambiguities. We also can't use `@` because it can't come after types - instead we use
/// it to indicate an unconstrained pattern without it getting confused for a type
///
/// You can use type aliases in unconstrained patterns but only if you're matching on a type rather
/// than using anyrefs.
///
/// An important note is that two commas like `,,` may well constitute an unconstrained empty
/// pattern. This macro cannot warn you because it can't capture each `,`-separated per-index
/// typematch pattern as a string of tokens and check for emptiness, and there's no way to extract
/// the `_` tokens as more general variables as they cause follow-set restrictions on `pat` and
/// `pat_param`.
///
/// This macro also explicitly forces you to provide a catch-all matcher. It has to
/// provide a manual extra one internally - because of the inability to conditionally include match
/// guards - so we force the user to handle it themselves so that this doesn't lead to issues with
/// not covering all cases.
///
/// # Basic Example - Matching on a Single Type
/// ```rust
/// use tisel::typematch;
/// use core::any::Any;
///
/// fn switcher<T: Any>(v: T) -> &'static str {
///     typematch!(T {
///         // note the use of a *witness* to convert the generic parameter type into the
///         // type it's been proven equal to by the match statement. The inverse can be done too,
///         // via .inverse() (which flips the witness), or via making the matched type use `out`
///         // as a prefix (which will create a reversed witness by default).
///         &'static str as extract => extract.owned(v),
///         u8 | u16 | u32 | u64 | u128 => "unsigned-int",
///         i8 | i16 | i32 | i64 | i128 => "signed-int",
///         // Note that we use `@_` instead of `_`
///         // This is due to limitations of macro_rules!. But it means the same as `_`
///         @_ => "unrecognised"
///     })
/// }
///
/// assert_eq!(switcher("hello"), "hello");
/// assert_eq!(switcher(4u32), "unsigned-int");
/// assert_eq!(switcher(-3), "signed-int");
/// assert_eq!(switcher(vec![89]), "unrecognised");
/// ```
///
/// # Basic Example - Matching on a Single Generic Type & Associated Types
/// This crate lets you build a complex, multi-component `match` statement over types to compare,
/// and then provides you with [`cisness::LiveWitness`] values to let you "assume" the types that
/// match do in fact match, and convert them for type signature validation.
///
/// To start with, we present a simple example on how to match a value with just one type and
/// produce another. Clearly, there are better ways to do this example, but it illustrates the
/// basic functionality.
///
/// This example also illustrates the `out` functionality. This lets you match on a type, but
/// produce a live witness that is inverted. While this is a trivial operation to do via a function
/// on the live witness if necessary, it's very common to want to just use a specific type as
/// output, and avoiding littering your codebase with `.inverse()`.
/// ```rust
/// use tisel::typematch;
/// use core::{any::Any, fmt::Display};
///
/// trait TypeDescriptor {
///     type Descriptor: Display + Any;
///
///     fn get_descriptor() -> Self::Descriptor;
/// }
///
/// impl TypeDescriptor for u32 {
///     type Descriptor = &'static str;
///     fn get_descriptor() -> Self::Descriptor {
///         "integer"
///     }
/// }
///
/// impl TypeDescriptor for u64 {
///     type Descriptor = String;
///     fn get_descriptor() -> Self::Descriptor {
///         "big integer".to_owned()
///     }
/// }
///
/// impl TypeDescriptor for () {
///     type Descriptor = u32;
///     fn get_descriptor() -> Self::Descriptor {
///         0
///     }
/// }
///
/// /// Select specific implementations - other implementations not in this function return
/// /// [`None`]. Prints a special notification for `()`, and emits `1` instead of `0` for that
/// /// case.
/// fn select_implementation<T: TypeDescriptor + Any>() -> Option<T::Descriptor> {
///     typematch!((T, out T::Descriptor) {
///        // The pattern lets you give names to the type witnesses, as
///        // well as create "local type aliases"
///        // This illustrates using types extracted from the trait, as well as directly
///        // writing the type (which could include, for instance, a generic type to the
///        // function).
///        // While it would be possible to make rust deduce these types from the code block
///        // that way lies unpredictable runtime panics for type errors, which is really
///        // a bad idea. You can make them `_`, to state that you don't care about the type,
///        // but that means you will get a `typeid` as a witness.
///        | (type IT = u64, <u64 as TypeDescriptor>::Descriptor as out_witness)
///            | (type IT = u32, &'static str as out_witness) => {
///            // Note how we take the inner type and get it's specific output, then
///            // use the provided witness (which assures that `IT` is `T` when this
///            // code path is run) to convert the value to the output. This typechecks
///            // fine, even when the generic type is not `u64` or `u32`.
///            let final_output = Some(out_witness.owned(IT::get_descriptor()));
///            final_output
///        },
///        (() as in_witness, <() as TypeDescriptor>::Descriptor as out_witness) => {
///            println!("Someone requested the descriptor for (), returning `1` instead");
///            Some(out_witness.owned(1))
///        },
///        (@_, @_) => None
///     })
/// }
///
/// // Implementation not known by the select_implementation function
/// impl TypeDescriptor for String {
///     type Descriptor = &'static str;
///     
///     fn get_descriptor() -> Self::Descriptor {
///         "owned string"
///     }
/// }
///
/// // Recognised implementation
/// assert_eq!(select_implementation::<u32>(), Some("integer"));
/// // Recognised implementation with custom override
/// assert_eq!(select_implementation::<()>(), Some(1));
/// // Unrecognised implementation
/// assert_eq!(select_implementation::<String>(), None);
/// ```
///
/// # Basic Example - Common Associated Data with Fallback
/// This example illustrates the powerful capability for composing [`Any`][core-any], with bare
/// type matching, and similar, to create registerable fallback handlers while also storing ones
/// that you know will be available at compile time, statically.
///
/// ```
/// # use tisel::typematch;
/// # use std::{collections::HashMap, any::{Any, TypeId}};
///
/// /// basic error type
/// ##[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
/// pub struct DidFail;
///
/// /// Trait for some message handleable by your handler.
/// pub trait Message {
///     type Response;
///
///     /// Handle the message
///     fn handle_me(&self) -> Result<Self::Response, DidFail>;
/// }
///
/// ##[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// pub enum ZeroStatus { Yes, No }
///
/// // Implement the message trait for ints, but artificially induce fallibility by making it
/// // not work when the value is 1 or 3
/// macro_rules! ints {
///     ($($int:ty)*) => {
///         $(impl Message for $int {
///             type Response = ZeroStatus;
///
///             fn handle_me(&self) -> Result<Self::Response, DidFail> {
///                 match self {
///                     1 | 3 => Err(DidFail),
///                     0 => Ok(ZeroStatus::Yes),
///                     _ => Ok(ZeroStatus::No)
///                 }
///             }
///         })*
///     }
/// }
///
/// ints!{u8 u16 u32 u64 i8 i16 i32 i64};
///
/// impl Message for String {
///    type Response = String;   
///    fn handle_me(&self) -> Result<Self::Response, DidFail> {
///        Ok(self.trim().to_owned())
///    }
/// }
///
/// /// Basically an example of things we can store
/// ##[derive(Debug, Clone)]
/// pub struct Fallbacks<T> {
///     pub primary_next_message: T,
///     pub fallback_messages: Vec<T>
/// }
///
/// impl <T> Fallbacks<T> {
///     pub fn iter(&self) -> impl Iterator<Item = &'_ T> {
///         core::iter::once(&self.primary_next_message)
///             .chain(self.fallback_messages.iter())
///     }
/// }
///
/// impl<T> From<T> for Fallbacks<T> {
///     fn from(v: T) -> Self {
///         Self {
///             primary_next_message: v,
///             fallback_messages: vec![]
///         }
///     }
/// }
///
/// /// Message fallback registry, with inline stored values and fallbacks, plus the ability to
/// /// register new message types and fallbacks. This illustrates how to do fallbacks and similar
/// /// such things as well
/// pub struct MyRegistry {
///     pub common_u8: Fallbacks<u8>,
///     pub common_u16: Fallbacks<u16>,
///     pub common_u32: Fallbacks<u32>,
///     pub other_registered_fallbacks: HashMap<TypeId, Box<dyn Any>>,
/// }
///
/// impl MyRegistry {
///     fn send_message_inner<T: Message>(
///         message: Option<&T>,
///         fallbacks: &Fallbacks<T>
///     ) -> Result<T::Response, DidFail> {
///         let try_order = message.into_iter().chain(fallbacks.iter());
///         let mut tried = try_order.map(Message::handle_me);
///         let mut curr_result = tried.next().unwrap();
///         loop {
///             match curr_result {
///                 Ok(v) => break Ok(v),
///                 Err(e) => match tried.next() {
///                     Some(new_res) => { curr_result = new_res; },
///                     None => break Err(e)
///                 }
///             }
///         }
///     }
///
///     /// "send" one of the example "messages". If you provide one, then it uses the value you
///     /// provided and falls back. If you do not provide one, then it uses the primary fallback
///     /// immediately.
///     ///
///     /// This also automatically merges signed and unsigned small ints (u8/i8, u16/i16, and
///     /// u32/i32), disallowing negative values.
///     pub fn send_message<T: Message<Response: Any> + Any>(
///         &self,
///         custom_message: Option<&T>
///     ) -> Option<Result<T::Response, DidFail>> {
///         typematch!((T, out T::Response) {
///             (u8 | i8 as input_witness, ZeroStatus as zw) => {
///                 let fallback = &self.common_u8;
///                 let message: Option<u8> = custom_message
///                     .map(|v| input_witness.reference(v))
///                     .cloned()
///                     .map(TryInto::try_into)
///                     .map(|v| v.expect("negative i8 not allowed!"));
///                 Some(Self::send_message_inner(
///                     message.as_ref(),
///                     &self.common_u8
///                 ).map(|r| zw.owned(r)))
///             },
///             (u16 | i16 as input_witness, ZeroStatus as zw) => {
///                 // similar                   
/// #               let fallback = &self.common_u16;
/// #               let message: Option<u16> = custom_message.map(|v| input_witness.reference(v)).cloned().map(TryInto::try_into).map(|v| v.expect("negative i16 not allowed!"));
/// #               Some(Self::send_message_inner(
/// #                   message.as_ref(),
/// #                   &self.common_u16
/// #               ).map(|r| zw.owned(r)))
///             },
///             (u32 | i32 as input_witness, ZeroStatus as zw) => {
///                 // similar                   
/// #               let fallback = &self.common_u32;
/// #               let message: Option<u32> = custom_message.map(|v| input_witness.reference(v)).cloned().map(TryInto::try_into).map(|v| v.expect("negative i32 not allowed!"));
/// #               Some(Self::send_message_inner(
/// #                   message.as_ref(),
/// #                   &self.common_u32
/// #               ).map(|r| zw.owned(r)))
///             },
///             // Using type aliases without explicit constraints is possible, but only when
///             // you're matching directly against a non-generic type. We can't use one here,
///             // because we're matching against a type derived from a generic parameter, and
///             // Rust will not let you create type aliases in sub-blocks that reference
///             // generic parameters (you can just use the generic parameter directly,
///             // though).
///             //
///             // We can also now use this to fall-back to retrieving from the map. Not only
///             // this, but we can use the type alias to then easily extract types directly
///             // from the map.
///             (/*type OtherMessage = */@_ as message_typeid, @_) => {
///                 let other_message_fallback =
///                     self.other_registered_fallbacks.get(&message_typeid)?;
///                 typematch!(
///                     // Here's an example of using an anyref. These can be used in full
///                     // combination with matching on types or on anymut.
///                     //
///                     // Important to note here is that, for Box, we need to make sure to be
///                     // getting an &dyn Any, not Box<dyn Any>, because the latter itself
///                     // implements Any
///                     (anyref (fallbacks = other_message_fallback.as_ref())) {
///                         (Fallbacks<T> as fallbacks) => {
///                             Some(Self::send_message_inner(custom_message, fallbacks))
///                         },
///                         (@_) => unreachable!(
///                             "wrong type for registered fallbacks"
///                         )
///                     }
///                 )
///             }
///         })
///     }
/// }
///
/// let mut my_registry = MyRegistry {
///     // This one will fall back to a working `2`
///     common_u8: Fallbacks { primary_next_message: 1,  fallback_messages: vec![2] },
///     // This one will simply fail unless another message is asked to be sent
///     common_u16: Fallbacks { primary_next_message: 3, fallback_messages: vec![] },
///     // This one will succeed :)
///     common_u32: Fallbacks { primary_next_message: 0, fallback_messages: vec![] },
///     other_registered_fallbacks: HashMap::new()
/// };
///
/// assert_eq!(my_registry.send_message(Some(&4u32)), Some(Ok(ZeroStatus::No)));
/// // this is a failing one so should fall back to zero because it's u32
/// assert_eq!(my_registry.send_message(Some(&1u32)), Some(Ok(ZeroStatus::Yes)));
/// // this illustrates the way we forced the signed ones to use the unsigned impls
/// assert_eq!(my_registry.send_message(Some(&5i16)), Some(Ok(ZeroStatus::No)));
/// // Illustrates the non-registered fallback
/// assert_eq!(my_registry.send_message::<String>(None), None);
/// // Registering it. This would in reality be abstracted behind some sort of method
/// my_registry.other_registered_fallbacks.insert(
///     TypeId::of::<String>(),
///     Box::new(Fallbacks::<String> {
///         primary_next_message: " hi people ".to_owned(),
///         fallback_messages: vec![]
///     })
/// );
/// // Now it can pull in the impl
/// assert_eq!(
///     my_registry.send_message::<String>(None).unwrap(),
///     Ok("hi people".to_owned())
/// );
/// assert_eq!(
///     my_registry.send_message(Some(&"ferris is cool  ".to_owned())).unwrap(),
///     Ok("ferris is cool".to_owned())
/// );
/// ```
///
///
/// [future-ideas]: Right now, [`cisness::LiveWitness`] structures have relatively low power,
/// because the underlying crate (`cismute`) has relatively few implementations for it's `Cismutable`
/// trait. However, in future, the author of this crate would like to cooperate with the author of the `cismute` crate to
/// create much more powerful `Cismutable` impls that allow cismutability between complex types
/// parameterised on basic underlying cismutable types.
///
/// [core-any]: `core::any::Any`
#[macro_export]
macro_rules! typematch {
    // This macro works recursively down each layer of patterns, aliases, etc.
    // to build up a massive list of match arms. This is important to do (as opposed to
    // recursive match statements) because it preserves the expected behaviour of match statement
    // order.
    //
    // This is specially important when the user tells this macro to ignore types in certain parts,
    // as the first match region in a recursive set of statements would "eat" all types, even if it
    // failed to match on further requirements. This does not match how actual match statements
    // function.
    //
    // We cannot use TypeOf directly in the pattern because of rust rules - instead, we need to
    // generate an array of relevant typeof values and use `if v ==` to emulate it. This has
    // important caveats in the case of exhaustiveness - we need to implement a way for a user to
    //
    // Something important for this is that we have the notion of "modes" to allow future
    // extensibility - the typeid generators may be simple typeid matching mode, but we allow the
    // option for e.g. `Any` mode to match on and automatically downcast.
    (($($typeid_gen_defs:tt)*) {
        $(
            $(|)? $(($($typeid_tuple_pattern:tt)*))|* => $output_expr:expr
        ),*
        $(,)?
    }) => {
        // Actual macro implementation.
        $crate::__typematch_parse_typeid_generators!{{
            unparsed_typeid_gens: [$($typeid_gen_defs)*],
            parsed_typeid_gens: [],
            // this automatically splits out |-patterns as well
            //
            // the unparsed specs are parsed layer-by-layer. Each arm is encoded in the form
            // [single branch components in []-bundle (syntactically extracted but not parsed);
            // { remaining arm data}], which then may branch further (one array to multiple).
            partially_parsed_match_arm_specs: [$($({
                unparsed_typeid_patterns: [$($typeid_tuple_pattern)*],
                output_expr: {$output_expr}
            })* /*each |-pattern*/ )* /*each arm*/]
        }}
    };
    // Simple version - anyref and anymut singles
    (anyref $anyref_id:ident $block:tt) => {
        $crate::__typematch_single_mode_dispatch!{{
            single_typeid_gen: [anyref $anyref_id],
            match_block: $block
        }}
    };
    (anyref ($anyref_id:ident = $anyref_expr:expr) $block:tt) => {
        $crate::__typematch_single_mode_dispatch!{{
            single_typeid_gen: [anyref ($anyref_id = $anyref_expr)],
            match_block: $block
        }}
    };
    (anymut $anymut_id:ident $block:tt) => {
        $crate::__typematch_single_mode_dispatch!{{
            single_typeid_gen: [anymut $anymut_id],
            match_block: $block
        }}
    };
    (anymut ($anymut_id:ident = $anymut_expr:expr) $block:tt) => {
        $crate::__typematch_single_mode_dispatch!{{
            single_typeid_gen: [anymut ($anymut_id = $anymut_expr)],
            match_block: $block
        }}
    };
    // value matchers
    //
    // squigglies are needed for follow-set rules on types
    {val $val_id:ident $(: $val_ty:ty)? {$($block:tt)*}} => {
        $crate::__typematch_single_mode_dispatch!{{
            single_typeid_gen: [val $val_id $(: $val_ty)?],
            match_block: {$($block)*}
        }}
    };
    {val ($val_id:ident $(: $val_ty:ty)? = $val_expr:expr) {$($block:tt)*}} => {
        $crate::__typematch_single_mode_dispatch!{{
            single_typeid_gen: [val ($val_id $(: $val_ty)? = $val_expr)],
            match_block: {$($block)*}
        }}
    };
    (out $type:ty { $($block:tt)* }) => {
        $crate::__typematch_single_mode_dispatch!{{
            single_typeid_gen: [out $type],
            match_block: {$($block)*}
        }}
    };
    // Simple single type matcher
    // squigglies are needed for follow-set rules on types
    (type $type:ty { $($block:tt)* }) => {
        $crate::__typematch_single_mode_dispatch!{{
            single_typeid_gen: [type $type],
            match_block: {$($block)*}
        }}
    };
    // Simple single type matcher
    // squigglies are needed for follow-set rules on types
    ($type:ty { $($block:tt)* }) => {
        $crate::__typematch_single_mode_dispatch!{{
            single_typeid_gen: [$type],
            match_block: {$($block)*}
        }}
    };
}

#[cfg(test)]
mod test_typematch {
    use crate::typematch;
    use core::any::Any;
    use std::collections::HashMap;

    #[test]
    fn basic_type_functionality() {
        fn switch_basic<T: Any>() -> &'static str {
            typematch!((T) {
                (String) => "string",
                (u32 | u64) => "bigger-integer",
                (u32) => "BAD",
                (@_) => "unrecognised"
            })
        }

        assert_eq!(switch_basic::<String>(), "string");
        assert_eq!(switch_basic::<u32>(), "bigger-integer");
        assert_eq!(switch_basic::<u64>(), "bigger-integer");
        assert_eq!(switch_basic::<i16>(), "unrecognised");
    }

    #[test]
    fn basic_anyref_functionality() {
        fn switch_get(v: &dyn Any) -> String {
            typematch!(anyref v {
                u32|u64 as data => format!("yay i'm {data}"),
                &'static str | String => "ooh fancy string. shame i won't display it".to_owned(),
                u32 => "NOT ALLOWED".to_string(),
                @_ => "unrecognised".to_string()
            })
        }

        let fancy_string = "my god it's a static string!!";
        let fancy_string_2 = "Get OWNED now :p".to_owned();
        assert_eq!(
            switch_get(&fancy_string),
            "ooh fancy string. shame i won't display it".to_owned()
        );
        assert_eq!(
            switch_get(&fancy_string_2),
            "ooh fancy string. shame i won't display it".to_owned()
        );

        let integer_data: u32 = 30;
        assert_eq!(switch_get(&integer_data), format!("yay i'm {integer_data}"));
        let integer_data_2: u64 = 490;
        assert_eq!(
            switch_get(&integer_data_2),
            format!("yay i'm {integer_data_2}")
        );

        let vectory = vec![4, 1, 93930, 229];
        assert_eq!(switch_get(&vectory), "unrecognised".to_owned());
    }

    #[test]
    fn basic_anymut_functionality() {
        fn switch_set(v: &mut dyn Any) {
            typematch!(anymut v {
                // u32 special ^.^
                u32 as data => { *data = 40; },
                u32 | u64 as data => { *data = 10; },
                &'static str as data => { *data = "yay"; },
                @_ => {}
            });
        }

        let mut vu32 = 0u32;
        let mut vu64 = 0u64;
        let mut sstr = "";
        let mut unknown_str = "very special string".to_owned();
        let data: [&mut dyn Any; 4] = [&mut vu32, &mut vu64, &mut sstr, &mut unknown_str];
        for r in data.into_iter() {
            switch_set(r);
        }
        assert_eq!(vu32, 40);
        assert_eq!(vu64, 10);
        assert_eq!(sstr, "yay");
        assert_eq!(unknown_str, "very special string".to_owned());
    }

    #[test]
    fn basic_val_functionality() {
        fn switch_val<T: Any>(v: T) -> String {
            typematch!(val v {
                u32 as _data => "u32 not allowed".to_owned(),
                u32 | u64 as data => format!("got integer: {data}"),
                &'static str | String as data => format!("got string: {data}"),
                @_ => "unrecognised".to_owned()
            })
        }

        let vu32 = 23u32;
        let vu64 = 438u64;
        let sstring = "hihihihi";
        let unknown_vec = Vec::<u8>::from([9, 19, 47]);
        let outputs = [
            switch_val(vu32),
            switch_val(vu64),
            switch_val(sstring),
            switch_val(unknown_vec),
        ];
        assert_eq!(
            outputs,
            [
                "u32 not allowed",
                "got integer: 438",
                "got string: hihihihi",
                "unrecognised"
            ]
            .map(ToOwned::to_owned)
        )
    }

    #[test]
    fn basic_out_functionality() {
        fn switch_out<Q: Any>() -> Q {
            // this is mostly just to ensure syntax stuff works nice
            typematch!(out Q {
                u64 | i64 as ow => ow.owned(83u32.into()),
                u32 as ow => ow.owned(20u32),
                u16 as ow => ow.owned(16u16),
                &'static str as ow => ow.owned("hello everyone <3"),
                @_ => panic!("unrecognised :( :(")
            })
        }

        let i64val: i64 = switch_out();
        let u32val: u32 = switch_out();
        let u16val: u16 = switch_out();
        let sstrval: &'static str = switch_out();

        assert_eq!(i64val, 83);
        assert_eq!(u32val, 20);
        assert_eq!(u16val, 16);
        assert_eq!(sstrval, "hello everyone <3");
    }

    /// Function that mainly exists to ensure various forms can be combined without cursed macro
    /// parsing errors.
    #[test]
    fn basic_combo_parsing_test() {
        /// The output on here is basically so unusedness is not complained about
        fn switch_multi<T: Any, T2: Any, T3: Any, V: Any, V2: Any>(
            val: V,
            val2: V2,
            anyr: &dyn Any,
            anym: &mut dyn Any,
        ) -> bool {
            let simples = typematch!((
                val val,
                anyref anyr,
                anymut anym,
                T,
                type T2,
                out T3
            ) {
                (@_, @_, @_, @_, @_, @_) => true
            });
            #[allow(unused_variables)]
            let complex = typematch!((
                val (val: V2 = val2),
                anyref (r = anyr),
                anymut (m = anym),
                T,
                type T2,
                out T3,
            ) {
                (u32 as d, @_, @_, @_, @_, @_) => {
                    d == d
                },
                (@_, @_, @_, @_, @_, @_) => true
            });
            simples && complex
        }
        assert!(switch_multi::<
            HashMap<String, u32>,
            HashMap<u32, u64>,
            bool,
            _,
            _,
        >(String::new(), Vec::<u8>::new(), &34u32, &mut 38u8));
    }
}

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.