]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/find_path.rs
Implement per-edition preludes
[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 {
686     pub mod rust_2018 {
687         pub struct S;
688     }
689 }
690         "#,
691             "S",
692             "S",
693             "S",
694             "S",
695         );
696     }
697
698     #[test]
699     fn enum_variant_from_prelude() {
700         let code = r#"
701 //- /main.rs crate:main deps:std
702 $0
703 //- /std.rs crate:std
704 pub mod prelude {
705     pub mod rust_2018 {
706         pub enum Option<T> { Some(T), None }
707         pub use Option::*;
708     }
709 }
710         "#;
711         check_found_path(code, "None", "None", "None", "None");
712         check_found_path(code, "Some", "Some", "Some", "Some");
713     }
714
715     #[test]
716     fn shortest_path() {
717         check_found_path(
718             r#"
719 //- /main.rs
720 pub mod foo;
721 pub mod baz;
722 struct S;
723 $0
724 //- /foo.rs
725 pub mod bar { pub struct S; }
726 //- /baz.rs
727 pub use crate::foo::bar::S;
728         "#,
729             "baz::S",
730             "baz::S",
731             "crate::baz::S",
732             "self::baz::S",
733         );
734     }
735
736     #[test]
737     fn discount_private_imports() {
738         check_found_path(
739             r#"
740 //- /main.rs
741 mod foo;
742 pub mod bar { pub struct S; }
743 use bar::S;
744 //- /foo.rs
745 $0
746         "#,
747             // crate::S would be shorter, but using private imports seems wrong
748             "crate::bar::S",
749             "crate::bar::S",
750             "crate::bar::S",
751             "crate::bar::S",
752         );
753     }
754
755     #[test]
756     fn import_cycle() {
757         check_found_path(
758             r#"
759 //- /main.rs
760 pub mod foo;
761 pub mod bar;
762 pub mod baz;
763 //- /bar.rs
764 $0
765 //- /foo.rs
766 pub use super::baz;
767 pub struct S;
768 //- /baz.rs
769 pub use super::foo;
770         "#,
771             "crate::foo::S",
772             "crate::foo::S",
773             "crate::foo::S",
774             "crate::foo::S",
775         );
776     }
777
778     #[test]
779     fn prefer_std_paths_over_alloc() {
780         cov_mark::check!(prefer_std_paths);
781         check_found_path(
782             r#"
783 //- /main.rs crate:main deps:alloc,std
784 $0
785
786 //- /std.rs crate:std deps:alloc
787 pub mod sync {
788     pub use alloc::sync::Arc;
789 }
790
791 //- /zzz.rs crate:alloc
792 pub mod sync {
793     pub struct Arc;
794 }
795         "#,
796             "std::sync::Arc",
797             "std::sync::Arc",
798             "std::sync::Arc",
799             "std::sync::Arc",
800         );
801     }
802
803     #[test]
804     fn prefer_core_paths_over_std() {
805         cov_mark::check!(prefer_no_std_paths);
806         check_found_path(
807             r#"
808 //- /main.rs crate:main deps:core,std
809 #![no_std]
810
811 $0
812
813 //- /std.rs crate:std deps:core
814
815 pub mod fmt {
816     pub use core::fmt::Error;
817 }
818
819 //- /zzz.rs crate:core
820
821 pub mod fmt {
822     pub struct Error;
823 }
824         "#,
825             "core::fmt::Error",
826             "core::fmt::Error",
827             "core::fmt::Error",
828             "core::fmt::Error",
829         );
830     }
831
832     #[test]
833     fn prefer_alloc_paths_over_std() {
834         check_found_path(
835             r#"
836 //- /main.rs crate:main deps:alloc,std
837 #![no_std]
838
839 $0
840
841 //- /std.rs crate:std deps:alloc
842
843 pub mod sync {
844     pub use alloc::sync::Arc;
845 }
846
847 //- /zzz.rs crate:alloc
848
849 pub mod sync {
850     pub struct Arc;
851 }
852             "#,
853             "alloc::sync::Arc",
854             "alloc::sync::Arc",
855             "alloc::sync::Arc",
856             "alloc::sync::Arc",
857         );
858     }
859
860     #[test]
861     fn prefer_shorter_paths_if_not_alloc() {
862         check_found_path(
863             r#"
864 //- /main.rs crate:main deps:megaalloc,std
865 $0
866
867 //- /std.rs crate:std deps:megaalloc
868 pub mod sync {
869     pub use megaalloc::sync::Arc;
870 }
871
872 //- /zzz.rs crate:megaalloc
873 pub struct Arc;
874             "#,
875             "megaalloc::Arc",
876             "megaalloc::Arc",
877             "megaalloc::Arc",
878             "megaalloc::Arc",
879         );
880     }
881
882     #[test]
883     fn builtins_are_in_scope() {
884         let code = r#"
885 $0
886
887 pub mod primitive {
888     pub use u8;
889 }
890         "#;
891         check_found_path(code, "u8", "u8", "u8", "u8");
892         check_found_path(code, "u16", "u16", "u16", "u16");
893     }
894
895     #[test]
896     fn inner_items() {
897         check_found_path(
898             r#"
899 fn main() {
900     struct Inner {}
901     $0
902 }
903         "#,
904             "Inner",
905             "Inner",
906             "Inner",
907             "Inner",
908         );
909     }
910
911     #[test]
912     fn inner_items_from_outer_scope() {
913         check_found_path(
914             r#"
915 fn main() {
916     struct Struct {}
917     {
918         $0
919     }
920 }
921         "#,
922             "Struct",
923             "Struct",
924             "Struct",
925             "Struct",
926         );
927     }
928
929     #[test]
930     fn inner_items_from_inner_module() {
931         cov_mark::check!(prefixed_in_block_expression);
932         check_found_path(
933             r#"
934 fn main() {
935     mod module {
936         struct Struct {}
937     }
938     {
939         $0
940     }
941 }
942         "#,
943             "module::Struct",
944             "module::Struct",
945             "module::Struct",
946             "module::Struct",
947         );
948     }
949
950     #[test]
951     fn outer_items_with_inner_items_present() {
952         check_found_path(
953             r#"
954 mod module {
955     pub struct CompleteMe;
956 }
957
958 fn main() {
959     fn inner() {}
960     $0
961 }
962             "#,
963             // FIXME: these could use fewer/better prefixes
964             "module::CompleteMe",
965             "crate::module::CompleteMe",
966             "crate::module::CompleteMe",
967             "crate::module::CompleteMe",
968         )
969     }
970
971     #[test]
972     fn from_inside_module() {
973         // This worked correctly, but the test suite logic was broken.
974         cov_mark::check!(submodule_in_testdb);
975         check_found_path(
976             r#"
977 mod baz {
978     pub struct Foo {}
979 }
980
981 mod bar {
982     fn bar() {
983         $0
984     }
985 }
986             "#,
987             "crate::baz::Foo",
988             "crate::baz::Foo",
989             "crate::baz::Foo",
990             "crate::baz::Foo",
991         )
992     }
993
994     #[test]
995     fn from_inside_module_with_inner_items() {
996         check_found_path(
997             r#"
998 mod baz {
999     pub struct Foo {}
1000 }
1001
1002 mod bar {
1003     fn bar() {
1004         fn inner() {}
1005         $0
1006     }
1007 }
1008             "#,
1009             "crate::baz::Foo",
1010             "crate::baz::Foo",
1011             "crate::baz::Foo",
1012             "crate::baz::Foo",
1013         )
1014     }
1015
1016     #[test]
1017     fn recursive_pub_mod_reexport() {
1018         cov_mark::check!(recursive_imports);
1019         check_found_path(
1020             r#"
1021 fn main() {
1022     let _ = 22_i32.as_name$0();
1023 }
1024
1025 pub mod name {
1026     pub trait AsName {
1027         fn as_name(&self) -> String;
1028     }
1029     impl AsName for i32 {
1030         fn as_name(&self) -> String {
1031             format!("Name: {}", self)
1032         }
1033     }
1034     pub use crate::name;
1035 }
1036 "#,
1037             "name::AsName",
1038             "name::AsName",
1039             "crate::name::AsName",
1040             "self::name::AsName",
1041         );
1042     }
1043
1044     #[test]
1045     fn extern_crate() {
1046         check_found_path(
1047             r#"
1048 //- /main.rs crate:main deps:dep
1049 $0
1050 //- /dep.rs crate:dep
1051 "#,
1052             "dep",
1053             "dep",
1054             "dep",
1055             "dep",
1056         );
1057
1058         check_found_path(
1059             r#"
1060 //- /main.rs crate:main deps:dep
1061 fn f() {
1062     fn inner() {}
1063     $0
1064 }
1065 //- /dep.rs crate:dep
1066 "#,
1067             "dep",
1068             "dep",
1069             "dep",
1070             "dep",
1071         );
1072     }
1073
1074     #[test]
1075     fn prelude_with_inner_items() {
1076         check_found_path(
1077             r#"
1078 //- /main.rs crate:main deps:std
1079 fn f() {
1080     fn inner() {}
1081     $0
1082 }
1083 //- /std.rs crate:std
1084 pub mod prelude {
1085     pub mod rust_2018 {
1086         pub enum Option { None }
1087         pub use Option::*;
1088     }
1089 }
1090         "#,
1091             "None",
1092             "None",
1093             "None",
1094             "None",
1095         );
1096     }
1097 }