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