]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/find_path.rs
Merge #8814
[rust.git] / crates / hir_def / src / find_path.rs
1 //! An algorithm to find a path to refer to a certain item.
2
3 use std::iter;
4
5 use hir_expand::name::{known, AsName, Name};
6 use rustc_hash::FxHashSet;
7
8 use crate::{
9     db::DefDatabase,
10     item_scope::ItemInNs,
11     nameres::DefMap,
12     path::{ModPath, PathKind},
13     visibility::Visibility,
14     ModuleDefId, ModuleId,
15 };
16
17 /// Find a path that can be used to refer to a certain item. This can depend on
18 /// *from where* you're referring to the item, hence the `from` parameter.
19 pub fn find_path(db: &dyn DefDatabase, item: ItemInNs, from: ModuleId) -> Option<ModPath> {
20     let _p = profile::span("find_path");
21     let mut visited_modules = FxHashSet::default();
22     find_path_inner(db, item, from, MAX_PATH_LEN, None, &mut visited_modules)
23 }
24
25 pub fn find_path_prefixed(
26     db: &dyn DefDatabase,
27     item: ItemInNs,
28     from: ModuleId,
29     prefix_kind: PrefixKind,
30 ) -> Option<ModPath> {
31     let _p = profile::span("find_path_prefixed");
32     let mut visited_modules = FxHashSet::default();
33     find_path_inner(db, item, from, MAX_PATH_LEN, Some(prefix_kind), &mut visited_modules)
34 }
35
36 const MAX_PATH_LEN: usize = 15;
37
38 impl ModPath {
39     fn starts_with_std(&self) -> bool {
40         self.segments().first() == Some(&known::std)
41     }
42
43     // When std library is present, paths starting with `std::`
44     // should be preferred over paths starting with `core::` and `alloc::`
45     fn can_start_with_std(&self) -> bool {
46         let first_segment = self.segments().first();
47         first_segment == Some(&known::alloc) || first_segment == Some(&known::core)
48     }
49 }
50
51 fn check_self_super(def_map: &DefMap, item: ItemInNs, from: ModuleId) -> Option<ModPath> {
52     if item == ItemInNs::Types(from.into()) {
53         // - if the item is the module we're in, use `self`
54         Some(ModPath::from_segments(PathKind::Super(0), Vec::new()))
55     } else if let Some(parent_id) = def_map[from.local_id].parent {
56         // - if the item is the parent module, use `super` (this is not used recursively, since `super::super` is ugly)
57         let parent_id = def_map.module_id(parent_id);
58         if item == ItemInNs::Types(ModuleDefId::ModuleId(parent_id)) {
59             Some(ModPath::from_segments(PathKind::Super(1), Vec::new()))
60         } else {
61             None
62         }
63     } else {
64         None
65     }
66 }
67
68 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
69 pub enum PrefixKind {
70     /// Causes paths to always start with either `self`, `super`, `crate` or a crate-name.
71     /// This is the same as plain, just that paths will start with `self` iprepended f the path
72     /// starts with an identifier that is not a crate.
73     BySelf,
74     /// Causes paths to ignore imports in the local module.
75     Plain,
76     /// Causes paths to start with `crate` where applicable, effectively forcing paths to be absolute.
77     ByCrate,
78 }
79
80 impl PrefixKind {
81     #[inline]
82     fn prefix(self) -> PathKind {
83         match self {
84             PrefixKind::BySelf => PathKind::Super(0),
85             PrefixKind::Plain => PathKind::Plain,
86             PrefixKind::ByCrate => PathKind::Crate,
87         }
88     }
89
90     #[inline]
91     fn is_absolute(&self) -> bool {
92         self == &PrefixKind::ByCrate
93     }
94 }
95
96 fn find_path_inner(
97     db: &dyn DefDatabase,
98     item: ItemInNs,
99     from: ModuleId,
100     max_len: usize,
101     mut prefixed: Option<PrefixKind>,
102     visited_modules: &mut FxHashSet<ModuleId>,
103 ) -> Option<ModPath> {
104     if max_len == 0 {
105         return None;
106     }
107
108     // Base cases:
109
110     // - if the item is already in scope, return the name under which it is
111     let def_map = from.def_map(db);
112     let scope_name = def_map.with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| {
113         def_map[local_id].scope.name_of(item).map(|(name, _)| name.clone())
114     });
115     if prefixed.is_none() && scope_name.is_some() {
116         return scope_name
117             .map(|scope_name| ModPath::from_segments(PathKind::Plain, vec![scope_name]));
118     }
119
120     // - if the item is the crate root, return `crate`
121     let root = def_map.crate_root(db);
122     if item == ItemInNs::Types(ModuleDefId::ModuleId(root)) {
123         return Some(ModPath::from_segments(PathKind::Crate, Vec::new()));
124     }
125
126     if prefixed.filter(PrefixKind::is_absolute).is_none() {
127         if let modpath @ Some(_) = check_self_super(&def_map, item, from) {
128             return modpath;
129         }
130     }
131
132     // - if the item is the crate root of a dependency crate, return the name from the extern prelude
133     let root_def_map = root.def_map(db);
134     for (name, def_id) in root_def_map.extern_prelude() {
135         if item == ItemInNs::Types(*def_id) {
136             let name = scope_name.unwrap_or_else(|| name.clone());
137
138             let name_already_occupied_in_type_ns = def_map
139                 .with_ancestor_maps(db, from.local_id, &mut |def_map, local_id| {
140                     def_map[local_id].scope.get(&name).take_types().filter(|&id| id != *def_id)
141                 })
142                 .is_some();
143             return Some(ModPath::from_segments(
144                 if name_already_occupied_in_type_ns { PathKind::Abs } else { PathKind::Plain },
145                 vec![name],
146             ));
147         }
148     }
149
150     // - if the item is in the prelude, return the name from there
151     if let Some(prelude_module) = root_def_map.prelude() {
152         // Preludes in block DefMaps are ignored, only the crate DefMap is searched
153         let prelude_def_map = prelude_module.def_map(db);
154         let prelude_scope: &crate::item_scope::ItemScope =
155             &prelude_def_map[prelude_module.local_id].scope;
156         if let Some((name, vis)) = prelude_scope.name_of(item) {
157             if vis.is_visible_from(db, from) {
158                 return Some(ModPath::from_segments(PathKind::Plain, vec![name.clone()]));
159             }
160         }
161     }
162
163     // - if the item is a builtin, it's in scope
164     if let ItemInNs::Types(ModuleDefId::BuiltinType(builtin)) = item {
165         return Some(ModPath::from_segments(PathKind::Plain, vec![builtin.as_name()]));
166     }
167
168     // Recursive case:
169     // - if the item is an enum variant, refer to it via the enum
170     if let Some(ModuleDefId::EnumVariantId(variant)) = item.as_module_def_id() {
171         if let Some(mut path) = find_path(db, ItemInNs::Types(variant.parent.into()), from) {
172             let data = db.enum_data(variant.parent);
173             path.push_segment(data.variants[variant.local_id].name.clone());
174             return Some(path);
175         }
176         // If this doesn't work, it seems we have no way of referring to the
177         // enum; that's very weird, but there might still be a reexport of the
178         // variant somewhere
179     }
180
181     // - otherwise, look for modules containing (reexporting) it and import it from one of those
182
183     let crate_root = def_map.crate_root(db);
184     let crate_attrs = db.attrs(crate_root.into());
185     let prefer_no_std = crate_attrs.by_key("no_std").exists();
186     let mut best_path = None;
187     let mut best_path_len = max_len;
188
189     if item.krate(db) == Some(from.krate) {
190         // Item was defined in the same crate that wants to import it. It cannot be found in any
191         // dependency in this case.
192         for (module_id, name) in find_local_import_locations(db, item, from) {
193             if !visited_modules.insert(module_id) {
194                 cov_mark::hit!(recursive_imports);
195                 continue;
196             }
197             if let Some(mut path) = find_path_inner(
198                 db,
199                 ItemInNs::Types(ModuleDefId::ModuleId(module_id)),
200                 from,
201                 best_path_len - 1,
202                 prefixed,
203                 visited_modules,
204             ) {
205                 path.push_segment(name);
206
207                 let new_path = if let Some(best_path) = best_path {
208                     select_best_path(best_path, path, prefer_no_std)
209                 } else {
210                     path
211                 };
212                 best_path_len = new_path.len();
213                 best_path = Some(new_path);
214             }
215         }
216     } else {
217         // Item was defined in some upstream crate. This means that it must be exported from one,
218         // too (unless we can't name it at all). It could *also* be (re)exported by the same crate
219         // that wants to import it here, but we always prefer to use the external path here.
220
221         let crate_graph = db.crate_graph();
222         let extern_paths = crate_graph[from.krate].dependencies.iter().filter_map(|dep| {
223             let import_map = db.import_map(dep.crate_id);
224             import_map.import_info_for(item).and_then(|info| {
225                 // Determine best path for containing module and append last segment from `info`.
226                 let mut path = find_path_inner(
227                     db,
228                     ItemInNs::Types(ModuleDefId::ModuleId(info.container)),
229                     from,
230                     best_path_len - 1,
231                     prefixed,
232                     visited_modules,
233                 )?;
234                 cov_mark::hit!(partially_imported);
235                 path.push_segment(info.path.segments.last().unwrap().clone());
236                 Some(path)
237             })
238         });
239
240         for path in extern_paths {
241             let new_path = if let Some(best_path) = best_path {
242                 select_best_path(best_path, path, prefer_no_std)
243             } else {
244                 path
245             };
246             best_path = Some(new_path);
247         }
248     }
249
250     // If the item is declared inside a block expression, don't use a prefix, as we don't handle
251     // that correctly (FIXME).
252     if let Some(item_module) = item.as_module_def_id().and_then(|did| did.module(db)) {
253         if item_module.def_map(db).block_id().is_some() && prefixed.is_some() {
254             cov_mark::hit!(prefixed_in_block_expression);
255             prefixed = Some(PrefixKind::Plain);
256         }
257     }
258
259     if let Some(prefix) = prefixed.map(PrefixKind::prefix) {
260         best_path.or_else(|| {
261             scope_name.map(|scope_name| ModPath::from_segments(prefix, vec![scope_name]))
262         })
263     } else {
264         best_path
265     }
266 }
267
268 fn select_best_path(old_path: ModPath, new_path: ModPath, prefer_no_std: bool) -> ModPath {
269     if old_path.starts_with_std() && new_path.can_start_with_std() {
270         if prefer_no_std {
271             cov_mark::hit!(prefer_no_std_paths);
272             new_path
273         } else {
274             cov_mark::hit!(prefer_std_paths);
275             old_path
276         }
277     } else if new_path.starts_with_std() && old_path.can_start_with_std() {
278         if prefer_no_std {
279             cov_mark::hit!(prefer_no_std_paths);
280             old_path
281         } else {
282             cov_mark::hit!(prefer_std_paths);
283             new_path
284         }
285     } else if new_path.len() < old_path.len() {
286         new_path
287     } else {
288         old_path
289     }
290 }
291
292 /// Finds locations in `from.krate` from which `item` can be imported by `from`.
293 fn find_local_import_locations(
294     db: &dyn DefDatabase,
295     item: ItemInNs,
296     from: ModuleId,
297 ) -> Vec<(ModuleId, Name)> {
298     let _p = profile::span("find_local_import_locations");
299
300     // `from` can import anything below `from` with visibility of at least `from`, and anything
301     // above `from` with any visibility. That means we do not need to descend into private siblings
302     // of `from` (and similar).
303
304     let def_map = from.def_map(db);
305
306     // Compute the initial worklist. We start with all direct child modules of `from` as well as all
307     // of its (recursive) parent modules.
308     let data = &def_map[from.local_id];
309     let mut worklist =
310         data.children.values().map(|child| def_map.module_id(*child)).collect::<Vec<_>>();
311     // FIXME: do we need to traverse out of block expressions here?
312     for ancestor in iter::successors(from.containing_module(db), |m| m.containing_module(db)) {
313         worklist.push(ancestor);
314     }
315
316     let def_map = def_map.crate_root(db).def_map(db);
317
318     let mut seen: FxHashSet<_> = FxHashSet::default();
319
320     let mut locations = Vec::new();
321     while let Some(module) = worklist.pop() {
322         if !seen.insert(module) {
323             continue; // already processed this module
324         }
325
326         let ext_def_map;
327         let data = if module.krate == from.krate {
328             if module.block.is_some() {
329                 // Re-query the block's DefMap
330                 ext_def_map = module.def_map(db);
331                 &ext_def_map[module.local_id]
332             } else {
333                 // Reuse the root DefMap
334                 &def_map[module.local_id]
335             }
336         } else {
337             // The crate might reexport a module defined in another crate.
338             ext_def_map = module.def_map(db);
339             &ext_def_map[module.local_id]
340         };
341
342         if let Some((name, vis)) = data.scope.name_of(item) {
343             if vis.is_visible_from(db, from) {
344                 let is_private = if let Visibility::Module(private_to) = vis {
345                     private_to.local_id == module.local_id
346                 } else {
347                     false
348                 };
349                 let is_original_def = if let Some(module_def_id) = item.as_module_def_id() {
350                     data.scope.declarations().any(|it| it == module_def_id)
351                 } else {
352                     false
353                 };
354
355                 // Ignore private imports. these could be used if we are
356                 // in a submodule of this module, but that's usually not
357                 // what the user wants; and if this module can import
358                 // the item and we're a submodule of it, so can we.
359                 // Also this keeps the cached data smaller.
360                 if !is_private || is_original_def {
361                     locations.push((module, name.clone()));
362                 }
363             }
364         }
365
366         // Descend into all modules visible from `from`.
367         for (_, per_ns) in data.scope.entries() {
368             if let Some((ModuleDefId::ModuleId(module), vis)) = per_ns.take_types_vis() {
369                 if vis.is_visible_from(db, from) {
370                     worklist.push(module);
371                 }
372             }
373         }
374     }
375
376     locations
377 }
378
379 #[cfg(test)]
380 mod tests {
381     use base_db::fixture::WithFixture;
382     use hir_expand::hygiene::Hygiene;
383     use syntax::ast::AstNode;
384
385     use crate::test_db::TestDB;
386
387     use super::*;
388
389     /// `code` needs to contain a cursor marker; checks that `find_path` for the
390     /// item the `path` refers to returns that same path when called from the
391     /// module the cursor is in.
392     fn check_found_path_(ra_fixture: &str, path: &str, prefix_kind: Option<PrefixKind>) {
393         let (db, pos) = TestDB::with_position(ra_fixture);
394         let module = db.module_at_position(pos);
395         let parsed_path_file = syntax::SourceFile::parse(&format!("use {};", path));
396         let ast_path =
397             parsed_path_file.syntax_node().descendants().find_map(syntax::ast::Path::cast).unwrap();
398         let mod_path = ModPath::from_src(&db, ast_path, &Hygiene::new_unhygienic()).unwrap();
399
400         let def_map = module.def_map(&db);
401         let resolved = def_map
402             .resolve_path(
403                 &db,
404                 module.local_id,
405                 &mod_path,
406                 crate::item_scope::BuiltinShadowMode::Module,
407             )
408             .0
409             .take_types()
410             .unwrap();
411
412         let mut visited_modules = FxHashSet::default();
413         let found_path = find_path_inner(
414             &db,
415             ItemInNs::Types(resolved),
416             module,
417             MAX_PATH_LEN,
418             prefix_kind,
419             &mut visited_modules,
420         );
421         assert_eq!(found_path, Some(mod_path), "{:?}", prefix_kind);
422     }
423
424     fn check_found_path(
425         ra_fixture: &str,
426         unprefixed: &str,
427         prefixed: &str,
428         absolute: &str,
429         self_prefixed: &str,
430     ) {
431         check_found_path_(ra_fixture, unprefixed, None);
432         check_found_path_(ra_fixture, prefixed, Some(PrefixKind::Plain));
433         check_found_path_(ra_fixture, absolute, Some(PrefixKind::ByCrate));
434         check_found_path_(ra_fixture, self_prefixed, Some(PrefixKind::BySelf));
435     }
436
437     #[test]
438     fn same_module() {
439         check_found_path(
440             r#"
441 struct S;
442 $0
443         "#,
444             "S",
445             "S",
446             "crate::S",
447             "self::S",
448         );
449     }
450
451     #[test]
452     fn enum_variant() {
453         check_found_path(
454             r#"
455 enum E { A }
456 $0
457         "#,
458             "E::A",
459             "E::A",
460             "E::A",
461             "E::A",
462         );
463     }
464
465     #[test]
466     fn sub_module() {
467         check_found_path(
468             r#"
469 mod foo {
470     pub struct S;
471 }
472 $0
473         "#,
474             "foo::S",
475             "foo::S",
476             "crate::foo::S",
477             "self::foo::S",
478         );
479     }
480
481     #[test]
482     fn super_module() {
483         check_found_path(
484             r#"
485 //- /main.rs
486 mod foo;
487 //- /foo.rs
488 mod bar;
489 struct S;
490 //- /foo/bar.rs
491 $0
492         "#,
493             "super::S",
494             "super::S",
495             "crate::foo::S",
496             "super::S",
497         );
498     }
499
500     #[test]
501     fn self_module() {
502         check_found_path(
503             r#"
504 //- /main.rs
505 mod foo;
506 //- /foo.rs
507 $0
508         "#,
509             "self",
510             "self",
511             "crate::foo",
512             "self",
513         );
514     }
515
516     #[test]
517     fn crate_root() {
518         check_found_path(
519             r#"
520 //- /main.rs
521 mod foo;
522 //- /foo.rs
523 $0
524         "#,
525             "crate",
526             "crate",
527             "crate",
528             "crate",
529         );
530     }
531
532     #[test]
533     fn same_crate() {
534         check_found_path(
535             r#"
536 //- /main.rs
537 mod foo;
538 struct S;
539 //- /foo.rs
540 $0
541         "#,
542             "crate::S",
543             "crate::S",
544             "crate::S",
545             "crate::S",
546         );
547     }
548
549     #[test]
550     fn different_crate() {
551         check_found_path(
552             r#"
553 //- /main.rs crate:main deps:std
554 $0
555 //- /std.rs crate:std
556 pub struct S;
557         "#,
558             "std::S",
559             "std::S",
560             "std::S",
561             "std::S",
562         );
563     }
564
565     #[test]
566     fn different_crate_renamed() {
567         check_found_path(
568             r#"
569 //- /main.rs crate:main deps:std
570 extern crate std as std_renamed;
571 $0
572 //- /std.rs crate:std
573 pub struct S;
574         "#,
575             "std_renamed::S",
576             "std_renamed::S",
577             "std_renamed::S",
578             "std_renamed::S",
579         );
580     }
581
582     #[test]
583     fn partially_imported() {
584         cov_mark::check!(partially_imported);
585         // Tests that short paths are used even for external items, when parts of the path are
586         // already in scope.
587         check_found_path(
588             r#"
589 //- /main.rs crate:main deps:syntax
590
591 use syntax::ast;
592 $0
593
594 //- /lib.rs crate:syntax
595 pub mod ast {
596     pub enum ModuleItem {
597         A, B, C,
598     }
599 }
600         "#,
601             "ast::ModuleItem",
602             "syntax::ast::ModuleItem",
603             "syntax::ast::ModuleItem",
604             "syntax::ast::ModuleItem",
605         );
606
607         check_found_path(
608             r#"
609 //- /main.rs crate:main deps:syntax
610 $0
611
612 //- /lib.rs crate:syntax
613 pub mod ast {
614     pub enum ModuleItem {
615         A, B, C,
616     }
617 }
618         "#,
619             "syntax::ast::ModuleItem",
620             "syntax::ast::ModuleItem",
621             "syntax::ast::ModuleItem",
622             "syntax::ast::ModuleItem",
623         );
624     }
625
626     #[test]
627     fn same_crate_reexport() {
628         check_found_path(
629             r#"
630 mod bar {
631     mod foo { pub(super) struct S; }
632     pub(crate) use foo::*;
633 }
634 $0
635         "#,
636             "bar::S",
637             "bar::S",
638             "crate::bar::S",
639             "self::bar::S",
640         );
641     }
642
643     #[test]
644     fn same_crate_reexport_rename() {
645         check_found_path(
646             r#"
647 mod bar {
648     mod foo { pub(super) struct S; }
649     pub(crate) use foo::S as U;
650 }
651 $0
652         "#,
653             "bar::U",
654             "bar::U",
655             "crate::bar::U",
656             "self::bar::U",
657         );
658     }
659
660     #[test]
661     fn different_crate_reexport() {
662         check_found_path(
663             r#"
664 //- /main.rs crate:main deps:std
665 $0
666 //- /std.rs crate:std deps:core
667 pub use core::S;
668 //- /core.rs crate:core
669 pub struct S;
670         "#,
671             "std::S",
672             "std::S",
673             "std::S",
674             "std::S",
675         );
676     }
677
678     #[test]
679     fn prelude() {
680         check_found_path(
681             r#"
682 //- /main.rs crate:main deps:std
683 $0
684 //- /std.rs crate:std
685 pub mod prelude { pub struct S; }
686 #[prelude_import]
687 pub use prelude::*;
688         "#,
689             "S",
690             "S",
691             "S",
692             "S",
693         );
694     }
695
696     #[test]
697     fn enum_variant_from_prelude() {
698         let code = r#"
699 //- /main.rs crate:main deps:std
700 $0
701 //- /std.rs crate:std
702 pub mod prelude {
703     pub enum Option<T> { Some(T), None }
704     pub use Option::*;
705 }
706 #[prelude_import]
707 pub use prelude::*;
708         "#;
709         check_found_path(code, "None", "None", "None", "None");
710         check_found_path(code, "Some", "Some", "Some", "Some");
711     }
712
713     #[test]
714     fn shortest_path() {
715         check_found_path(
716             r#"
717 //- /main.rs
718 pub mod foo;
719 pub mod baz;
720 struct S;
721 $0
722 //- /foo.rs
723 pub mod bar { pub struct S; }
724 //- /baz.rs
725 pub use crate::foo::bar::S;
726         "#,
727             "baz::S",
728             "baz::S",
729             "crate::baz::S",
730             "self::baz::S",
731         );
732     }
733
734     #[test]
735     fn discount_private_imports() {
736         check_found_path(
737             r#"
738 //- /main.rs
739 mod foo;
740 pub mod bar { pub struct S; }
741 use bar::S;
742 //- /foo.rs
743 $0
744         "#,
745             // crate::S would be shorter, but using private imports seems wrong
746             "crate::bar::S",
747             "crate::bar::S",
748             "crate::bar::S",
749             "crate::bar::S",
750         );
751     }
752
753     #[test]
754     fn import_cycle() {
755         check_found_path(
756             r#"
757 //- /main.rs
758 pub mod foo;
759 pub mod bar;
760 pub mod baz;
761 //- /bar.rs
762 $0
763 //- /foo.rs
764 pub use super::baz;
765 pub struct S;
766 //- /baz.rs
767 pub use super::foo;
768         "#,
769             "crate::foo::S",
770             "crate::foo::S",
771             "crate::foo::S",
772             "crate::foo::S",
773         );
774     }
775
776     #[test]
777     fn prefer_std_paths_over_alloc() {
778         cov_mark::check!(prefer_std_paths);
779         check_found_path(
780             r#"
781 //- /main.rs crate:main deps:alloc,std
782 $0
783
784 //- /std.rs crate:std deps:alloc
785 pub mod sync {
786     pub use alloc::sync::Arc;
787 }
788
789 //- /zzz.rs crate:alloc
790 pub mod sync {
791     pub struct Arc;
792 }
793         "#,
794             "std::sync::Arc",
795             "std::sync::Arc",
796             "std::sync::Arc",
797             "std::sync::Arc",
798         );
799     }
800
801     #[test]
802     fn prefer_core_paths_over_std() {
803         cov_mark::check!(prefer_no_std_paths);
804         check_found_path(
805             r#"
806 //- /main.rs crate:main deps:core,std
807 #![no_std]
808
809 $0
810
811 //- /std.rs crate:std deps:core
812
813 pub mod fmt {
814     pub use core::fmt::Error;
815 }
816
817 //- /zzz.rs crate:core
818
819 pub mod fmt {
820     pub struct Error;
821 }
822         "#,
823             "core::fmt::Error",
824             "core::fmt::Error",
825             "core::fmt::Error",
826             "core::fmt::Error",
827         );
828     }
829
830     #[test]
831     fn prefer_alloc_paths_over_std() {
832         check_found_path(
833             r#"
834 //- /main.rs crate:main deps:alloc,std
835 #![no_std]
836
837 $0
838
839 //- /std.rs crate:std deps:alloc
840
841 pub mod sync {
842     pub use alloc::sync::Arc;
843 }
844
845 //- /zzz.rs crate:alloc
846
847 pub mod sync {
848     pub struct Arc;
849 }
850             "#,
851             "alloc::sync::Arc",
852             "alloc::sync::Arc",
853             "alloc::sync::Arc",
854             "alloc::sync::Arc",
855         );
856     }
857
858     #[test]
859     fn prefer_shorter_paths_if_not_alloc() {
860         check_found_path(
861             r#"
862 //- /main.rs crate:main deps:megaalloc,std
863 $0
864
865 //- /std.rs crate:std deps:megaalloc
866 pub mod sync {
867     pub use megaalloc::sync::Arc;
868 }
869
870 //- /zzz.rs crate:megaalloc
871 pub struct Arc;
872             "#,
873             "megaalloc::Arc",
874             "megaalloc::Arc",
875             "megaalloc::Arc",
876             "megaalloc::Arc",
877         );
878     }
879
880     #[test]
881     fn builtins_are_in_scope() {
882         let code = r#"
883 $0
884
885 pub mod primitive {
886     pub use u8;
887 }
888         "#;
889         check_found_path(code, "u8", "u8", "u8", "u8");
890         check_found_path(code, "u16", "u16", "u16", "u16");
891     }
892
893     #[test]
894     fn inner_items() {
895         check_found_path(
896             r#"
897 fn main() {
898     struct Inner {}
899     $0
900 }
901         "#,
902             "Inner",
903             "Inner",
904             "Inner",
905             "Inner",
906         );
907     }
908
909     #[test]
910     fn inner_items_from_outer_scope() {
911         check_found_path(
912             r#"
913 fn main() {
914     struct Struct {}
915     {
916         $0
917     }
918 }
919         "#,
920             "Struct",
921             "Struct",
922             "Struct",
923             "Struct",
924         );
925     }
926
927     #[test]
928     fn inner_items_from_inner_module() {
929         cov_mark::check!(prefixed_in_block_expression);
930         check_found_path(
931             r#"
932 fn main() {
933     mod module {
934         struct Struct {}
935     }
936     {
937         $0
938     }
939 }
940         "#,
941             "module::Struct",
942             "module::Struct",
943             "module::Struct",
944             "module::Struct",
945         );
946     }
947
948     #[test]
949     fn outer_items_with_inner_items_present() {
950         check_found_path(
951             r#"
952 mod module {
953     pub struct CompleteMe;
954 }
955
956 fn main() {
957     fn inner() {}
958     $0
959 }
960             "#,
961             // FIXME: these could use fewer/better prefixes
962             "module::CompleteMe",
963             "crate::module::CompleteMe",
964             "crate::module::CompleteMe",
965             "crate::module::CompleteMe",
966         )
967     }
968
969     #[test]
970     fn from_inside_module() {
971         // This worked correctly, but the test suite logic was broken.
972         cov_mark::check!(submodule_in_testdb);
973         check_found_path(
974             r#"
975 mod baz {
976     pub struct Foo {}
977 }
978
979 mod bar {
980     fn bar() {
981         $0
982     }
983 }
984             "#,
985             "crate::baz::Foo",
986             "crate::baz::Foo",
987             "crate::baz::Foo",
988             "crate::baz::Foo",
989         )
990     }
991
992     #[test]
993     fn from_inside_module_with_inner_items() {
994         check_found_path(
995             r#"
996 mod baz {
997     pub struct Foo {}
998 }
999
1000 mod bar {
1001     fn bar() {
1002         fn inner() {}
1003         $0
1004     }
1005 }
1006             "#,
1007             "crate::baz::Foo",
1008             "crate::baz::Foo",
1009             "crate::baz::Foo",
1010             "crate::baz::Foo",
1011         )
1012     }
1013
1014     #[test]
1015     fn recursive_pub_mod_reexport() {
1016         cov_mark::check!(recursive_imports);
1017         check_found_path(
1018             r#"
1019 fn main() {
1020     let _ = 22_i32.as_name$0();
1021 }
1022
1023 pub mod name {
1024     pub trait AsName {
1025         fn as_name(&self) -> String;
1026     }
1027     impl AsName for i32 {
1028         fn as_name(&self) -> String {
1029             format!("Name: {}", self)
1030         }
1031     }
1032     pub use crate::name;
1033 }
1034 "#,
1035             "name::AsName",
1036             "name::AsName",
1037             "crate::name::AsName",
1038             "self::name::AsName",
1039         );
1040     }
1041
1042     #[test]
1043     fn extern_crate() {
1044         check_found_path(
1045             r#"
1046 //- /main.rs crate:main deps:dep
1047 $0
1048 //- /dep.rs crate:dep
1049 "#,
1050             "dep",
1051             "dep",
1052             "dep",
1053             "dep",
1054         );
1055
1056         check_found_path(
1057             r#"
1058 //- /main.rs crate:main deps:dep
1059 fn f() {
1060     fn inner() {}
1061     $0
1062 }
1063 //- /dep.rs crate:dep
1064 "#,
1065             "dep",
1066             "dep",
1067             "dep",
1068             "dep",
1069         );
1070     }
1071
1072     #[test]
1073     fn prelude_with_inner_items() {
1074         check_found_path(
1075             r#"
1076 //- /main.rs crate:main deps:std
1077 fn f() {
1078     fn inner() {}
1079     $0
1080 }
1081 //- /std.rs crate:std
1082 pub mod prelude {
1083     pub enum Option { None }
1084     pub use Option::*;
1085 }
1086 #[prelude_import]
1087 pub use prelude::*;
1088         "#,
1089             "None",
1090             "None",
1091             "None",
1092             "None",
1093         );
1094     }
1095 }