]> git.lizzy.rs Git - rust.git/blob - crates/ide_db/src/helpers.rs
fix(11422): have two different funuctions - one for iterating breaks, one for iteraat...
[rust.git] / crates / ide_db / src / helpers.rs
1 //! A module with ide helpers for high-level ide features.
2 pub mod famous_defs;
3 pub mod generated_lints;
4 pub mod import_assets;
5 pub mod insert_use;
6 pub mod merge_imports;
7 pub mod insert_whitespace_into_node;
8 pub mod node_ext;
9 pub mod rust_doc;
10 pub mod format_string;
11
12 use std::collections::VecDeque;
13
14 use base_db::FileId;
15 use hir::{ItemInNs, MacroDef, ModuleDef, Name, Semantics};
16 use itertools::Itertools;
17 use syntax::{
18     ast::{self, make, HasLoopBody},
19     AstNode, AstToken, Preorder, RustLanguage, SyntaxKind, SyntaxToken, TokenAtOffset, WalkEvent,
20     T,
21 };
22
23 use crate::{defs::Definition, RootDatabase};
24
25 pub use self::famous_defs::FamousDefs;
26
27 pub fn item_name(db: &RootDatabase, item: ItemInNs) -> Option<Name> {
28     match item {
29         ItemInNs::Types(module_def_id) => ModuleDef::from(module_def_id).name(db),
30         ItemInNs::Values(module_def_id) => ModuleDef::from(module_def_id).name(db),
31         ItemInNs::Macros(macro_def_id) => MacroDef::from(macro_def_id).name(db),
32     }
33 }
34
35 /// Picks the token with the highest rank returned by the passed in function.
36 pub fn pick_best_token(
37     tokens: TokenAtOffset<SyntaxToken>,
38     f: impl Fn(SyntaxKind) -> usize,
39 ) -> Option<SyntaxToken> {
40     tokens.max_by_key(move |t| f(t.kind()))
41 }
42 pub fn pick_token<T: AstToken>(mut tokens: TokenAtOffset<SyntaxToken>) -> Option<T> {
43     tokens.find_map(T::cast)
44 }
45
46 /// Converts the mod path struct into its ast representation.
47 pub fn mod_path_to_ast(path: &hir::ModPath) -> ast::Path {
48     let _p = profile::span("mod_path_to_ast");
49
50     let mut segments = Vec::new();
51     let mut is_abs = false;
52     match path.kind {
53         hir::PathKind::Plain => {}
54         hir::PathKind::Super(0) => segments.push(make::path_segment_self()),
55         hir::PathKind::Super(n) => segments.extend((0..n).map(|_| make::path_segment_super())),
56         hir::PathKind::DollarCrate(_) | hir::PathKind::Crate => {
57             segments.push(make::path_segment_crate())
58         }
59         hir::PathKind::Abs => is_abs = true,
60     }
61
62     segments.extend(
63         path.segments()
64             .iter()
65             .map(|segment| make::path_segment(make::name_ref(&segment.to_smol_str()))),
66     );
67     make::path_from_segments(segments, is_abs)
68 }
69
70 /// Iterates all `ModuleDef`s and `Impl` blocks of the given file.
71 pub fn visit_file_defs(
72     sema: &Semantics<RootDatabase>,
73     file_id: FileId,
74     cb: &mut dyn FnMut(Definition),
75 ) {
76     let db = sema.db;
77     let module = match sema.to_module_def(file_id) {
78         Some(it) => it,
79         None => return,
80     };
81     let mut defs: VecDeque<_> = module.declarations(db).into();
82     while let Some(def) = defs.pop_front() {
83         if let ModuleDef::Module(submodule) = def {
84             if let hir::ModuleSource::Module(_) = submodule.definition_source(db).value {
85                 defs.extend(submodule.declarations(db));
86                 submodule.impl_defs(db).into_iter().for_each(|impl_| cb(impl_.into()));
87             }
88         }
89         cb(def.into());
90     }
91     module.impl_defs(db).into_iter().for_each(|impl_| cb(impl_.into()));
92 }
93
94 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
95 pub struct SnippetCap {
96     _private: (),
97 }
98
99 impl SnippetCap {
100     pub const fn new(allow_snippets: bool) -> Option<SnippetCap> {
101         if allow_snippets {
102             Some(SnippetCap { _private: () })
103         } else {
104             None
105         }
106     }
107 }
108
109 /// Calls `cb` on each expression inside `expr` that is at "tail position".
110 /// Does not walk into `break` or `return` expressions.
111 /// Note that modifying the tree while iterating it will cause undefined iteration which might
112 /// potentially results in an out of bounds panic.
113 pub fn for_each_tail_expr(expr: &ast::Expr, cb: &mut dyn FnMut(&ast::Expr)) {
114     match expr {
115         ast::Expr::BlockExpr(b) => {
116             match b.modifier() {
117                 Some(
118                     ast::BlockModifier::Async(_)
119                     | ast::BlockModifier::Try(_)
120                     | ast::BlockModifier::Const(_),
121                 ) => return cb(expr),
122
123                 Some(ast::BlockModifier::Label(label)) => {
124                     for_each_break_expr(Some(label), b.stmt_list(), &mut |b| {
125                         cb(&ast::Expr::BreakExpr(b))
126                     });
127                 }
128                 Some(ast::BlockModifier::Unsafe(_)) => (),
129                 None => (),
130             }
131             if let Some(stmt_list) = b.stmt_list() {
132                 if let Some(e) = stmt_list.tail_expr() {
133                     for_each_tail_expr(&e, cb);
134                 }
135             }
136         }
137         ast::Expr::IfExpr(if_) => {
138             let mut if_ = if_.clone();
139             loop {
140                 if let Some(block) = if_.then_branch() {
141                     for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
142                 }
143                 match if_.else_branch() {
144                     Some(ast::ElseBranch::IfExpr(it)) => if_ = it,
145                     Some(ast::ElseBranch::Block(block)) => {
146                         for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
147                         break;
148                     }
149                     None => break,
150                 }
151             }
152         }
153         ast::Expr::LoopExpr(l) => {
154             for_each_break_expr(l.label(), l.loop_body().and_then(|it| it.stmt_list()), &mut |b| {
155                 cb(&ast::Expr::BreakExpr(b))
156             })
157         }
158         ast::Expr::MatchExpr(m) => {
159             if let Some(arms) = m.match_arm_list() {
160                 arms.arms().filter_map(|arm| arm.expr()).for_each(|e| for_each_tail_expr(&e, cb));
161             }
162         }
163         ast::Expr::ArrayExpr(_)
164         | ast::Expr::AwaitExpr(_)
165         | ast::Expr::BinExpr(_)
166         | ast::Expr::BoxExpr(_)
167         | ast::Expr::BreakExpr(_)
168         | ast::Expr::CallExpr(_)
169         | ast::Expr::CastExpr(_)
170         | ast::Expr::ClosureExpr(_)
171         | ast::Expr::ContinueExpr(_)
172         | ast::Expr::FieldExpr(_)
173         | ast::Expr::ForExpr(_)
174         | ast::Expr::IndexExpr(_)
175         | ast::Expr::Literal(_)
176         | ast::Expr::MacroCall(_)
177         | ast::Expr::MacroStmts(_)
178         | ast::Expr::MethodCallExpr(_)
179         | ast::Expr::ParenExpr(_)
180         | ast::Expr::PathExpr(_)
181         | ast::Expr::PrefixExpr(_)
182         | ast::Expr::RangeExpr(_)
183         | ast::Expr::RecordExpr(_)
184         | ast::Expr::RefExpr(_)
185         | ast::Expr::ReturnExpr(_)
186         | ast::Expr::TryExpr(_)
187         | ast::Expr::TupleExpr(_)
188         | ast::Expr::WhileExpr(_)
189         | ast::Expr::LetExpr(_)
190         | ast::Expr::YieldExpr(_) => cb(expr),
191     }
192 }
193
194 pub fn for_each_break_and_continue_expr(
195     label: Option<ast::Label>,
196     body: Option<ast::StmtList>,
197     cb: &mut dyn FnMut(ast::Expr),
198 ) {
199     let label = label.and_then(|lbl| lbl.lifetime());
200     if let Some(b) = body {
201         let tree_depth_iterator = TreeWithDepthIterator::new(b);
202         for (expr, depth) in tree_depth_iterator {
203             match expr {
204                 ast::Expr::BreakExpr(b)
205                     if (depth == 0 && b.lifetime().is_none())
206                         || eq_label_lt(&label, &b.lifetime()) =>
207                 {
208                     cb(ast::Expr::BreakExpr(b));
209                 }
210                 ast::Expr::ContinueExpr(c)
211                     if (depth == 0 && c.lifetime().is_none())
212                         || eq_label_lt(&label, &c.lifetime()) =>
213                 {
214                     cb(ast::Expr::ContinueExpr(c));
215                 }
216                 _ => (),
217             }
218         }
219     }
220 }
221
222 fn for_each_break_expr(
223     label: Option<ast::Label>,
224     body: Option<ast::StmtList>,
225     cb: &mut dyn FnMut(ast::BreakExpr),
226 ) {
227     let label = label.and_then(|lbl| lbl.lifetime());
228     if let Some(b) = body {
229         let tree_depth_iterator = TreeWithDepthIterator::new(b);
230         for (expr, depth) in tree_depth_iterator {
231             match expr {
232                 ast::Expr::BreakExpr(b)
233                     if (depth == 0 && b.lifetime().is_none())
234                         || eq_label_lt(&label, &b.lifetime()) =>
235                 {
236                     cb(b);
237                 }
238                 _ => (),
239             }
240         }
241     }
242 }
243
244 fn eq_label_lt(lt1: &Option<ast::Lifetime>, lt2: &Option<ast::Lifetime>) -> bool {
245     lt1.as_ref().zip(lt2.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
246 }
247
248 struct TreeWithDepthIterator {
249     preorder: Preorder<RustLanguage>,
250     depth: i32,
251 }
252
253 impl TreeWithDepthIterator {
254     fn new(body: ast::StmtList) -> Self {
255         let preorder = body.syntax().preorder();
256         Self { preorder, depth: 0 }
257     }
258 }
259
260 impl<'a> Iterator for TreeWithDepthIterator {
261     type Item = (ast::Expr, i32);
262
263     fn next(&mut self) -> Option<Self::Item> {
264         while let Some((event, expr)) = self.preorder.find_map(|ev| match ev {
265             WalkEvent::Enter(it) => Some(WalkEvent::Enter(())).zip(ast::Expr::cast(it)),
266             WalkEvent::Leave(it) => Some(WalkEvent::Leave(())).zip(ast::Expr::cast(it)),
267         }) {
268             match (event, expr) {
269                 (
270                     WalkEvent::Enter(_),
271                     ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_),
272                 ) => {
273                     self.depth += 1;
274                 }
275                 (
276                     WalkEvent::Leave(_),
277                     ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_),
278                 ) => {
279                     self.depth -= 1;
280                 }
281                 (WalkEvent::Enter(_), ast::Expr::BlockExpr(e)) if e.label().is_some() => {
282                     self.depth += 1;
283                 }
284                 (WalkEvent::Leave(_), ast::Expr::BlockExpr(e)) if e.label().is_some() => {
285                     self.depth -= 1;
286                 }
287                 (WalkEvent::Enter(_), expr) => return Some((expr, self.depth)),
288                 _ => (),
289             }
290         }
291         None
292     }
293 }
294
295 /// Checks if the given lint is equal or is contained by the other lint which may or may not be a group.
296 pub fn lint_eq_or_in_group(lint: &str, lint_is: &str) -> bool {
297     if lint == lint_is {
298         return true;
299     }
300
301     if let Some(group) = generated_lints::DEFAULT_LINT_GROUPS
302         .iter()
303         .chain(generated_lints::CLIPPY_LINT_GROUPS.iter())
304         .chain(generated_lints::RUSTDOC_LINT_GROUPS.iter())
305         .find(|&check| check.lint.label == lint_is)
306     {
307         group.children.contains(&lint)
308     } else {
309         false
310     }
311 }
312
313 /// Parses the input token tree as comma separated plain paths.
314 pub fn parse_tt_as_comma_sep_paths(input: ast::TokenTree) -> Option<Vec<ast::Path>> {
315     let r_paren = input.r_paren_token();
316     let tokens =
317         input.syntax().children_with_tokens().skip(1).map_while(|it| match it.into_token() {
318             // seeing a keyword means the attribute is unclosed so stop parsing here
319             Some(tok) if tok.kind().is_keyword() => None,
320             // don't include the right token tree parenthesis if it exists
321             tok @ Some(_) if tok == r_paren => None,
322             // only nodes that we can find are other TokenTrees, those are unexpected in this parse though
323             None => None,
324             Some(tok) => Some(tok),
325         });
326     let input_expressions = tokens.into_iter().group_by(|tok| tok.kind() == T![,]);
327     let paths = input_expressions
328         .into_iter()
329         .filter_map(|(is_sep, group)| (!is_sep).then(|| group))
330         .filter_map(|mut tokens| {
331             syntax::hacks::parse_expr_from_str(&tokens.join("")).and_then(|expr| match expr {
332                 ast::Expr::PathExpr(it) => it.path(),
333                 _ => None,
334             })
335         })
336         .collect();
337     Some(paths)
338 }