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