]> git.lizzy.rs Git - rust.git/blob - crates/ide_db/src/helpers.rs
Merge #9807
[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::{
14     ast::{self, make, LoopBodyOwner},
15     AstNode, Direction, SyntaxElement, SyntaxKind, SyntaxToken, TokenAtOffset, WalkEvent, T,
16 };
17
18 use crate::RootDatabase;
19
20 pub fn item_name(db: &RootDatabase, item: ItemInNs) -> Option<Name> {
21     match item {
22         ItemInNs::Types(module_def_id) => ModuleDef::from(module_def_id).name(db),
23         ItemInNs::Values(module_def_id) => ModuleDef::from(module_def_id).name(db),
24         ItemInNs::Macros(macro_def_id) => MacroDef::from(macro_def_id).name(db),
25     }
26 }
27
28 /// Resolves the path at the cursor token as a derive macro if it inside a token tree of a derive attribute.
29 pub fn try_resolve_derive_input_at(
30     sema: &Semantics<RootDatabase>,
31     derive_attr: &ast::Attr,
32     cursor: &SyntaxToken,
33 ) -> Option<MacroDef> {
34     use itertools::Itertools;
35     if cursor.kind() != T![ident] {
36         return None;
37     }
38     let tt = match derive_attr.as_simple_call() {
39         Some((name, tt))
40             if name == "derive" && tt.syntax().text_range().contains_range(cursor.text_range()) =>
41         {
42             tt
43         }
44         _ => return None,
45     };
46     let tokens: Vec<_> = cursor
47         .siblings_with_tokens(Direction::Prev)
48         .flat_map(SyntaxElement::into_token)
49         .take_while(|tok| tok.kind() != T!['('] && tok.kind() != T![,])
50         .collect();
51     let path = ast::Path::parse(&tokens.into_iter().rev().join("")).ok()?;
52     match sema.scope(tt.syntax()).speculative_resolve(&path) {
53         Some(hir::PathResolution::Macro(makro)) if makro.kind() == hir::MacroKind::Derive => {
54             Some(makro)
55         }
56         _ => None,
57     }
58 }
59
60 /// Picks the token with the highest rank returned by the passed in function.
61 pub fn pick_best_token(
62     tokens: TokenAtOffset<SyntaxToken>,
63     f: impl Fn(SyntaxKind) -> usize,
64 ) -> Option<SyntaxToken> {
65     tokens.max_by_key(move |t| f(t.kind()))
66 }
67
68 /// Converts the mod path struct into its ast representation.
69 pub fn mod_path_to_ast(path: &hir::ModPath) -> ast::Path {
70     let _p = profile::span("mod_path_to_ast");
71
72     let mut segments = Vec::new();
73     let mut is_abs = false;
74     match path.kind {
75         hir::PathKind::Plain => {}
76         hir::PathKind::Super(0) => segments.push(make::path_segment_self()),
77         hir::PathKind::Super(n) => segments.extend((0..n).map(|_| make::path_segment_super())),
78         hir::PathKind::DollarCrate(_) | hir::PathKind::Crate => {
79             segments.push(make::path_segment_crate())
80         }
81         hir::PathKind::Abs => is_abs = true,
82     }
83
84     segments.extend(
85         path.segments()
86             .iter()
87             .map(|segment| make::path_segment(make::name_ref(&segment.to_string()))),
88     );
89     make::path_from_segments(segments, is_abs)
90 }
91
92 /// Iterates all `ModuleDef`s and `Impl` blocks of the given file.
93 pub fn visit_file_defs(
94     sema: &Semantics<RootDatabase>,
95     file_id: FileId,
96     cb: &mut dyn FnMut(Either<hir::ModuleDef, hir::Impl>),
97 ) {
98     let db = sema.db;
99     let module = match sema.to_module_def(file_id) {
100         Some(it) => it,
101         None => return,
102     };
103     let mut defs: VecDeque<_> = module.declarations(db).into();
104     while let Some(def) = defs.pop_front() {
105         if let ModuleDef::Module(submodule) = def {
106             if let hir::ModuleSource::Module(_) = submodule.definition_source(db).value {
107                 defs.extend(submodule.declarations(db));
108                 submodule.impl_defs(db).into_iter().for_each(|impl_| cb(Either::Right(impl_)));
109             }
110         }
111         cb(Either::Left(def));
112     }
113     module.impl_defs(db).into_iter().for_each(|impl_| cb(Either::Right(impl_)));
114 }
115
116 /// Helps with finding well-know things inside the standard library. This is
117 /// somewhat similar to the known paths infra inside hir, but it different; We
118 /// want to make sure that IDE specific paths don't become interesting inside
119 /// the compiler itself as well.
120 ///
121 /// Note that, by default, rust-analyzer tests **do not** include core or std
122 /// libraries. If you are writing tests for functionality using [`FamousDefs`],
123 /// you'd want to include minicore (see `test_utils::MiniCore`) declaration at
124 /// the start of your tests:
125 ///
126 /// ```
127 /// //- minicore: iterator, ord, derive
128 /// ```
129 pub struct FamousDefs<'a, 'b>(pub &'a Semantics<'b, RootDatabase>, pub Option<Crate>);
130
131 #[allow(non_snake_case)]
132 impl FamousDefs<'_, '_> {
133     pub fn std(&self) -> Option<Crate> {
134         self.find_crate("std")
135     }
136
137     pub fn core(&self) -> Option<Crate> {
138         self.find_crate("core")
139     }
140
141     pub fn core_cmp_Ord(&self) -> Option<Trait> {
142         self.find_trait("core:cmp:Ord")
143     }
144
145     pub fn core_convert_From(&self) -> Option<Trait> {
146         self.find_trait("core:convert:From")
147     }
148
149     pub fn core_convert_Into(&self) -> Option<Trait> {
150         self.find_trait("core:convert:Into")
151     }
152
153     pub fn core_option_Option(&self) -> Option<Enum> {
154         self.find_enum("core:option:Option")
155     }
156
157     pub fn core_result_Result(&self) -> Option<Enum> {
158         self.find_enum("core:result:Result")
159     }
160
161     pub fn core_default_Default(&self) -> Option<Trait> {
162         self.find_trait("core:default:Default")
163     }
164
165     pub fn core_iter_Iterator(&self) -> Option<Trait> {
166         self.find_trait("core:iter:traits:iterator:Iterator")
167     }
168
169     pub fn core_iter_IntoIterator(&self) -> Option<Trait> {
170         self.find_trait("core:iter:traits:collect:IntoIterator")
171     }
172
173     pub fn core_iter(&self) -> Option<Module> {
174         self.find_module("core:iter")
175     }
176
177     pub fn core_ops_Deref(&self) -> Option<Trait> {
178         self.find_trait("core:ops:Deref")
179     }
180
181     fn find_trait(&self, path: &str) -> Option<Trait> {
182         match self.find_def(path)? {
183             hir::ScopeDef::ModuleDef(hir::ModuleDef::Trait(it)) => Some(it),
184             _ => None,
185         }
186     }
187
188     fn find_enum(&self, path: &str) -> Option<Enum> {
189         match self.find_def(path)? {
190             hir::ScopeDef::ModuleDef(hir::ModuleDef::Adt(hir::Adt::Enum(it))) => Some(it),
191             _ => None,
192         }
193     }
194
195     fn find_module(&self, path: &str) -> Option<Module> {
196         match self.find_def(path)? {
197             hir::ScopeDef::ModuleDef(hir::ModuleDef::Module(it)) => Some(it),
198             _ => None,
199         }
200     }
201
202     fn find_crate(&self, name: &str) -> Option<Crate> {
203         let krate = self.1?;
204         let db = self.0.db;
205         let res =
206             krate.dependencies(db).into_iter().find(|dep| dep.name.to_string() == name)?.krate;
207         Some(res)
208     }
209
210     fn find_def(&self, path: &str) -> Option<ScopeDef> {
211         let db = self.0.db;
212         let mut path = path.split(':');
213         let trait_ = path.next_back()?;
214         let std_crate = path.next()?;
215         let std_crate = self.find_crate(std_crate)?;
216         let mut module = std_crate.root_module(db);
217         for segment in path {
218             module = module.children(db).find_map(|child| {
219                 let name = child.name(db)?;
220                 if name.to_string() == segment {
221                     Some(child)
222                 } else {
223                     None
224                 }
225             })?;
226         }
227         let def =
228             module.scope(db, None).into_iter().find(|(name, _def)| name.to_string() == trait_)?.1;
229         Some(def)
230     }
231 }
232
233 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
234 pub struct SnippetCap {
235     _private: (),
236 }
237
238 impl SnippetCap {
239     pub const fn new(allow_snippets: bool) -> Option<SnippetCap> {
240         if allow_snippets {
241             Some(SnippetCap { _private: () })
242         } else {
243             None
244         }
245     }
246 }
247
248 /// Calls `cb` on each expression inside `expr` that is at "tail position".
249 /// Does not walk into `break` or `return` expressions.
250 /// Note that modifying the tree while iterating it will cause undefined iteration which might
251 /// potentially results in an out of bounds panic.
252 pub fn for_each_tail_expr(expr: &ast::Expr, cb: &mut dyn FnMut(&ast::Expr)) {
253     match expr {
254         ast::Expr::BlockExpr(b) => {
255             if let Some(e) = b.tail_expr() {
256                 for_each_tail_expr(&e, cb);
257             }
258         }
259         ast::Expr::EffectExpr(e) => match e.effect() {
260             ast::Effect::Label(label) => {
261                 for_each_break_expr(Some(label), e.block_expr(), &mut |b| {
262                     cb(&ast::Expr::BreakExpr(b))
263                 });
264                 if let Some(b) = e.block_expr() {
265                     for_each_tail_expr(&ast::Expr::BlockExpr(b), cb);
266                 }
267             }
268             ast::Effect::Unsafe(_) => {
269                 if let Some(e) = e.block_expr().and_then(|b| b.tail_expr()) {
270                     for_each_tail_expr(&e, cb);
271                 }
272             }
273             ast::Effect::Async(_) | ast::Effect::Try(_) | ast::Effect::Const(_) => cb(expr),
274         },
275         ast::Expr::IfExpr(if_) => {
276             let mut if_ = if_.clone();
277             loop {
278                 if let Some(block) = if_.then_branch() {
279                     for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
280                 }
281                 match if_.else_branch() {
282                     Some(ast::ElseBranch::IfExpr(it)) => if_ = it,
283                     Some(ast::ElseBranch::Block(block)) => {
284                         for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
285                         break;
286                     }
287                     None => break,
288                 }
289             }
290         }
291         ast::Expr::LoopExpr(l) => {
292             for_each_break_expr(l.label(), l.loop_body(), &mut |b| cb(&ast::Expr::BreakExpr(b)))
293         }
294         ast::Expr::MatchExpr(m) => {
295             if let Some(arms) = m.match_arm_list() {
296                 arms.arms().filter_map(|arm| arm.expr()).for_each(|e| for_each_tail_expr(&e, cb));
297             }
298         }
299         ast::Expr::ArrayExpr(_)
300         | ast::Expr::AwaitExpr(_)
301         | ast::Expr::BinExpr(_)
302         | ast::Expr::BoxExpr(_)
303         | ast::Expr::BreakExpr(_)
304         | ast::Expr::CallExpr(_)
305         | ast::Expr::CastExpr(_)
306         | ast::Expr::ClosureExpr(_)
307         | ast::Expr::ContinueExpr(_)
308         | ast::Expr::FieldExpr(_)
309         | ast::Expr::ForExpr(_)
310         | ast::Expr::IndexExpr(_)
311         | ast::Expr::Literal(_)
312         | ast::Expr::MacroCall(_)
313         | ast::Expr::MacroStmts(_)
314         | ast::Expr::MethodCallExpr(_)
315         | ast::Expr::ParenExpr(_)
316         | ast::Expr::PathExpr(_)
317         | ast::Expr::PrefixExpr(_)
318         | ast::Expr::RangeExpr(_)
319         | ast::Expr::RecordExpr(_)
320         | ast::Expr::RefExpr(_)
321         | ast::Expr::ReturnExpr(_)
322         | ast::Expr::TryExpr(_)
323         | ast::Expr::TupleExpr(_)
324         | ast::Expr::WhileExpr(_)
325         | ast::Expr::YieldExpr(_) => cb(expr),
326     }
327 }
328
329 /// Calls `cb` on each break expr inside of `body` that is applicable for the given label.
330 pub fn for_each_break_expr(
331     label: Option<ast::Label>,
332     body: Option<ast::BlockExpr>,
333     cb: &mut dyn FnMut(ast::BreakExpr),
334 ) {
335     let label = label.and_then(|lbl| lbl.lifetime());
336     let mut depth = 0;
337     if let Some(b) = body {
338         let preorder = &mut b.syntax().preorder();
339         let ev_as_expr = |ev| match ev {
340             WalkEvent::Enter(it) => Some(WalkEvent::Enter(ast::Expr::cast(it)?)),
341             WalkEvent::Leave(it) => Some(WalkEvent::Leave(ast::Expr::cast(it)?)),
342         };
343         let eq_label = |lt: Option<ast::Lifetime>| {
344             lt.zip(label.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
345         };
346         while let Some(node) = preorder.find_map(ev_as_expr) {
347             match node {
348                 WalkEvent::Enter(expr) => match expr {
349                     ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
350                         depth += 1
351                     }
352                     ast::Expr::EffectExpr(e) if e.label().is_some() => depth += 1,
353                     ast::Expr::BreakExpr(b)
354                         if (depth == 0 && b.lifetime().is_none()) || eq_label(b.lifetime()) =>
355                     {
356                         cb(b);
357                     }
358                     _ => (),
359                 },
360                 WalkEvent::Leave(expr) => match expr {
361                     ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
362                         depth -= 1
363                     }
364                     ast::Expr::EffectExpr(e) if e.label().is_some() => depth -= 1,
365                     _ => (),
366                 },
367             }
368         }
369     }
370 }