]> git.lizzy.rs Git - rust.git/blob - crates/ide_db/src/helpers.rs
Merge #10563
[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;
11
12 use base_db::FileId;
13 use either::Either;
14 use hir::{ItemInNs, MacroDef, ModuleDef, Name, Semantics};
15 use syntax::{
16     ast::{self, make, HasLoopBody},
17     AstNode, Direction, SyntaxElement, SyntaxKind, SyntaxToken, TokenAtOffset, WalkEvent, T,
18 };
19
20 use crate::RootDatabase;
21
22 pub use self::famous_defs::FamousDefs;
23
24 pub fn item_name(db: &RootDatabase, item: ItemInNs) -> Option<Name> {
25     match item {
26         ItemInNs::Types(module_def_id) => ModuleDef::from(module_def_id).name(db),
27         ItemInNs::Values(module_def_id) => ModuleDef::from(module_def_id).name(db),
28         ItemInNs::Macros(macro_def_id) => MacroDef::from(macro_def_id).name(db),
29     }
30 }
31
32 /// Resolves the path at the cursor token as a derive macro if it inside a token tree of a derive attribute.
33 pub fn try_resolve_derive_input_at(
34     sema: &hir::Semantics<RootDatabase>,
35     derive_attr: &ast::Attr,
36     cursor: &SyntaxToken,
37 ) -> Option<MacroDef> {
38     use itertools::Itertools;
39     if cursor.kind() != T![ident] {
40         return None;
41     }
42     let tt = match derive_attr.as_simple_call() {
43         Some((name, tt))
44             if name == "derive" && tt.syntax().text_range().contains_range(cursor.text_range()) =>
45         {
46             tt
47         }
48         _ => return None,
49     };
50     let tokens: Vec<_> = cursor
51         .siblings_with_tokens(Direction::Prev)
52         .flat_map(SyntaxElement::into_token)
53         .take_while(|tok| tok.kind() != T!['('] && tok.kind() != T![,])
54         .collect();
55     let path = ast::Path::parse(&tokens.into_iter().rev().join("")).ok()?;
56     sema.scope(tt.syntax())
57         .speculative_resolve_as_mac(&path)
58         .filter(|mac| mac.kind() == hir::MacroKind::Derive)
59 }
60
61 /// Picks the token with the highest rank returned by the passed in function.
62 pub fn pick_best_token(
63     tokens: TokenAtOffset<SyntaxToken>,
64     f: impl Fn(SyntaxKind) -> usize,
65 ) -> Option<SyntaxToken> {
66     tokens.max_by_key(move |t| f(t.kind()))
67 }
68
69 /// Converts the mod path struct into its ast representation.
70 pub fn mod_path_to_ast(path: &hir::ModPath) -> ast::Path {
71     let _p = profile::span("mod_path_to_ast");
72
73     let mut segments = Vec::new();
74     let mut is_abs = false;
75     match path.kind {
76         hir::PathKind::Plain => {}
77         hir::PathKind::Super(0) => segments.push(make::path_segment_self()),
78         hir::PathKind::Super(n) => segments.extend((0..n).map(|_| make::path_segment_super())),
79         hir::PathKind::DollarCrate(_) | hir::PathKind::Crate => {
80             segments.push(make::path_segment_crate())
81         }
82         hir::PathKind::Abs => is_abs = true,
83     }
84
85     segments.extend(
86         path.segments()
87             .iter()
88             .map(|segment| make::path_segment(make::name_ref(&segment.to_string()))),
89     );
90     make::path_from_segments(segments, is_abs)
91 }
92
93 /// Iterates all `ModuleDef`s and `Impl` blocks of the given file.
94 pub fn visit_file_defs(
95     sema: &Semantics<RootDatabase>,
96     file_id: FileId,
97     cb: &mut dyn FnMut(Either<hir::ModuleDef, hir::Impl>),
98 ) {
99     let db = sema.db;
100     let module = match sema.to_module_def(file_id) {
101         Some(it) => it,
102         None => return,
103     };
104     let mut defs: VecDeque<_> = module.declarations(db).into();
105     while let Some(def) = defs.pop_front() {
106         if let ModuleDef::Module(submodule) = def {
107             if let hir::ModuleSource::Module(_) = submodule.definition_source(db).value {
108                 defs.extend(submodule.declarations(db));
109                 submodule.impl_defs(db).into_iter().for_each(|impl_| cb(Either::Right(impl_)));
110             }
111         }
112         cb(Either::Left(def));
113     }
114     module.impl_defs(db).into_iter().for_each(|impl_| cb(Either::Right(impl_)));
115 }
116
117 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
118 pub struct SnippetCap {
119     _private: (),
120 }
121
122 impl SnippetCap {
123     pub const fn new(allow_snippets: bool) -> Option<SnippetCap> {
124         if allow_snippets {
125             Some(SnippetCap { _private: () })
126         } else {
127             None
128         }
129     }
130 }
131
132 /// Calls `cb` on each expression inside `expr` that is at "tail position".
133 /// Does not walk into `break` or `return` expressions.
134 /// Note that modifying the tree while iterating it will cause undefined iteration which might
135 /// potentially results in an out of bounds panic.
136 pub fn for_each_tail_expr(expr: &ast::Expr, cb: &mut dyn FnMut(&ast::Expr)) {
137     match expr {
138         ast::Expr::BlockExpr(b) => {
139             match b.modifier() {
140                 Some(
141                     ast::BlockModifier::Async(_)
142                     | ast::BlockModifier::Try(_)
143                     | ast::BlockModifier::Const(_),
144                 ) => return cb(expr),
145
146                 Some(ast::BlockModifier::Label(label)) => {
147                     for_each_break_expr(Some(label), b.stmt_list(), &mut |b| {
148                         cb(&ast::Expr::BreakExpr(b))
149                     });
150                 }
151                 Some(ast::BlockModifier::Unsafe(_)) => (),
152                 None => (),
153             }
154             if let Some(stmt_list) = b.stmt_list() {
155                 if let Some(e) = stmt_list.tail_expr() {
156                     for_each_tail_expr(&e, cb);
157                 }
158             }
159         }
160         ast::Expr::IfExpr(if_) => {
161             let mut if_ = if_.clone();
162             loop {
163                 if let Some(block) = if_.then_branch() {
164                     for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
165                 }
166                 match if_.else_branch() {
167                     Some(ast::ElseBranch::IfExpr(it)) => if_ = it,
168                     Some(ast::ElseBranch::Block(block)) => {
169                         for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
170                         break;
171                     }
172                     None => break,
173                 }
174             }
175         }
176         ast::Expr::LoopExpr(l) => {
177             for_each_break_expr(l.label(), l.loop_body().and_then(|it| it.stmt_list()), &mut |b| {
178                 cb(&ast::Expr::BreakExpr(b))
179             })
180         }
181         ast::Expr::MatchExpr(m) => {
182             if let Some(arms) = m.match_arm_list() {
183                 arms.arms().filter_map(|arm| arm.expr()).for_each(|e| for_each_tail_expr(&e, cb));
184             }
185         }
186         ast::Expr::ArrayExpr(_)
187         | ast::Expr::AwaitExpr(_)
188         | ast::Expr::BinExpr(_)
189         | ast::Expr::BoxExpr(_)
190         | ast::Expr::BreakExpr(_)
191         | ast::Expr::CallExpr(_)
192         | ast::Expr::CastExpr(_)
193         | ast::Expr::ClosureExpr(_)
194         | ast::Expr::ContinueExpr(_)
195         | ast::Expr::FieldExpr(_)
196         | ast::Expr::ForExpr(_)
197         | ast::Expr::IndexExpr(_)
198         | ast::Expr::Literal(_)
199         | ast::Expr::MacroCall(_)
200         | ast::Expr::MacroStmts(_)
201         | ast::Expr::MethodCallExpr(_)
202         | ast::Expr::ParenExpr(_)
203         | ast::Expr::PathExpr(_)
204         | ast::Expr::PrefixExpr(_)
205         | ast::Expr::RangeExpr(_)
206         | ast::Expr::RecordExpr(_)
207         | ast::Expr::RefExpr(_)
208         | ast::Expr::ReturnExpr(_)
209         | ast::Expr::TryExpr(_)
210         | ast::Expr::TupleExpr(_)
211         | ast::Expr::WhileExpr(_)
212         | ast::Expr::YieldExpr(_) => cb(expr),
213     }
214 }
215
216 /// Calls `cb` on each break expr inside of `body` that is applicable for the given label.
217 pub fn for_each_break_expr(
218     label: Option<ast::Label>,
219     body: Option<ast::StmtList>,
220     cb: &mut dyn FnMut(ast::BreakExpr),
221 ) {
222     let label = label.and_then(|lbl| lbl.lifetime());
223     let mut depth = 0;
224     if let Some(b) = body {
225         let preorder = &mut b.syntax().preorder();
226         let ev_as_expr = |ev| match ev {
227             WalkEvent::Enter(it) => Some(WalkEvent::Enter(ast::Expr::cast(it)?)),
228             WalkEvent::Leave(it) => Some(WalkEvent::Leave(ast::Expr::cast(it)?)),
229         };
230         let eq_label = |lt: Option<ast::Lifetime>| {
231             lt.zip(label.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
232         };
233         while let Some(node) = preorder.find_map(ev_as_expr) {
234             match node {
235                 WalkEvent::Enter(expr) => match expr {
236                     ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
237                         depth += 1
238                     }
239                     ast::Expr::BlockExpr(e) if e.label().is_some() => depth += 1,
240                     ast::Expr::BreakExpr(b)
241                         if (depth == 0 && b.lifetime().is_none()) || eq_label(b.lifetime()) =>
242                     {
243                         cb(b);
244                     }
245                     _ => (),
246                 },
247                 WalkEvent::Leave(expr) => match expr {
248                     ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
249                         depth -= 1
250                     }
251                     ast::Expr::BlockExpr(e) if e.label().is_some() => depth -= 1,
252                     _ => (),
253                 },
254             }
255         }
256     }
257 }