]> git.lizzy.rs Git - rust.git/blob - crates/ide_db/src/helpers.rs
internal: retire famous_defs_fixture
[rust.git] / crates / ide_db / src / helpers.rs
1 //! A module with ide helpers for high-level ide features.
2 pub mod import_assets;
3 pub mod insert_use;
4 pub mod merge_imports;
5 pub mod rust_doc;
6 pub mod generated_lints;
7
8 use std::collections::VecDeque;
9
10 use base_db::FileId;
11 use either::Either;
12 use hir::{Crate, Enum, ItemInNs, MacroDef, Module, ModuleDef, Name, ScopeDef, Semantics, Trait};
13 use syntax::ast::{self, make};
14
15 use crate::RootDatabase;
16
17 pub fn item_name(db: &RootDatabase, item: ItemInNs) -> Option<Name> {
18     match item {
19         ItemInNs::Types(module_def_id) => ModuleDef::from(module_def_id).name(db),
20         ItemInNs::Values(module_def_id) => ModuleDef::from(module_def_id).name(db),
21         ItemInNs::Macros(macro_def_id) => MacroDef::from(macro_def_id).name(db),
22     }
23 }
24
25 /// Converts the mod path struct into its ast representation.
26 pub fn mod_path_to_ast(path: &hir::ModPath) -> ast::Path {
27     let _p = profile::span("mod_path_to_ast");
28
29     let mut segments = Vec::new();
30     let mut is_abs = false;
31     match path.kind {
32         hir::PathKind::Plain => {}
33         hir::PathKind::Super(0) => segments.push(make::path_segment_self()),
34         hir::PathKind::Super(n) => segments.extend((0..n).map(|_| make::path_segment_super())),
35         hir::PathKind::DollarCrate(_) | hir::PathKind::Crate => {
36             segments.push(make::path_segment_crate())
37         }
38         hir::PathKind::Abs => is_abs = true,
39     }
40
41     segments.extend(
42         path.segments()
43             .iter()
44             .map(|segment| make::path_segment(make::name_ref(&segment.to_string()))),
45     );
46     make::path_from_segments(segments, is_abs)
47 }
48
49 /// Iterates all `ModuleDef`s and `Impl` blocks of the given file.
50 pub fn visit_file_defs(
51     sema: &Semantics<RootDatabase>,
52     file_id: FileId,
53     cb: &mut dyn FnMut(Either<hir::ModuleDef, hir::Impl>),
54 ) {
55     let db = sema.db;
56     let module = match sema.to_module_def(file_id) {
57         Some(it) => it,
58         None => return,
59     };
60     let mut defs: VecDeque<_> = module.declarations(db).into();
61     while let Some(def) = defs.pop_front() {
62         if let ModuleDef::Module(submodule) = def {
63             if let hir::ModuleSource::Module(_) = submodule.definition_source(db).value {
64                 defs.extend(submodule.declarations(db));
65                 submodule.impl_defs(db).into_iter().for_each(|impl_| cb(Either::Right(impl_)));
66             }
67         }
68         cb(Either::Left(def));
69     }
70     module.impl_defs(db).into_iter().for_each(|impl_| cb(Either::Right(impl_)));
71 }
72
73 /// Helps with finding well-know things inside the standard library. This is
74 /// somewhat similar to the known paths infra inside hir, but it different; We
75 /// want to make sure that IDE specific paths don't become interesting inside
76 /// the compiler itself as well.
77 ///
78 /// Note that, by default, rust-analyzer tests **do not** include core or std
79 /// libraries. If you are writing tests for functionality using [`FamousDefs`],
80 /// you'd want to include [minicore](test_utils::MiniCore) declaration at the
81 /// start of your tests:
82 ///
83 /// ```
84 /// //- minicore: iterator, ord, derive
85 /// ```
86 pub struct FamousDefs<'a, 'b>(pub &'a Semantics<'b, RootDatabase>, pub Option<Crate>);
87
88 #[allow(non_snake_case)]
89 impl FamousDefs<'_, '_> {
90     pub fn std(&self) -> Option<Crate> {
91         self.find_crate("std")
92     }
93
94     pub fn core(&self) -> Option<Crate> {
95         self.find_crate("core")
96     }
97
98     pub fn core_cmp_Ord(&self) -> Option<Trait> {
99         self.find_trait("core:cmp:Ord")
100     }
101
102     pub fn core_convert_From(&self) -> Option<Trait> {
103         self.find_trait("core:convert:From")
104     }
105
106     pub fn core_convert_Into(&self) -> Option<Trait> {
107         self.find_trait("core:convert:Into")
108     }
109
110     pub fn core_option_Option(&self) -> Option<Enum> {
111         self.find_enum("core:option:Option")
112     }
113
114     pub fn core_default_Default(&self) -> Option<Trait> {
115         self.find_trait("core:default:Default")
116     }
117
118     pub fn core_iter_Iterator(&self) -> Option<Trait> {
119         self.find_trait("core:iter:traits:iterator:Iterator")
120     }
121
122     pub fn core_iter(&self) -> Option<Module> {
123         self.find_module("core:iter")
124     }
125
126     pub fn core_ops_Deref(&self) -> Option<Trait> {
127         self.find_trait("core:ops:Deref")
128     }
129
130     fn find_trait(&self, path: &str) -> Option<Trait> {
131         match self.find_def(path)? {
132             hir::ScopeDef::ModuleDef(hir::ModuleDef::Trait(it)) => Some(it),
133             _ => None,
134         }
135     }
136
137     fn find_enum(&self, path: &str) -> Option<Enum> {
138         match self.find_def(path)? {
139             hir::ScopeDef::ModuleDef(hir::ModuleDef::Adt(hir::Adt::Enum(it))) => Some(it),
140             _ => None,
141         }
142     }
143
144     fn find_module(&self, path: &str) -> Option<Module> {
145         match self.find_def(path)? {
146             hir::ScopeDef::ModuleDef(hir::ModuleDef::Module(it)) => Some(it),
147             _ => None,
148         }
149     }
150
151     fn find_crate(&self, name: &str) -> Option<Crate> {
152         let krate = self.1?;
153         let db = self.0.db;
154         let res =
155             krate.dependencies(db).into_iter().find(|dep| dep.name.to_string() == name)?.krate;
156         Some(res)
157     }
158
159     fn find_def(&self, path: &str) -> Option<ScopeDef> {
160         let db = self.0.db;
161         let mut path = path.split(':');
162         let trait_ = path.next_back()?;
163         let std_crate = path.next()?;
164         let std_crate = self.find_crate(std_crate)?;
165         let mut module = std_crate.root_module(db);
166         for segment in path {
167             module = module.children(db).find_map(|child| {
168                 let name = child.name(db)?;
169                 if name.to_string() == segment {
170                     Some(child)
171                 } else {
172                     None
173                 }
174             })?;
175         }
176         let def =
177             module.scope(db, None).into_iter().find(|(name, _def)| name.to_string() == trait_)?.1;
178         Some(def)
179     }
180 }
181
182 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
183 pub struct SnippetCap {
184     _private: (),
185 }
186
187 impl SnippetCap {
188     pub const fn new(allow_snippets: bool) -> Option<SnippetCap> {
189         if allow_snippets {
190             Some(SnippetCap { _private: () })
191         } else {
192             None
193         }
194     }
195 }