]> git.lizzy.rs Git - rust.git/blob - crates/ide_db/src/helpers.rs
Merge #10688
[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 node_ext;
8 pub mod rust_doc;
9
10 use std::{collections::VecDeque, iter};
11
12 use base_db::FileId;
13 use either::Either;
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::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 cursor = cursor.syntax();
44     let path = attr.path()?;
45     let tt = attr.token_tree()?;
46     if !tt.syntax().text_range().contains_range(cursor.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
56     let first = cursor
57         .siblings_with_tokens(Direction::Prev)
58         .filter_map(SyntaxElement::into_token)
59         .take_while(|tok| tok.kind() != T!['('] && tok.kind() != T![,])
60         .last()?;
61     let path_tokens = first
62         .siblings_with_tokens(Direction::Next)
63         .filter_map(SyntaxElement::into_token)
64         .take_while(|tok| tok != cursor);
65
66     ast::Path::parse(&path_tokens.chain(iter::once(cursor.clone())).join("")).ok()
67 }
68
69 /// Parses and resolves the path at the cursor position in the given attribute, if it is a derive.
70 /// This special case is required because the derive macro is a compiler builtin that discards the input derives.
71 pub fn try_resolve_derive_input(
72     sema: &hir::Semantics<RootDatabase>,
73     attr: &ast::Attr,
74     cursor: &Ident,
75 ) -> Option<PathResolution> {
76     let path = get_path_in_derive_attr(sema, attr, cursor)?;
77     let scope = sema.scope(attr.syntax());
78     // FIXME: This double resolve shouldn't be necessary
79     // It's only here so we prefer macros over other namespaces
80     match scope.speculative_resolve_as_mac(&path) {
81         Some(mac) if mac.kind() == hir::MacroKind::Derive => Some(PathResolution::Macro(mac)),
82         Some(_) => return None,
83         None => scope
84             .speculative_resolve(&path)
85             .filter(|res| matches!(res, PathResolution::Def(ModuleDef::Module(_)))),
86     }
87 }
88
89 /// Picks the token with the highest rank returned by the passed in function.
90 pub fn pick_best_token(
91     tokens: TokenAtOffset<SyntaxToken>,
92     f: impl Fn(SyntaxKind) -> usize,
93 ) -> Option<SyntaxToken> {
94     tokens.max_by_key(move |t| f(t.kind()))
95 }
96
97 /// Converts the mod path struct into its ast representation.
98 pub fn mod_path_to_ast(path: &hir::ModPath) -> ast::Path {
99     let _p = profile::span("mod_path_to_ast");
100
101     let mut segments = Vec::new();
102     let mut is_abs = false;
103     match path.kind {
104         hir::PathKind::Plain => {}
105         hir::PathKind::Super(0) => segments.push(make::path_segment_self()),
106         hir::PathKind::Super(n) => segments.extend((0..n).map(|_| make::path_segment_super())),
107         hir::PathKind::DollarCrate(_) | hir::PathKind::Crate => {
108             segments.push(make::path_segment_crate())
109         }
110         hir::PathKind::Abs => is_abs = true,
111     }
112
113     segments.extend(
114         path.segments()
115             .iter()
116             .map(|segment| make::path_segment(make::name_ref(&segment.to_smol_str()))),
117     );
118     make::path_from_segments(segments, is_abs)
119 }
120
121 /// Iterates all `ModuleDef`s and `Impl` blocks of the given file.
122 pub fn visit_file_defs(
123     sema: &Semantics<RootDatabase>,
124     file_id: FileId,
125     cb: &mut dyn FnMut(Either<hir::ModuleDef, hir::Impl>),
126 ) {
127     let db = sema.db;
128     let module = match sema.to_module_def(file_id) {
129         Some(it) => it,
130         None => return,
131     };
132     let mut defs: VecDeque<_> = module.declarations(db).into();
133     while let Some(def) = defs.pop_front() {
134         if let ModuleDef::Module(submodule) = def {
135             if let hir::ModuleSource::Module(_) = submodule.definition_source(db).value {
136                 defs.extend(submodule.declarations(db));
137                 submodule.impl_defs(db).into_iter().for_each(|impl_| cb(Either::Right(impl_)));
138             }
139         }
140         cb(Either::Left(def));
141     }
142     module.impl_defs(db).into_iter().for_each(|impl_| cb(Either::Right(impl_)));
143 }
144
145 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
146 pub struct SnippetCap {
147     _private: (),
148 }
149
150 impl SnippetCap {
151     pub const fn new(allow_snippets: bool) -> Option<SnippetCap> {
152         if allow_snippets {
153             Some(SnippetCap { _private: () })
154         } else {
155             None
156         }
157     }
158 }
159
160 /// Calls `cb` on each expression inside `expr` that is at "tail position".
161 /// Does not walk into `break` or `return` expressions.
162 /// Note that modifying the tree while iterating it will cause undefined iteration which might
163 /// potentially results in an out of bounds panic.
164 pub fn for_each_tail_expr(expr: &ast::Expr, cb: &mut dyn FnMut(&ast::Expr)) {
165     match expr {
166         ast::Expr::BlockExpr(b) => {
167             match b.modifier() {
168                 Some(
169                     ast::BlockModifier::Async(_)
170                     | ast::BlockModifier::Try(_)
171                     | ast::BlockModifier::Const(_),
172                 ) => return cb(expr),
173
174                 Some(ast::BlockModifier::Label(label)) => {
175                     for_each_break_expr(Some(label), b.stmt_list(), &mut |b| {
176                         cb(&ast::Expr::BreakExpr(b))
177                     });
178                 }
179                 Some(ast::BlockModifier::Unsafe(_)) => (),
180                 None => (),
181             }
182             if let Some(stmt_list) = b.stmt_list() {
183                 if let Some(e) = stmt_list.tail_expr() {
184                     for_each_tail_expr(&e, cb);
185                 }
186             }
187         }
188         ast::Expr::IfExpr(if_) => {
189             let mut if_ = if_.clone();
190             loop {
191                 if let Some(block) = if_.then_branch() {
192                     for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
193                 }
194                 match if_.else_branch() {
195                     Some(ast::ElseBranch::IfExpr(it)) => if_ = it,
196                     Some(ast::ElseBranch::Block(block)) => {
197                         for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
198                         break;
199                     }
200                     None => break,
201                 }
202             }
203         }
204         ast::Expr::LoopExpr(l) => {
205             for_each_break_expr(l.label(), l.loop_body().and_then(|it| it.stmt_list()), &mut |b| {
206                 cb(&ast::Expr::BreakExpr(b))
207             })
208         }
209         ast::Expr::MatchExpr(m) => {
210             if let Some(arms) = m.match_arm_list() {
211                 arms.arms().filter_map(|arm| arm.expr()).for_each(|e| for_each_tail_expr(&e, cb));
212             }
213         }
214         ast::Expr::ArrayExpr(_)
215         | ast::Expr::AwaitExpr(_)
216         | ast::Expr::BinExpr(_)
217         | ast::Expr::BoxExpr(_)
218         | ast::Expr::BreakExpr(_)
219         | ast::Expr::CallExpr(_)
220         | ast::Expr::CastExpr(_)
221         | ast::Expr::ClosureExpr(_)
222         | ast::Expr::ContinueExpr(_)
223         | ast::Expr::FieldExpr(_)
224         | ast::Expr::ForExpr(_)
225         | ast::Expr::IndexExpr(_)
226         | ast::Expr::Literal(_)
227         | ast::Expr::MacroCall(_)
228         | ast::Expr::MacroStmts(_)
229         | ast::Expr::MethodCallExpr(_)
230         | ast::Expr::ParenExpr(_)
231         | ast::Expr::PathExpr(_)
232         | ast::Expr::PrefixExpr(_)
233         | ast::Expr::RangeExpr(_)
234         | ast::Expr::RecordExpr(_)
235         | ast::Expr::RefExpr(_)
236         | ast::Expr::ReturnExpr(_)
237         | ast::Expr::TryExpr(_)
238         | ast::Expr::TupleExpr(_)
239         | ast::Expr::WhileExpr(_)
240         | ast::Expr::YieldExpr(_) => cb(expr),
241     }
242 }
243
244 /// Calls `cb` on each break expr inside of `body` that is applicable for the given label.
245 pub fn for_each_break_expr(
246     label: Option<ast::Label>,
247     body: Option<ast::StmtList>,
248     cb: &mut dyn FnMut(ast::BreakExpr),
249 ) {
250     let label = label.and_then(|lbl| lbl.lifetime());
251     let mut depth = 0;
252     if let Some(b) = body {
253         let preorder = &mut b.syntax().preorder();
254         let ev_as_expr = |ev| match ev {
255             WalkEvent::Enter(it) => Some(WalkEvent::Enter(ast::Expr::cast(it)?)),
256             WalkEvent::Leave(it) => Some(WalkEvent::Leave(ast::Expr::cast(it)?)),
257         };
258         let eq_label = |lt: Option<ast::Lifetime>| {
259             lt.zip(label.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
260         };
261         while let Some(node) = preorder.find_map(ev_as_expr) {
262             match node {
263                 WalkEvent::Enter(expr) => match expr {
264                     ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
265                         depth += 1
266                     }
267                     ast::Expr::BlockExpr(e) if e.label().is_some() => depth += 1,
268                     ast::Expr::BreakExpr(b)
269                         if (depth == 0 && b.lifetime().is_none()) || eq_label(b.lifetime()) =>
270                     {
271                         cb(b);
272                     }
273                     _ => (),
274                 },
275                 WalkEvent::Leave(expr) => match expr {
276                     ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
277                         depth -= 1
278                     }
279                     ast::Expr::BlockExpr(e) if e.label().is_some() => depth -= 1,
280                     _ => (),
281                 },
282             }
283         }
284     }
285 }