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