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