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