]> git.lizzy.rs Git - rust.git/blob - crates/ide_db/src/helpers.rs
Generate default lint completions
[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 pub struct FamousDefs<'a, 'b>(pub &'a Semantics<'b, RootDatabase>, pub Option<Crate>);
78
79 #[allow(non_snake_case)]
80 impl FamousDefs<'_, '_> {
81     pub const FIXTURE: &'static str = include_str!("helpers/famous_defs_fixture.rs");
82
83     pub fn std(&self) -> Option<Crate> {
84         self.find_crate("std")
85     }
86
87     pub fn core(&self) -> Option<Crate> {
88         self.find_crate("core")
89     }
90
91     pub fn core_cmp_Ord(&self) -> Option<Trait> {
92         self.find_trait("core:cmp:Ord")
93     }
94
95     pub fn core_convert_From(&self) -> Option<Trait> {
96         self.find_trait("core:convert:From")
97     }
98
99     pub fn core_convert_Into(&self) -> Option<Trait> {
100         self.find_trait("core:convert:Into")
101     }
102
103     pub fn core_option_Option(&self) -> Option<Enum> {
104         self.find_enum("core:option:Option")
105     }
106
107     pub fn core_default_Default(&self) -> Option<Trait> {
108         self.find_trait("core:default:Default")
109     }
110
111     pub fn core_iter_Iterator(&self) -> Option<Trait> {
112         self.find_trait("core:iter:traits:iterator:Iterator")
113     }
114
115     pub fn core_iter(&self) -> Option<Module> {
116         self.find_module("core:iter")
117     }
118
119     pub fn core_ops_Deref(&self) -> Option<Trait> {
120         self.find_trait("core:ops:Deref")
121     }
122
123     fn find_trait(&self, path: &str) -> Option<Trait> {
124         match self.find_def(path)? {
125             hir::ScopeDef::ModuleDef(hir::ModuleDef::Trait(it)) => Some(it),
126             _ => None,
127         }
128     }
129
130     fn find_enum(&self, path: &str) -> Option<Enum> {
131         match self.find_def(path)? {
132             hir::ScopeDef::ModuleDef(hir::ModuleDef::Adt(hir::Adt::Enum(it))) => Some(it),
133             _ => None,
134         }
135     }
136
137     fn find_module(&self, path: &str) -> Option<Module> {
138         match self.find_def(path)? {
139             hir::ScopeDef::ModuleDef(hir::ModuleDef::Module(it)) => Some(it),
140             _ => None,
141         }
142     }
143
144     fn find_crate(&self, name: &str) -> Option<Crate> {
145         let krate = self.1?;
146         let db = self.0.db;
147         let res =
148             krate.dependencies(db).into_iter().find(|dep| dep.name.to_string() == name)?.krate;
149         Some(res)
150     }
151
152     fn find_def(&self, path: &str) -> Option<ScopeDef> {
153         let db = self.0.db;
154         let mut path = path.split(':');
155         let trait_ = path.next_back()?;
156         let std_crate = path.next()?;
157         let std_crate = self.find_crate(std_crate)?;
158         let mut module = std_crate.root_module(db);
159         for segment in path {
160             module = module.children(db).find_map(|child| {
161                 let name = child.name(db)?;
162                 if name.to_string() == segment {
163                     Some(child)
164                 } else {
165                     None
166                 }
167             })?;
168         }
169         let def =
170             module.scope(db, None).into_iter().find(|(name, _def)| name.to_string() == trait_)?.1;
171         Some(def)
172     }
173 }
174
175 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
176 pub struct SnippetCap {
177     _private: (),
178 }
179
180 impl SnippetCap {
181     pub const fn new(allow_snippets: bool) -> Option<SnippetCap> {
182         if allow_snippets {
183             Some(SnippetCap { _private: () })
184         } else {
185             None
186         }
187     }
188 }