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