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
//! Do you think Rust macros are a bit like magic? I do too!
//!
//! With this crate you can live your wizard dreams right in your source code.
//! It aliases some common (and some less common) code snippets to macros
//! named after thematically appropriate spells from Harry Potter.
//!
//! This enables you to cast [`geminio!(item)`](geminio) instead of forcing you to call [`item.clone()`](core::clone::Clone::clone).
//! ```
//! # use code_spells::{accio, erecto, obliviate, expecto_patronum, geminio};
//! let v1 = vec![erecto!(i32); 5];
//! let mut v2 = geminio!(&v1);
//! obliviate!(v1);
//! accio!(expecto_patronum!(v2.get_mut(0), "Dementors B-gone!")) = 5;
//! ```
//! Also aliases `unsafe` to the macro [`unforgivable!`](unforgivable),
//! because what could be more unforgivable than undefined behaviour?  

/// Alias for [`std::thread::sleep`](std::thread::sleep).
/// # Example
/// ```
/// # use code_spells::petrificus_totalus;
/// petrificus_totalus!(std::time::Duration::from_secs(1));
/// ```
#[macro_export]
macro_rules! petrificus_totalus {
    ($duration:expr) => {
        ::std::thread::sleep($duration)
    };
}

/// Alias for [`panic!`].
/// # Example
/// ```no_run
/// # use code_spells::avada_kedavra;
/// avada_kedavra!("Lily Potter");
/// let lily_potter = "continue"; // This code will never execute, as the program is dead!
/// ```
#[macro_export]
macro_rules! avada_kedavra {
    ($($arg:tt)*) => {
        panic!($($arg)*)
    };
}

/// Alias for [`Drop::drop`](core::mem::drop).
/// # Examples
/// Drop the return value of an expression:
/// ```
/// # use code_spells::obliviate;
/// obliviate!(vec![0; 5]);
/// ```
/// Drop a variable:
/// ```compile_fail
/// # use code_spells::obliviate;
/// let x = vec![0; 5];
/// obliviate!(x);
/// // no longer possible to reference x
/// println!("{x:?}");
/// ```
#[macro_export]
macro_rules! obliviate {
    ($memory:expr) => {
        ::core::mem::drop($memory)
    };
}

/// Constructs the given type using either the [`Default::default`](core::default::Default::default)
/// or `new(<optional args>)` functions.
/// Calling it with `erecto!(type)` results in the former, while
/// `erecto!(type: <optional args>)` results in the latter.
/// # Examples
/// ```
/// # use code_spells::erecto;
/// #[derive(Debug, Default, PartialEq)]
/// struct Thing {
///     x: u8,
/// }
///
/// impl Thing {
///     fn new(x: u8) -> Self {
///         Self { x }
///     }
/// }
///
/// assert_eq!(erecto!(u8), 0);
/// assert_eq!(erecto!(String), String::default());
/// assert_eq!(erecto!(String:), String::new());
/// assert_eq!(erecto!(Thing), Thing::default());
/// assert_eq!(erecto!(Thing: 5), Thing::new(5));
/// ```
#[macro_export]
macro_rules! erecto {
    ($t:ty) => {
        <$t as ::core::default::Default>::default()
    };
    ($t:ty: $($arg:expr),*) => {
        <$t>::new( $($arg,)* )
    };
}

/// Alias for dereferencing. This does not use the [`Deref`](core::ops::Deref) or [`DerefMut`](core::ops::DerefMut) traits,
/// but prepends `*` to the start of the given expression.
/// # Example
/// ```
/// # use code_spells::accio;
/// let x = 5;
/// let y = &x;
/// assert_eq!(accio!(y), x);
///
/// let a = vec![0; 5];
/// assert_eq!(accio!(a.get(0).unwrap()), 0);
/// ```
#[macro_export]
macro_rules! accio {
    ($x:expr) => {
        *$x
    };
}

/// Alias for [`Clone::clone`](core::clone::Clone::clone).
/// # Example
/// ```
/// # use code_spells::geminio;
/// let a = vec![0; 5];
/// let b = geminio!(&a);
/// drop(a);
/// assert_eq!(b, vec![0; 5]);
/// ```
#[macro_export]
macro_rules! geminio {
    ($object:expr) => {
        ::core::clone::Clone::clone($object)
    };
}

/// Alias for [`Pin::new`](core::pin::Pin::new).
/// # Example
/// ```
/// # use code_spells::immobulus;
/// let mut val = 5;
/// let pinned = immobulus!(&mut val);
/// let r = core::pin::Pin::into_inner(pinned);
/// assert_eq!(*r, 5);
/// ```
#[macro_export]
macro_rules! immobulus {
    ($item:expr) => {
        ::core::pin::Pin::new($item)
    };
}

/// Appends `.expect(message)` if given a message, otherwise appends `.unwrap()`.
/// # Examples
/// ```
/// # use code_spells::expecto_patronum;
/// expecto_patronum!(u8::try_from(5));
/// ```
/// ```should_panic
/// # use code_spells::expecto_patronum;
/// expecto_patronum!(u8::try_from(-5), "Here be Dementors!");
/// ```
#[macro_export]
macro_rules! expecto_patronum {
    ($danger:expr, $message:expr) => {
        $danger.expect($message)
    };
    ($danger:expr) => {
        $danger.unwrap()
    };
}

/// Alias for [`Mutex::lock`](std::sync::Mutex::lock).
/// # Example
/// ```
/// # use code_spells::colloportus;
/// use std::sync::Mutex;
/// let door = Mutex::new(5);
/// let guard_result = colloportus!(&door);
/// ```
#[macro_export]
macro_rules! colloportus {
    ($door:expr) => {
        ::std::sync::Mutex::lock($door)
    };
}

/// Alias for [`Box::leak`](std::boxed::Box::leak). The item is still there, it's just invisible. Can be revealed with [`aparecium!`](aparecium).
/// # Examples
/// If the returned pointer is dropped this causes a memory leak. You forgot where you put it, and it's invisible.
/// ```compile_fail
/// # use code_spells::evanesco;
/// let a = Box::new(vec![5; 100]);
/// evanesco!(a);
/// println!("{a:?}");
/// ```
/// ```no_run
/// # use code_spells::evanesco;
/// let ostrich = Box::new(vec![5; 100]);
/// // What do you have there?
/// evanesco!(ostrich);
/// // A smoothie..?
/// ```
/// Using [`Box::from_raw`](std::boxed::Box::from_raw) is one way of getting the item back.
/// This crate allows that function to be cast with [aparecium!].
/// ```
/// # use code_spells::{evanesco, aparecium};
/// let a: &mut Vec<i32> = evanesco!(Box::new(vec![5; 100]));
/// assert_eq!(unsafe { aparecium!(a) }, Box::new(vec![5; 100]));
/// ```
#[macro_export]
macro_rules! evanesco {
    ($item:expr) => {
        ::std::boxed::Box::leak($item)
    };
}

/// Alias for [`Box::from_raw`](std::boxed::Box::from_raw). Useful if you have made something invisible with [`evanesco!`](evanesco).
/// This is `unsafe` as revealing something invisible might not be what the invisible thing wants,
/// and it might attack you and cause undefined behaviour.
/// # Example
/// ```
/// # use code_spells::{evanesco, aparecium};
/// let a: &mut Vec<i32> = evanesco!(Box::new(vec![5; 100]));
/// assert_eq!(unsafe { aparecium!(a) }, Box::new(vec![5; 100]));
/// ```
#[macro_export]
macro_rules! aparecium {
    ($item:expr) => {
        ::std::boxed::Box::from_raw($item)
    };
}

/// Alias for [`println!`].
/// # Example
/// ```
/// # use code_spells::sonorous;
/// sonorous!("Hello, World!");
/// sonorous!("{} chocolate", "dark");
/// let a = 1 + 1;
/// sonorous!("{a} is not {}", 5);
/// ```
#[macro_export]
macro_rules! sonorous {
    () => {
        print!("\n")
    };
    ($($arg:tt)*) => {
        println!($($arg)*)
    };
}

/// Alias for [`Result::unwrap_or`](core::result::Result::unwrap_or) and [`Result::unwrap_or_else`](core::result::Result::unwrap_or_else).
/// Automatically chooses [`unwrap_or_else`](core::result::Result::unwrap_or_else) if given a closure,
/// and [`unwrap_or`](core::result::Result::unwrap_or) if given an expression that is not a closure.
/// # Example
/// ```
/// # use code_spells::reparo;
/// fn foo(x: u8) -> Result<u8, u8> {
///     if x < 125 {
///         Ok(x)
///     } else {
///         Err(x)
///     }
/// }
/// let five = 5;
/// assert_eq!(reparo!(foo(5), five), 5); // unwrap_or
/// assert_eq!(reparo!(foo(255), u8::MAX), u8::MAX); // unwrap_or
/// assert_eq!(reparo!(foo(255), |_| 5), 5); // unwrap_or_else
/// let primes = vec![2, 3, 5];
/// assert_eq!(reparo!(foo(255), move |_| primes.into_iter().sum()), 10); // unwrap_or_else
/// ```
/// # Note
/// If the second argument is the name of a function this macro will not work.
/// ```compile_fail
/// # use code_spells::reparo;
/// # fn foo(x: u8) -> Result<u8, u8> {if x < 125 { Ok(x) } else { Err(x) } }
/// fn ten() -> u8 { 10 }
/// assert_eq!(reparo!(foo(255), ten), 10);
/// ```
/// We can make it work by converting the function to a closure
/// ```
/// # use code_spells::reparo;
/// # fn foo(x: u8) -> Result<u8, u8> {if x < 125 { Ok(x) } else { Err(x) } }
/// # fn ten() -> u8 { 10 }
/// assert_eq!(reparo!(foo(255), |_| ten()), 10); // uses unwrap_or_else
/// ```
/// or by calling the function in the macro.
/// ```
/// # use code_spells::reparo;
/// # fn foo(x: u8) -> Result<u8, u8> {if x < 125 { Ok(x) } else { Err(x) } }
/// # fn ten() -> u8 { 10 }
/// assert_eq!(reparo!(foo(255), ten()), 10); // uses unwrap_or
/// ```
#[macro_export]
macro_rules! reparo {
    ($result:expr, move |$arg_name:pat_param| $body:expr) => {
        ::core::result::Result::unwrap_or_else($result, move |$arg_name| $body)
    };
    ($result:expr, |$arg_name:pat_param| $body:expr) => {
        ::core::result::Result::unwrap_or_else($result, |$arg_name| $body)
    };
    ($result:expr, $alt:expr) => {
        ::core::result::Result::unwrap_or($result, $alt)
    };
}

/// Alias for unsafe. What could be more unforgivable than undefined behaviour?
/// # Example
/// ```
/// # use code_spells::unforgivable;
/// use core::num::NonZeroU8;
/// // Forgivability: `new_unchecked` is UB if the argument is zero, but two is not zero.
/// const two: NonZeroU8 = unforgivable! { NonZeroU8::new_unchecked(2) };
/// assert_eq!(two.get(), 2);
/// ```
#[macro_export]
macro_rules! unforgivable {
    ($($code:tt)+) => {
        unsafe {
            $($code)+
        }
    };
}

/// Alias for [`Vec::reserve`](std::vec::Vec::reserve).
/// # Example
/// ```
/// # use code_spells::capacious_extremis;
/// let mut police_box = Vec::<i32>::new();
/// capacious_extremis!(&mut police_box, 5);
/// assert!(police_box.capacity() >= 5);
/// let r = &mut police_box;
/// capacious_extremis!(r, 10);
/// assert!(police_box.capacity() >= 10);
/// ```
#[macro_export]
macro_rules! capacious_extremis {
    (&mut $vec:ident, $capacity:expr) => {
        ::std::vec::Vec::reserve(&mut $vec, $capacity)
    };
    ($vec:ident, $capacity:expr) => {
        ::std::vec::Vec::reserve($vec, $capacity)
    };
}

/// Alias for [`mem::transmute`](core::mem::transmute). Disregard the rules, force the type system to do what you want!
/// # Safety
/// This spell is unforgivable for a reason, see the documentation of [`mem::transmute`](core::mem::transmute) for more details.
/// # Examples
/// ```
/// # use code_spells::{imperio, unforgivable};
/// let a = [0_u8; 4];
/// let b: u32 = unforgivable! { imperio!(a) };
/// assert_eq!(b, 0);
/// let mut c = unforgivable! { imperio!(b, u32 => [u8; 4]) };
/// assert_eq!(c, [0; 4]);
/// let d = &mut c;
/// assert_eq!(unforgivable! { imperio!(d, &mut [u8; 4] => &[u8; 4]) }, &c)
/// ```
/// Force a pointer to become a function pointer!
/// ```
/// # use code_spells::{imperio, unforgivable};
/// fn foo() -> i32 { 0 }
/// let pointer = foo as *const ();
/// let function = unforgivable! {
///     imperio!(pointer, *const () => fn() -> i32)
/// };
/// assert_eq!(function(), 0);
/// ```
#[macro_export]
macro_rules! imperio {
    // Elision
    ($will:expr) => {
        ::core::mem::transmute($will)
    };
    // Pure type to type
    ($will:expr, $src:ty => $dst:ty) => {
        ::core::mem::transmute::<$src, $dst>($will)
    };
    // Attempt to match against any expression
    ($will:expr, $src:expr => $dst:expr) => {
        ::core::mem::transmute::<$src, $dst>($will)
    };
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn practice_obliviate() {
        let x = vec![0; 5];
        obliviate!(x);
    }

    #[test]
    fn practice_accio() {
        let x = 5;
        let y = &x;
        assert_eq!(accio!(y), 5);
    }

    #[test]
    fn practice_erecto() {
        #[derive(Debug, Default, PartialEq)]
        struct Thing {
            x1: f64,
            x2: f32,
            y1: u64,
            y2: u32,
            y3: u16,
            y4: u8,
            y5: i64,
            y6: i32,
            y7: i16,
            y8: i8,
            y9: u128,
            y10: i128,
            y11: usize,
            y12: isize,
            b: bool,
            cs: std::ffi::CString,
            os: std::ffi::OsString,
            s: String,
        }
        impl Thing {
            fn new(b: bool, x: u8) -> Self {
                Self {
                    b,
                    y4: x,
                    ..Default::default()
                }
            }
        }
        assert_eq!(erecto!(Thing), Thing::default());
        assert_eq!(erecto!(Thing: true, 5), Thing::new(true, 5));
        let b = true;
        let x = 5;
        assert_eq!(erecto!(Thing: b, x), Thing::new(b, x));
        assert_eq!(
            erecto!(Thing: 5 != 2, 2_u8.pow(5)),
            Thing::new(5 != 2, 2_u8.pow(5))
        );
        assert_eq!(erecto!(Thing: 5 != 2, x), Thing::new(5 != 2, x));
        assert_eq!(erecto!(String:), String::new());
    }

    #[test]
    fn practice_geminio() {
        let a = vec![0; 5];
        let b = geminio!(&a);
        assert_eq!(a, b);
        drop(a);
        assert_eq!(b, vec![0; 5]);
    }

    #[test]
    fn practice_immobulus() {
        let mut val = 5;
        let pinned = immobulus!(&mut val);
        let r = core::pin::Pin::into_inner(pinned);
        assert_eq!(*r, 5);
    }

    #[test]
    fn practice_expecto_patronum() {
        expecto_patronum!(u8::try_from(5));
    }

    #[test]
    fn practice_colloportus() {
        let door = std::sync::Mutex::new(5);
        let _guard = colloportus!(&door);
    }

    #[test]
    fn practice_evanesco_and_apericium() {
        let a = Box::new(vec![5; 100]);
        let b: &mut Vec<i32> = evanesco!(a);
        assert_eq!(unsafe { aparecium!(b) }, Box::new(vec![5; 100]));
    }

    #[test]
    fn practice_reparo() {
        fn foo(x: u8) -> Result<u8, u8> {
            if x < 125 {
                Ok(x)
            } else {
                Err(x)
            }
        }
        let five = 5;
        fn identity(x: u8) -> u8 {
            x
        }
        assert_eq!(reparo!(foo(5), five), 5);
        assert_eq!(reparo!(foo(255), u8::MAX), u8::MAX);
        assert_eq!(reparo!(foo(255), |_| 5), 5);
        assert_eq!(reparo!(foo(255), |_| identity(10)), 10);
    }

    #[test]
    fn practice_capacious_extremis() {
        let mut a = Vec::<i32>::new();
        let b = &mut a;
        capacious_extremis!(b, 5);
        capacious_extremis!(&mut a, 10);
        assert!(a.capacity() >= 10);
    }

    #[test]
    fn practice_imperio() {
        let a = [0_u8; 4];
        let b: u32 = unforgivable! { imperio!(a) };
        assert_eq!(b, 0);
        let c = unforgivable! { imperio!(b, u32 => [u8; 4]) };
        assert_eq!(c, [0; 4]);
    }
}