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