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