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