]> git.lizzy.rs Git - rust.git/blob - crates/ide_db/src/helpers.rs
simplify and document
[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(&ast::Expr::BreakExpr(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(&ast::Expr::BreakExpr(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, cb));
160             }
161         }
162         ast::Expr::ArrayExpr(_)
163         | ast::Expr::AwaitExpr(_)
164         | ast::Expr::BinExpr(_)
165         | ast::Expr::BoxExpr(_)
166         | ast::Expr::BreakExpr(_)
167         | ast::Expr::CallExpr(_)
168         | ast::Expr::CastExpr(_)
169         | ast::Expr::ClosureExpr(_)
170         | ast::Expr::ContinueExpr(_)
171         | ast::Expr::FieldExpr(_)
172         | ast::Expr::ForExpr(_)
173         | ast::Expr::IndexExpr(_)
174         | ast::Expr::Literal(_)
175         | ast::Expr::MacroCall(_)
176         | ast::Expr::MacroStmts(_)
177         | ast::Expr::MethodCallExpr(_)
178         | ast::Expr::ParenExpr(_)
179         | ast::Expr::PathExpr(_)
180         | ast::Expr::PrefixExpr(_)
181         | ast::Expr::RangeExpr(_)
182         | ast::Expr::RecordExpr(_)
183         | ast::Expr::RefExpr(_)
184         | ast::Expr::ReturnExpr(_)
185         | ast::Expr::TryExpr(_)
186         | ast::Expr::TupleExpr(_)
187         | ast::Expr::WhileExpr(_)
188         | ast::Expr::LetExpr(_)
189         | ast::Expr::YieldExpr(_) => cb(expr),
190     }
191 }
192
193 /// Calls `cb` on each break expr inside of `body` that is applicable for the given label.
194 pub fn for_each_break_expr(
195     label: Option<ast::Label>,
196     body: Option<ast::StmtList>,
197     cb: &mut dyn FnMut(ast::BreakExpr),
198 ) {
199     let label = label.and_then(|lbl| lbl.lifetime());
200     let mut depth = 0;
201     if let Some(b) = body {
202         let preorder = &mut b.syntax().preorder();
203         let ev_as_expr = |ev| match ev {
204             WalkEvent::Enter(it) => Some(WalkEvent::Enter(ast::Expr::cast(it)?)),
205             WalkEvent::Leave(it) => Some(WalkEvent::Leave(ast::Expr::cast(it)?)),
206         };
207         let eq_label = |lt: Option<ast::Lifetime>| {
208             lt.zip(label.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
209         };
210         while let Some(node) = preorder.find_map(ev_as_expr) {
211             match node {
212                 WalkEvent::Enter(expr) => match expr {
213                     ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
214                         depth += 1
215                     }
216                     ast::Expr::BlockExpr(e) if e.label().is_some() => depth += 1,
217                     ast::Expr::BreakExpr(b)
218                         if (depth == 0 && b.lifetime().is_none()) || eq_label(b.lifetime()) =>
219                     {
220                         cb(b);
221                     }
222                     _ => (),
223                 },
224                 WalkEvent::Leave(expr) => match expr {
225                     ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
226                         depth -= 1
227                     }
228                     ast::Expr::BlockExpr(e) if e.label().is_some() => depth -= 1,
229                     _ => (),
230                 },
231             }
232         }
233     }
234 }
235
236 /// Checks if the given lint is equal or is contained by the other lint which may or may not be a group.
237 pub fn lint_eq_or_in_group(lint: &str, lint_is: &str) -> bool {
238     if lint == lint_is {
239         return true;
240     }
241
242     if let Some(group) = generated_lints::DEFAULT_LINT_GROUPS
243         .iter()
244         .chain(generated_lints::CLIPPY_LINT_GROUPS.iter())
245         .chain(generated_lints::RUSTDOC_LINT_GROUPS.iter())
246         .find(|&check| check.lint.label == lint_is)
247     {
248         group.children.contains(&lint)
249     } else {
250         false
251     }
252 }
253
254 /// Parses the input token tree as comma separated plain paths.
255 pub fn parse_tt_as_comma_sep_paths(input: ast::TokenTree) -> Option<Vec<ast::Path>> {
256     let r_paren = input.r_paren_token();
257     let tokens =
258         input.syntax().children_with_tokens().skip(1).map_while(|it| match it.into_token() {
259             // seeing a keyword means the attribute is unclosed so stop parsing here
260             Some(tok) if tok.kind().is_keyword() => None,
261             // don't include the right token tree parenthesis if it exists
262             tok @ Some(_) if tok == r_paren => None,
263             // only nodes that we can find are other TokenTrees, those are unexpected in this parse though
264             None => None,
265             Some(tok) => Some(tok),
266         });
267     let input_expressions = tokens.into_iter().group_by(|tok| tok.kind() == T![,]);
268     let paths = input_expressions
269         .into_iter()
270         .filter_map(|(is_sep, group)| (!is_sep).then(|| group))
271         .filter_map(|mut tokens| {
272             syntax::hacks::parse_expr_from_str(&tokens.join("")).and_then(|expr| match expr {
273                 ast::Expr::PathExpr(it) => it.path(),
274                 _ => None,
275             })
276         })
277         .collect();
278     Some(paths)
279 }