aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_ide/src/completion/complete_qualified_path.rs
blob: b08f5b9b45e0bdfe07f21991e59cdc48302d687e (plain)
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
//! Completion of paths, i.e. `some::prefix::<|>`.

use hir::{Adt, HasVisibility, PathResolution, ScopeDef};
use ra_syntax::AstNode;
use rustc_hash::FxHashSet;
use test_utils::mark;

use crate::completion::{CompletionContext, Completions};

pub(super) fn complete_qualified_path(acc: &mut Completions, ctx: &CompletionContext) {
    let path = match &ctx.path_prefix {
        Some(path) => path.clone(),
        None => return,
    };

    if ctx.attribute_under_caret.is_some() {
        return;
    }

    let context_module = ctx.scope.module();

    let resolution = match ctx.scope.resolve_hir_path_qualifier(&path) {
        Some(res) => res,
        None => return,
    };

    // Add associated types on type parameters and `Self`.
    resolution.assoc_type_shorthand_candidates(ctx.db, |alias| {
        acc.add_type_alias(ctx, alias);
        None::<()>
    });

    match resolution {
        PathResolution::Def(hir::ModuleDef::Module(module)) => {
            let module_scope = module.scope(ctx.db, context_module);
            for (name, def) in module_scope {
                if ctx.use_item_syntax.is_some() {
                    if let ScopeDef::Unknown = def {
                        if let Some(name_ref) = ctx.name_ref_syntax.as_ref() {
                            if name_ref.syntax().text() == name.to_string().as_str() {
                                // for `use self::foo<|>`, don't suggest `foo` as a completion
                                mark::hit!(dont_complete_current_use);
                                continue;
                            }
                        }
                    }
                }

                acc.add_resolution(ctx, name.to_string(), &def);
            }
        }
        PathResolution::Def(def @ hir::ModuleDef::Adt(_))
        | PathResolution::Def(def @ hir::ModuleDef::TypeAlias(_)) => {
            if let hir::ModuleDef::Adt(Adt::Enum(e)) = def {
                for variant in e.variants(ctx.db) {
                    acc.add_enum_variant(ctx, variant, None);
                }
            }
            let ty = match def {
                hir::ModuleDef::Adt(adt) => adt.ty(ctx.db),
                hir::ModuleDef::TypeAlias(a) => a.ty(ctx.db),
                _ => unreachable!(),
            };

            // XXX: For parity with Rust bug #22519, this does not complete Ty::AssocType.
            // (where AssocType is defined on a trait, not an inherent impl)

            let krate = ctx.krate;
            if let Some(krate) = krate {
                let traits_in_scope = ctx.scope.traits_in_scope();
                ty.iterate_path_candidates(ctx.db, krate, &traits_in_scope, None, |_ty, item| {
                    if context_module.map_or(false, |m| !item.is_visible_from(ctx.db, m)) {
                        return None;
                    }
                    match item {
                        hir::AssocItem::Function(func) => {
                            acc.add_function(ctx, func, None);
                        }
                        hir::AssocItem::Const(ct) => acc.add_const(ctx, ct),
                        hir::AssocItem::TypeAlias(ty) => acc.add_type_alias(ctx, ty),
                    }
                    None::<()>
                });

                // Iterate assoc types separately
                ty.iterate_assoc_items(ctx.db, krate, |item| {
                    if context_module.map_or(false, |m| !item.is_visible_from(ctx.db, m)) {
                        return None;
                    }
                    match item {
                        hir::AssocItem::Function(_) | hir::AssocItem::Const(_) => {}
                        hir::AssocItem::TypeAlias(ty) => acc.add_type_alias(ctx, ty),
                    }
                    None::<()>
                });
            }
        }
        PathResolution::Def(hir::ModuleDef::Trait(t)) => {
            // Handles `Trait::assoc` as well as `<Ty as Trait>::assoc`.
            for item in t.items(ctx.db) {
                if context_module.map_or(false, |m| !item.is_visible_from(ctx.db, m)) {
                    continue;
                }
                match item {
                    hir::AssocItem::Function(func) => {
                        acc.add_function(ctx, func, None);
                    }
                    hir::AssocItem::Const(ct) => acc.add_const(ctx, ct),
                    hir::AssocItem::TypeAlias(ty) => acc.add_type_alias(ctx, ty),
                }
            }
        }
        PathResolution::TypeParam(_) | PathResolution::SelfType(_) => {
            if let Some(krate) = ctx.krate {
                let ty = match resolution {
                    PathResolution::TypeParam(param) => param.ty(ctx.db),
                    PathResolution::SelfType(impl_def) => impl_def.target_ty(ctx.db),
                    _ => return,
                };

                let traits_in_scope = ctx.scope.traits_in_scope();
                let mut seen = FxHashSet::default();
                ty.iterate_path_candidates(ctx.db, krate, &traits_in_scope, None, |_ty, item| {
                    if context_module.map_or(false, |m| !item.is_visible_from(ctx.db, m)) {
                        return None;
                    }

                    // We might iterate candidates of a trait multiple times here, so deduplicate
                    // them.
                    if seen.insert(item) {
                        match item {
                            hir::AssocItem::Function(func) => {
                                acc.add_function(ctx, func, None);
                            }
                            hir::AssocItem::Const(ct) => acc.add_const(ctx, ct),
                            hir::AssocItem::TypeAlias(ty) => acc.add_type_alias(ctx, ty),
                        }
                    }
                    None::<()>
                });
            }
        }
        _ => {}
    }
}

#[cfg(test)]
mod tests {
    use expect::{expect, Expect};
    use test_utils::mark;

    use crate::completion::{
        test_utils::{check_edit, completion_list},
        CompletionKind,
    };

    fn check(ra_fixture: &str, expect: Expect) {
        let actual = completion_list(ra_fixture, CompletionKind::Reference);
        expect.assert_eq(&actual);
    }

    fn check_builtin(ra_fixture: &str, expect: Expect) {
        let actual = completion_list(ra_fixture, CompletionKind::BuiltinType);
        expect.assert_eq(&actual);
    }

    #[test]
    fn dont_complete_current_use() {
        mark::check!(dont_complete_current_use);
        check(r#"use self::foo<|>;"#, expect![[""]]);
    }

    #[test]
    fn dont_complete_current_use_in_braces_with_glob() {
        check(
            r#"
mod foo { pub struct S; }
use self::{foo::*, bar<|>};
"#,
            expect![[r#"
                st S
                md foo
            "#]],
        );
    }

    #[test]
    fn dont_complete_primitive_in_use() {
        check_builtin(r#"use self::<|>;"#, expect![[""]]);
    }

    #[test]
    fn dont_complete_primitive_in_module_scope() {
        check_builtin(r#"fn foo() { self::<|> }"#, expect![[""]]);
    }

    #[test]
    fn completes_primitives() {
        check_builtin(
            r#"fn main() { let _: <|> = 92; }"#,
            expect![[r#"
                bt bool
                bt char
                bt f32
                bt f64
                bt i128
                bt i16
                bt i32
                bt i64
                bt i8
                bt isize
                bt str
                bt u128
                bt u16
                bt u32
                bt u64
                bt u8
                bt usize
            "#]],
        );
    }

    #[test]
    fn completes_mod_with_same_name_as_function() {
        check(
            r#"
use self::my::<|>;

mod my { pub struct Bar; }
fn my() {}
"#,
            expect![[r#"
                st Bar
            "#]],
        );
    }

    #[test]
    fn filters_visibility() {
        check(
            r#"
use self::my::<|>;

mod my {
    struct Bar;
    pub struct Foo;
    pub use Bar as PublicBar;
}
"#,
            expect![[r#"
                st Foo
                st PublicBar
            "#]],
        );
    }

    #[test]
    fn completes_use_item_starting_with_self() {
        check(
            r#"
use self::m::<|>;

mod m { pub struct Bar; }
"#,
            expect![[r#"
                st Bar
            "#]],
        );
    }

    #[test]
    fn completes_use_item_starting_with_crate() {
        check(
            r#"
//- /lib.rs
mod foo;
struct Spam;
//- /foo.rs
use crate::Sp<|>
"#,
            expect![[r#"
                st Spam
                md foo
            "#]],
        );
    }

    #[test]
    fn completes_nested_use_tree() {
        check(
            r#"
//- /lib.rs
mod foo;
struct Spam;
//- /foo.rs
use crate::{Sp<|>};
"#,
            expect![[r#"
                st Spam
                md foo
            "#]],
        );
    }

    #[test]
    fn completes_deeply_nested_use_tree() {
        check(
            r#"
//- /lib.rs
mod foo;
pub mod bar {
    pub mod baz {
        pub struct Spam;
    }
}
//- /foo.rs
use crate::{bar::{baz::Sp<|>}};
"#,
            expect![[r#"
                st Spam
            "#]],
        );
    }

    #[test]
    fn completes_enum_variant() {
        check(
            r#"
enum E { Foo, Bar(i32) }
fn foo() { let _ = E::<|> }
"#,
            expect![[r#"
                ev Bar(…) (i32)
                ev Foo    ()
            "#]],
        );
    }

    #[test]
    fn completes_struct_associated_items() {
        check(
            r#"
//- /lib.rs
struct S;

impl S {
    fn a() {}
    fn b(&self) {}
    const C: i32 = 42;
    type T = i32;
}

fn foo() { let _ = S::<|> }
"#,
            expect![[r#"
                ct C   const C: i32 = 42;
                ta T   type T = i32;
                fn a() fn a()
                me b() fn b(&self)
            "#]],
        );
    }

    #[test]
    fn associated_item_visibility() {
        check(
            r#"
struct S;

mod m {
    impl super::S {
        pub(super) fn public_method() { }
        fn private_method() { }
        pub(super) type PublicType = u32;
        type PrivateType = u32;
        pub(super) const PUBLIC_CONST: u32 = 1;
        const PRIVATE_CONST: u32 = 1;
    }
}

fn foo() { let _ = S::<|> }
"#,
            expect![[r#"
                ct PUBLIC_CONST    pub(super) const PUBLIC_CONST: u32 = 1;
                ta PublicType      pub(super) type PublicType = u32;
                fn public_method() pub(super) fn public_method()
            "#]],
        );
    }

    #[test]
    fn completes_enum_associated_method() {
        check(
            r#"
enum E {};
impl E { fn m() { } }

fn foo() { let _ = E::<|> }
        "#,
            expect![[r#"
                fn m() fn m()
            "#]],
        );
    }

    #[test]
    fn completes_union_associated_method() {
        check(
            r#"
union U {};
impl U { fn m() { } }

fn foo() { let _ = U::<|> }
"#,
            expect![[r#"
                fn m() fn m()
            "#]],
        );
    }

    #[test]
    fn completes_use_paths_across_crates() {
        check(
            r#"
//- /main.rs
use foo::<|>;

//- /foo/lib.rs
pub mod bar { pub struct S; }
"#,
            expect![[r#"
                md bar
            "#]],
        );
    }

    #[test]
    fn completes_trait_associated_method_1() {
        check(
            r#"
trait Trait { fn m(); }

fn foo() { let _ = Trait::<|> }
"#,
            expect![[r#"
                fn m() fn m()
            "#]],
        );
    }

    #[test]
    fn completes_trait_associated_method_2() {
        check(
            r#"
trait Trait { fn m(); }

struct S;
impl Trait for S {}

fn foo() { let _ = S::<|> }
"#,
            expect![[r#"
                fn m() fn m()
            "#]],
        );
    }

    #[test]
    fn completes_trait_associated_method_3() {
        check(
            r#"
trait Trait { fn m(); }

struct S;
impl Trait for S {}

fn foo() { let _ = <S as Trait>::<|> }
"#,
            expect![[r#"
                fn m() fn m()
            "#]],
        );
    }

    #[test]
    fn completes_ty_param_assoc_ty() {
        check(
            r#"
trait Super {
    type Ty;
    const CONST: u8;
    fn func() {}
    fn method(&self) {}
}

trait Sub: Super {
    type SubTy;
    const C2: ();
    fn subfunc() {}
    fn submethod(&self) {}
}

fn foo<T: Sub>() { T::<|> }
"#,
            expect![[r#"
                ct C2          const C2: ();
                ct CONST       const CONST: u8;
                ta SubTy       type SubTy;
                ta Ty          type Ty;
                fn func()      fn func()
                me method()    fn method(&self)
                fn subfunc()   fn subfunc()
                me submethod() fn submethod(&self)
            "#]],
        );
    }

    #[test]
    fn completes_self_param_assoc_ty() {
        check(
            r#"
trait Super {
    type Ty;
    const CONST: u8 = 0;
    fn func() {}
    fn method(&self) {}
}

trait Sub: Super {
    type SubTy;
    const C2: () = ();
    fn subfunc() {}
    fn submethod(&self) {}
}

struct Wrap<T>(T);
impl<T> Super for Wrap<T> {}
impl<T> Sub for Wrap<T> {
    fn subfunc() {
        // Should be able to assume `Self: Sub + Super`
        Self::<|>
    }
}
"#,
            expect![[r#"
                ct C2          const C2: () = ();
                ct CONST       const CONST: u8 = 0;
                ta SubTy       type SubTy;
                ta Ty          type Ty;
                fn func()      fn func()
                me method()    fn method(&self)
                fn subfunc()   fn subfunc()
                me submethod() fn submethod(&self)
            "#]],
        );
    }

    #[test]
    fn completes_type_alias() {
        check(
            r#"
struct S;
impl S { fn foo() {} }
type T = S;
impl T { fn bar() {} }

fn main() { T::<|>; }
"#,
            expect![[r#"
                fn bar() fn bar()
                fn foo() fn foo()
            "#]],
        );
    }

    #[test]
    fn completes_qualified_macros() {
        check(
            r#"
#[macro_export]
macro_rules! foo { () => {} }

fn main() { let _ = crate::<|> }
        "#,
            expect![[r##"
                ma foo!(…) #[macro_export]
                macro_rules! foo
                fn main()  fn main()
            "##]],
        );
    }

    #[test]
    fn test_super_super_completion() {
        check(
            r#"
mod a {
    const A: usize = 0;
    mod b {
        const B: usize = 0;
        mod c { use super::super::<|> }
    }
}
"#,
            expect![[r#"
                ct A
                md b
            "#]],
        );
    }

    #[test]
    fn completes_reexported_items_under_correct_name() {
        check(
            r#"
fn foo() { self::m::<|> }

mod m {
    pub use super::p::wrong_fn as right_fn;
    pub use super::p::WRONG_CONST as RIGHT_CONST;
    pub use super::p::WrongType as RightType;
}
mod p {
    fn wrong_fn() {}
    const WRONG_CONST: u32 = 1;
    struct WrongType {};
}
"#,
            expect![[r#"
                ct RIGHT_CONST
                st RightType
                fn right_fn()  fn wrong_fn()
            "#]],
        );

        check_edit(
            "RightType",
            r#"
fn foo() { self::m::<|> }

mod m {
    pub use super::p::wrong_fn as right_fn;
    pub use super::p::WRONG_CONST as RIGHT_CONST;
    pub use super::p::WrongType as RightType;
}
mod p {
    fn wrong_fn() {}
    const WRONG_CONST: u32 = 1;
    struct WrongType {};
}
"#,
            r#"
fn foo() { self::m::RightType }

mod m {
    pub use super::p::wrong_fn as right_fn;
    pub use super::p::WRONG_CONST as RIGHT_CONST;
    pub use super::p::WrongType as RightType;
}
mod p {
    fn wrong_fn() {}
    const WRONG_CONST: u32 = 1;
    struct WrongType {};
}
"#,
        );
    }

    #[test]
    fn completes_in_simple_macro_call() {
        check(
            r#"
macro_rules! m { ($e:expr) => { $e } }
fn main() { m!(self::f<|>); }
fn foo() {}
"#,
            expect![[r#"
                fn foo()  fn foo()
                fn main() fn main()
            "#]],
        );
    }

    #[test]
    fn function_mod_share_name() {
        check(
            r#"
fn foo() { self::m::<|> }

mod m {
    pub mod z {}
    pub fn z() {}
}
"#,
            expect![[r#"
                md z
                fn z() pub fn z()
            "#]],
        );
    }

    #[test]
    fn completes_hashmap_new() {
        check(
            r#"
struct RandomState;
struct HashMap<K, V, S = RandomState> {}

impl<K, V> HashMap<K, V, RandomState> {
    pub fn new() -> HashMap<K, V, RandomState> { }
}
fn foo() {
    HashMap::<|>
}
"#,
            expect![[r#"
                fn new() pub fn new() -> HashMap<K, V, RandomState>
            "#]],
        );
    }

    #[test]
    fn dont_complete_attr() {
        check(
            r#"
mod foo { pub struct Foo; }
#[foo::<|>]
fn f() {}
"#,
            expect![[""]],
        );
    }
}