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