File: test.rs

package info (click to toggle)
rust-easy-ext 1.0.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 284 kB
  • sloc: makefile: 2
file content (668 lines) | stat: -rw-r--r-- 14,713 bytes parent folder | download
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
// SPDX-License-Identifier: Apache-2.0 OR MIT

#![allow(
    dead_code,
    unreachable_pub,
    clippy::items_after_statements,
    clippy::missing_safety_doc,
    clippy::no_effect_underscore_binding,
    clippy::undocumented_unsafe_blocks
)]

use std::{pin::Pin, rc::Rc};

use async_trait::async_trait;
use easy_ext::ext;

#[test]
fn simple() {
    #[ext]
    impl str {
        fn foo(&self, pat: &str) -> String {
            self.replace(pat, "_")
        }
    }

    assert_eq!("--".foo("-"), "__");
}

#[test]
fn params() {
    #[ext]
    impl<T, E> Result<T, E> {
        fn err_into<U>(self) -> Result<T, U>
        where
            E: Into<U>,
        {
            self.map_err(Into::into)
        }
    }

    let err: Result<(), _> = Err(1_u32);
    assert_eq!(err.err_into::<u64>().unwrap_err(), 1_u64);
}

#[test]
fn lifetime() {
    #[ext(OptionExt)]
    impl<'a, T> &'a mut Option<T> {
        fn into_ref(self) -> Option<&'a T> {
            self.as_ref()
        }
    }

    let _: Option<&u8> = Some(1).into_ref();
}

mod bar {
    use easy_ext::ext;

    // assoc-item-level visibility + named
    #[ext(E1)]
    impl str {
        pub const FOO1: &'static str = "_";

        pub fn foo1(&self, pat: &str) -> String {
            self.replace(pat, Self::FOO1)
        }
    }

    // assoc-item-level visibility + unnamed
    #[ext]
    impl str {
        pub const FOO2: &'static str = "_";

        pub fn foo2(&self, pat: &str) -> String {
            self.replace(pat, Self::FOO2)
        }
    }

    // impl-level visibility + named
    #[ext(E2)]
    pub impl str {
        const FOO3: &'static str = "_";

        fn foo3(&self, pat: &str) -> String {
            self.replace(pat, Self::FOO3)
        }
    }

    // impl-level visibility + unnamed
    #[ext]
    pub impl str {
        const FOO4: &'static str = "_";

        fn foo4(&self, pat: &str) -> String {
            self.replace(pat, Self::FOO4)
        }
    }

    pub(super) mod baz {
        use easy_ext::ext;

        #[ext(E4)]
        impl str {
            pub(super) fn bar(&self, pat: &str) -> String {
                self.replace(pat, "_")
            }
        }

        #[ext(E5)]
        impl str {
            pub fn baz(&self, pat: &str) -> String {
                self.replace(pat, "_")
            }

            pub fn baz2(&self, pat: &str) -> String {
                self.replace(pat, "-")
            }
        }

        #[ext(E6)]
        pub(super) impl str {
            fn bar2(&self, pat: &str) -> String {
                self.replace(pat, "_")
            }
        }

        #[ext(E7)]
        pub(crate) impl str {
            fn baz3(&self, pat: &str) -> String {
                self.replace(pat, "_")
            }

            fn baz4(&self, pat: &str) -> String {
                self.replace(pat, "-")
            }
        }
    }
}

#[test]
fn visibility() {
    use self::bar::{
        baz::{E5, E7},
        E1, E2,
    };

    assert_eq!("..".foo1("."), "__");
    assert_eq!("..".foo3("."), "__");
    assert_eq!("..".baz("."), "__");
    assert_eq!("..".baz2("."), "--");
    assert_eq!("..".baz3("."), "__");
    assert_eq!("..".baz4("."), "--");
}

#[test]
fn generics() {
    #[ext(IterExt)]
    impl<I: IntoIterator> I {
        fn _next(self) -> Option<I::Item> {
            self.into_iter().next()
        }
    }

    assert_eq!(vec![1, 2, 3]._next(), Some(1_u8));
}

#[test]
fn trait_generics() {
    #[derive(Debug, PartialEq, Eq)]
    struct A {}

    impl Iterator for A {
        type Item = ();
        fn next(&mut self) -> Option<Self::Item> {
            None
        }
    }

    #[ext(ConstInit)]
    impl A {
        const INIT1: Self = Self {};
        const INIT2: A = A {};
    }

    #[ext(Ext1)]
    impl<I: Iterator + ConstInit> I {
        const CONST1: Self = Self::INIT1;
        const CONST2: I = I::INIT1;
        type Item2 = Self::Item;
        type Item3 = I::Item;
        fn method1(mut self) -> Option<Self::Item> {
            self.next()
        }
        fn method2(mut self) -> Option<I::Item> {
            self.next()
        }
        fn method3(mut self) -> Option<Self::Item2> {
            self.next()
        }
        fn method4(mut self) -> Option<<I as Ext1>::Item3> {
            self.next()
        }
    }

    fn a<T: Ext1 + Eq + std::fmt::Debug>(mut x: T) {
        let y = T::CONST1;
        let _ = T::CONST2;
        assert_eq!(x, y);
        assert!(x.next().is_none());
    }

    assert_eq!(A {}.method1(), None);
    assert_eq!(A {}.method2(), None);

    a(A::INIT1);
    a(A::INIT2);

    #[ext(Ext2)]
    impl<I: Iterator + ConstInit> I {
        const CONST3: I = {
            fn a<I>() {}
            I::INIT1
        };
        type Item4 = I::Item;
        fn method5(self, _: I::Item) -> (Option<I::Item>, <I as Ext2>::Item4) {
            fn a<I>() {}
            unimplemented!()
        }
    }
}

#[test]
fn type_parameter_defaults() {
    #[ext(Ext)]
    impl<T = ()> () {}
    impl Ext for u8 {}

    // The code above is equivalent to the code below.

    trait Trait<T = ()> {}
    impl<T> Trait<T> for () {}
    impl Trait for u8 {}
}

// See also ui/maybe.rs
#[test]
fn maybe() {
    #[ext]
    impl<T: ?Sized> T {
        fn f(&self) {}
    }

    #[ext]
    impl<T> T
    where
        T: ?Sized,
    {
        fn f(&self) {}
    }

    #[ext]
    impl<T: Send + ?Sized + Sync> T {
        fn f(&self) {}
    }

    #[ext]
    impl<T> T
    where
        T: Send + ?Sized + Sync,
    {
        fn f(&self) {}
    }

    #[ext]
    impl<T> T
    where
        T: Iterator,
        T: ?Sized,
        T: Default,
    {
        fn f(&self) {}
    }
}

#[test]
fn inline() {
    #[ext]
    impl str {
        #[inline]
        fn auto(&self) {}
        #[inline(always)]
        fn always(&self) {}
        #[inline(never)]
        fn never(&self) {}
    }
}

#[test]
fn assoc_ty() {
    #[ext(StrExt)]
    impl str {
        type Assoc = String;

        fn owned(&self) -> Self::Assoc {
            self.to_owned()
        }
    }

    let s: <str as StrExt>::Assoc = "?".owned();
    assert_eq!(s, "?");

    #[ext(TryIterator)]
    impl<I: Iterator<Item = Result<T, E>>, T, E> I {
        type Ok = T;
        type Error = E;

        fn try_next(&mut self) -> Result<Option<Self::Ok>, Self::Error> {
            self.next().transpose()
        }
    }

    let mut iter = vec![Ok(1), Err(1)].into_iter();
    assert_eq!(iter.try_next(), Ok(Some(1)));
    assert_eq!(iter.try_next(), Err(1));
    assert_eq!(iter.try_next(), Ok(None));
}

#[allow(clippy::let_underscore_future)]
#[test]
fn syntax() {
    #[ext(E1)]
    unsafe impl str {
        fn normal(&self) {}
        unsafe fn unsafety(&self) {}
        extern "C" fn abi1() {}
        extern "C" fn abi2() {}
        unsafe extern "C" fn unsafe_abi1() {}
        unsafe extern "C" fn unsafe_abi2() {}
    }

    "a".normal();
    unsafe { "?".unsafety() };
    str::abi1();
    unsafe { str::unsafe_abi1() };

    struct S {}
    unsafe impl E1 for S {
        fn normal(&self) {}
        unsafe fn unsafety(&self) {}
        extern "C" fn abi1() {}
        extern "C" fn abi2() {}
        unsafe extern "C" fn unsafe_abi1() {}
        unsafe extern "C" fn unsafe_abi2() {}
    }

    #[ext(E2)]
    #[async_trait]
    impl str {
        async fn asyncness(&self) {}
        async unsafe fn unsafe_asyncness(&self) {}
    }

    let _ = async {
        "a".asyncness().await;
        unsafe { "b".unsafe_asyncness().await }
    };

    #[async_trait]
    impl E2 for S {
        async fn asyncness(&self) {}
        async unsafe fn unsafe_asyncness(&self) {}
    }
}

// test for angle bracket
#[test]
fn angle_bracket() {
    #[ext]
    impl fn() -> () {
        const FUNC: fn() -> fn() -> fn() -> () = Self::func;
        type Func = fn() -> fn() -> ();
        fn func() -> fn() -> fn() -> () {
            || || {}
        }
    }

    #[ext(E1)]
    impl<T> T
    where
        Self::Assoc3: Sized,
        T::Assoc3: Sized,
        Self: E2,
        T: E2,
    {
        const ASSOC1: <Self>::Assoc1 = <Self>::assoc1;
        type Assoc1 = fn() -> <Self>::Assoc2;
        type Assoc2 = ();
        fn assoc1() -> <Self>::Assoc2
        where
            <Self as E1>::Assoc1: Sized,
            <T as E1>::Assoc1: Sized,
            Self::Assoc1: Sized,
            T::Assoc3: Sized,
            Self: E2,
            T: E2,
        {
        }
    }

    struct A {}
    #[ext(E2)]
    impl A {
        const ASSOC1: <Self>::Assoc3 = <Self>::assoc2;
        type Assoc3 = fn() -> <Self>::Assoc4;
        type Assoc4 = ();
        fn assoc2() -> <Self>::Assoc4
        where
            <Self as E2>::Assoc3: Sized,
            Self::Assoc3: Sized,
        {
        }
    }

    #[ext]
    impl<T: Fn() -> fn() -> T, E> Result<T, E>
    where
        E: FnOnce() -> Result<T, E>,
        &'static dyn Fn() -> T: Fn() -> T + 'static,
        fn() -> fn() -> T: Fn() -> fn() -> T,
    {
        fn where_clause<U: Fn() -> fn() -> T, F>(self, _f: F) -> Self
        where
            F: FnOnce() -> Result<U, E>,
            &'static dyn Fn() -> T: Fn() -> T + 'static,
            fn() -> fn() -> T: Fn() -> fn() -> T,
        {
            unimplemented!()
        }
    }
}

#[test]
fn min_const_generics() {
    struct S1<T, const CAP: usize>([T; CAP]);
    #[ext(E1)]
    impl<T, const CAP: usize> S1<T, CAP> {
        const CAPACITY: usize = CAP;
        fn f<const C: usize>() -> S1<T, C> {
            unimplemented!()
        }
    }

    struct S2<const CAP: usize>;
    impl<const CAP: usize> E1<(), { CAP }> for S2<{ CAP }> {
        const CAPACITY: usize = CAP;
        fn f<const C: usize>() -> S1<(), { C }> {
            S1([(); C])
        }
    }

    let _: [(); 2] = <S2<3>>::f::<2>().0;

    struct S3<T, const CAP: char>(T);

    #[ext(E2)]
    impl str {
        fn method1(&self) -> S1<Option<fn() -> ()>, 1> {
            S1([Some(|| {})])
        }
        #[allow(unused_braces)]
        fn method2(&self) -> S1<Option<fn() -> ()>, { 1 }> {
            S1([Some(|| {})])
        }
        fn method3(&self) -> S3<fn() -> (), 'a'> {
            S3(|| {})
        }
        #[allow(unused_braces)]
        fn method4(&self) -> S3<fn() -> (), { 'a' }> {
            S3(|| {})
        }
    }
}

#[test]
fn const_generics_defaults() {
    // https://github.com/rust-lang/rust/tree/1.70.0/tests/ui/const-generics/defaults

    #[ext(Ext)]
    impl<const N: usize = 3> () {}
    impl Ext for u8 {}

    // The code above is equivalent to the code below.

    trait Trait<const N: usize = 3> {}
    impl<const N: usize> Trait<N> for () {}
    impl Trait for u8 {}

    // https://github.com/rust-lang/rust/blob/1.70.0/tests/ui/const-generics/defaults/const-param-as-default-value.rs
    #[ext(Ext2)]
    impl<const N: usize, const M: usize = N> () {}
}

#[test]
fn generic_associated_types() {
    // https://github.com/rust-lang/rust/blob/1.70.0/tests/ui/generic-associated-types/collections.rs

    trait CollectionFamily {
        type Member<T>: Collection<T, Family = Self>;
    }

    struct VecFamily;

    impl CollectionFamily for VecFamily {
        type Member<T> = Vec<T>;
    }

    #[ext(Collection)]
    impl<T> Vec<T> {
        // TODO: handle where clause in GAT: https://github.com/rust-lang/rust/pull/90076
        // type Iter<'iter> = std::slice::Iter<'iter, T>
        // where
        //     T: 'iter,
        //     Self: 'iter;
        type Family = VecFamily;
        type Sibling<U> = <<Self as Collection<T>>::Family as CollectionFamily>::Member<U>;

        fn empty() -> Self {
            vec![]
        }

        fn add(&mut self, value: T) {
            self.push(value);
        }

        // TODO: handle where clause in GAT: https://github.com/rust-lang/rust/pull/90076
        // fn iterate<'iter>(&'iter self) -> Self::Iter<'iter> {
        //     self.iter()
        // }
    }
}

#[test]
fn macros() {
    macro_rules! m {
        (
            $impl:ident $path:path [$($generics:tt)*] $where:ident {$(
                [$vis:vis, $($fn_sig:ident)*]
            )*}
        ) => {
            $(
                #[ext]
                $impl<T, E> Result<T, E> {
                    $vis $($fn_sig)* <U>(self) -> Result<T, U>
                    where
                        E: Into<U>,
                    {
                        unimplemented!()
                    }
                }
            )*
        };
    }

    m!(impl Result [T,E] where {
        [, fn a]
        [pub, fn b]
        [pub, unsafe fn c]
        [pub(crate), fn d]
    });
}

// https://github.com/taiki-e/easy-ext/issues/36
#[test]
fn where_clause() {
    pub trait Trait<T> {}

    #[rustfmt::skip]
    #[ext]
    pub impl<T> Vec<T>
    where
        Self: Trait<Vec<T>>
    {
    }
}

#[allow(clippy::needless_pub_self)] // This is intentional
pub mod visibility {
    use easy_ext::ext;

    pub struct Pub;
    #[ext]
    impl str {
        pub const ASSOC: u8 = 1;
        pub type Assoc = u8;
        pub fn assoc() {}
    }

    pub struct PubCrate;
    #[ext]
    impl PubCrate {
        pub(crate) const ASSOC: u8 = 1;
        pub(crate) type Assoc = u8;
        pub(crate) fn assoc() {}
    }

    pub struct PubSelf;
    #[ext]
    impl PubSelf {
        pub(self) const ASSOC: u8 = 1;
        pub(self) type Assoc = u8;
        pub(self) fn assoc() {}
    }

    pub mod m {
        use easy_ext::ext;

        pub struct PubSuper;
        #[ext]
        impl PubSuper {
            pub(super) const ASSOC: u8 = 1;
            pub(super) type Assoc = u8;
            pub(super) fn assoc() {}
        }

        pub struct PubIn;
        #[ext]
        impl PubIn {
            pub(in super::m) const ASSOC: u8 = 1;
            pub(in super::m) type Assoc = u8;
            pub(in super::m) fn assoc() {}
        }
    }
}

#[test]
fn arg_pat() {
    #[ext]
    impl str {
        fn f((x, y): (u8, u8)) {
            let _x = x;
            let _y = y;
        }
    }
}

#[test]
fn arbitrary_self_types() {
    #[ext]
    #[allow(clippy::needless_arbitrary_self_type)]
    impl String {
        fn recv(self: Self) {}
        fn recv_ref(self: &Self) {}
        fn recv_mut(self: &mut Self) {}
        fn recv_rc(self: Rc<Self>) {}
        fn recv_rc_ref(self: &Rc<Self>) {}
        fn recv_rc_mut(self: &mut Rc<Self>) {}
        fn recv_pin_box(self: Pin<Box<Self>>) {}
    }

    String::default().recv();
    String::default().recv_ref();
    String::default().recv_mut();
    Rc::new(String::default()).recv_rc();
    Rc::new(String::default()).recv_rc_ref();
    Rc::new(String::default()).recv_rc_mut();
    Box::pin(String::default()).recv_pin_box();
}