1 //! A module with ide helpers for high-level ide features.
3 pub mod generated_lints;
7 pub mod insert_whitespace_into_node;
11 use std::{collections::VecDeque, iter};
14 use hir::{ItemInNs, MacroDef, ModuleDef, Name, PathResolution, Semantics};
15 use itertools::Itertools;
17 ast::{self, make, HasLoopBody},
18 AstNode, AstToken, Direction, SyntaxElement, SyntaxKind, SyntaxToken, TokenAtOffset, WalkEvent,
22 use crate::{defs::Definition, RootDatabase};
24 pub use self::famous_defs::FamousDefs;
26 pub fn item_name(db: &RootDatabase, item: ItemInNs) -> Option<Name> {
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),
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.
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>,
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()) {
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 {
54 get_path_at_cursor_in_tt(cursor)
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();
61 .siblings_with_tokens(Direction::Prev)
62 .filter_map(SyntaxElement::into_token)
63 .take_while(|tok| tok.kind() != T!['('] && tok.kind() != T![,])
65 let path_tokens = first
66 .siblings_with_tokens(Direction::Next)
67 .filter_map(SyntaxElement::into_token)
68 .take_while(|tok| tok != cursor);
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(),
77 /// Picks the token with the highest rank returned by the passed in function.
78 pub fn pick_best_token(
79 tokens: TokenAtOffset<SyntaxToken>,
80 f: impl Fn(SyntaxKind) -> usize,
81 ) -> Option<SyntaxToken> {
82 tokens.max_by_key(move |t| f(t.kind()))
85 /// Converts the mod path struct into its ast representation.
86 pub fn mod_path_to_ast(path: &hir::ModPath) -> ast::Path {
87 let _p = profile::span("mod_path_to_ast");
89 let mut segments = Vec::new();
90 let mut is_abs = false;
92 hir::PathKind::Plain => {}
93 hir::PathKind::Super(0) => segments.push(make::path_segment_self()),
94 hir::PathKind::Super(n) => segments.extend((0..n).map(|_| make::path_segment_super())),
95 hir::PathKind::DollarCrate(_) | hir::PathKind::Crate => {
96 segments.push(make::path_segment_crate())
98 hir::PathKind::Abs => is_abs = true,
104 .map(|segment| make::path_segment(make::name_ref(&segment.to_smol_str()))),
106 make::path_from_segments(segments, is_abs)
109 /// Iterates all `ModuleDef`s and `Impl` blocks of the given file.
110 pub fn visit_file_defs(
111 sema: &Semantics<RootDatabase>,
113 cb: &mut dyn FnMut(Definition),
116 let module = match sema.to_module_def(file_id) {
120 let mut defs: VecDeque<_> = module.declarations(db).into();
121 while let Some(def) = defs.pop_front() {
122 if let ModuleDef::Module(submodule) = def {
123 if let hir::ModuleSource::Module(_) = submodule.definition_source(db).value {
124 defs.extend(submodule.declarations(db));
125 submodule.impl_defs(db).into_iter().for_each(|impl_| cb(impl_.into()));
130 module.impl_defs(db).into_iter().for_each(|impl_| cb(impl_.into()));
133 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
134 pub struct SnippetCap {
139 pub const fn new(allow_snippets: bool) -> Option<SnippetCap> {
141 Some(SnippetCap { _private: () })
148 /// Calls `cb` on each expression inside `expr` that is at "tail position".
149 /// Does not walk into `break` or `return` expressions.
150 /// Note that modifying the tree while iterating it will cause undefined iteration which might
151 /// potentially results in an out of bounds panic.
152 pub fn for_each_tail_expr(expr: &ast::Expr, cb: &mut dyn FnMut(&ast::Expr)) {
154 ast::Expr::BlockExpr(b) => {
157 ast::BlockModifier::Async(_)
158 | ast::BlockModifier::Try(_)
159 | ast::BlockModifier::Const(_),
160 ) => return cb(expr),
162 Some(ast::BlockModifier::Label(label)) => {
163 for_each_break_expr(Some(label), b.stmt_list(), &mut |b| {
164 cb(&ast::Expr::BreakExpr(b))
167 Some(ast::BlockModifier::Unsafe(_)) => (),
170 if let Some(stmt_list) = b.stmt_list() {
171 if let Some(e) = stmt_list.tail_expr() {
172 for_each_tail_expr(&e, cb);
176 ast::Expr::IfExpr(if_) => {
177 let mut if_ = if_.clone();
179 if let Some(block) = if_.then_branch() {
180 for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
182 match if_.else_branch() {
183 Some(ast::ElseBranch::IfExpr(it)) => if_ = it,
184 Some(ast::ElseBranch::Block(block)) => {
185 for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
192 ast::Expr::LoopExpr(l) => {
193 for_each_break_expr(l.label(), l.loop_body().and_then(|it| it.stmt_list()), &mut |b| {
194 cb(&ast::Expr::BreakExpr(b))
197 ast::Expr::MatchExpr(m) => {
198 if let Some(arms) = m.match_arm_list() {
199 arms.arms().filter_map(|arm| arm.expr()).for_each(|e| for_each_tail_expr(&e, cb));
202 ast::Expr::ArrayExpr(_)
203 | ast::Expr::AwaitExpr(_)
204 | ast::Expr::BinExpr(_)
205 | ast::Expr::BoxExpr(_)
206 | ast::Expr::BreakExpr(_)
207 | ast::Expr::CallExpr(_)
208 | ast::Expr::CastExpr(_)
209 | ast::Expr::ClosureExpr(_)
210 | ast::Expr::ContinueExpr(_)
211 | ast::Expr::FieldExpr(_)
212 | ast::Expr::ForExpr(_)
213 | ast::Expr::IndexExpr(_)
214 | ast::Expr::Literal(_)
215 | ast::Expr::MacroCall(_)
216 | ast::Expr::MacroStmts(_)
217 | ast::Expr::MethodCallExpr(_)
218 | ast::Expr::ParenExpr(_)
219 | ast::Expr::PathExpr(_)
220 | ast::Expr::PrefixExpr(_)
221 | ast::Expr::RangeExpr(_)
222 | ast::Expr::RecordExpr(_)
223 | ast::Expr::RefExpr(_)
224 | ast::Expr::ReturnExpr(_)
225 | ast::Expr::TryExpr(_)
226 | ast::Expr::TupleExpr(_)
227 | ast::Expr::WhileExpr(_)
228 | ast::Expr::YieldExpr(_) => cb(expr),
232 /// Calls `cb` on each break expr inside of `body` that is applicable for the given label.
233 pub fn for_each_break_expr(
234 label: Option<ast::Label>,
235 body: Option<ast::StmtList>,
236 cb: &mut dyn FnMut(ast::BreakExpr),
238 let label = label.and_then(|lbl| lbl.lifetime());
240 if let Some(b) = body {
241 let preorder = &mut b.syntax().preorder();
242 let ev_as_expr = |ev| match ev {
243 WalkEvent::Enter(it) => Some(WalkEvent::Enter(ast::Expr::cast(it)?)),
244 WalkEvent::Leave(it) => Some(WalkEvent::Leave(ast::Expr::cast(it)?)),
246 let eq_label = |lt: Option<ast::Lifetime>| {
247 lt.zip(label.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
249 while let Some(node) = preorder.find_map(ev_as_expr) {
251 WalkEvent::Enter(expr) => match expr {
252 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
255 ast::Expr::BlockExpr(e) if e.label().is_some() => depth += 1,
256 ast::Expr::BreakExpr(b)
257 if (depth == 0 && b.lifetime().is_none()) || eq_label(b.lifetime()) =>
263 WalkEvent::Leave(expr) => match expr {
264 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
267 ast::Expr::BlockExpr(e) if e.label().is_some() => depth -= 1,
275 /// Checks if the given lint is equal or is contained by the other lint which may or may not be a group.
276 pub fn lint_eq_or_in_group(lint: &str, lint_is: &str) -> bool {
281 if let Some(group) = generated_lints::DEFAULT_LINT_GROUPS
283 .chain(generated_lints::CLIPPY_LINT_GROUPS.iter())
284 .chain(generated_lints::RUSTDOC_LINT_GROUPS.iter())
285 .find(|&check| check.lint.label == lint_is)
287 group.children.contains(&lint)
293 /// Parses the input token tree as comma separated plain paths.
294 pub fn parse_tt_as_comma_sep_paths(input: ast::TokenTree) -> Option<Vec<ast::Path>> {
295 let r_paren = input.r_paren_token();
297 input.syntax().children_with_tokens().skip(1).map_while(|it| match it.into_token() {
298 // seeing a keyword means the attribute is unclosed so stop parsing here
299 Some(tok) if tok.kind().is_keyword() => None,
300 // don't include the right token tree parenthesis if it exists
301 tok @ Some(_) if tok == r_paren => None,
302 // only nodes that we can find are other TokenTrees, those are unexpected in this parse though
304 Some(tok) => Some(tok),
306 let input_expressions = tokens.into_iter().group_by(|tok| tok.kind() == T![,]);
307 let paths = input_expressions
309 .filter_map(|(is_sep, group)| (!is_sep).then(|| group))
310 .filter_map(|mut tokens| {
311 syntax::hacks::parse_expr_from_str(&tokens.join("")).and_then(|expr| match expr {
312 ast::Expr::PathExpr(it) => it.path(),