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