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