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