1 //! A module with ide helpers for high-level ide features.
3 pub mod generated_lints;
7 pub mod insert_whitespace_into_node;
10 pub mod format_string;
12 use std::{collections::VecDeque, iter};
15 use hir::{ItemInNs, MacroDef, ModuleDef, Name, PathResolution, Semantics};
16 use itertools::Itertools;
18 ast::{self, make, HasLoopBody},
19 AstNode, AstToken, Direction, SyntaxElement, SyntaxKind, SyntaxToken, TokenAtOffset, WalkEvent,
23 use crate::{defs::Definition, RootDatabase};
25 pub use self::famous_defs::FamousDefs;
27 pub fn item_name(db: &RootDatabase, item: ItemInNs) -> Option<Name> {
29 ItemInNs::Types(module_def_id) => ModuleDef::from(module_def_id).name(db),
30 ItemInNs::Values(module_def_id) => ModuleDef::from(module_def_id).name(db),
31 ItemInNs::Macros(macro_def_id) => MacroDef::from(macro_def_id).name(db),
35 /// Parses and returns the derive path at the cursor position in the given attribute, if it is a derive.
36 /// This special case is required because the derive macro is a compiler builtin that discards the input derives.
38 /// The returned path is synthesized from TokenTree tokens and as such cannot be used with the [`Semantics`].
39 pub fn get_path_in_derive_attr(
40 sema: &hir::Semantics<RootDatabase>,
43 ) -> Option<ast::Path> {
44 let path = attr.path()?;
45 let tt = attr.token_tree()?;
46 if !tt.syntax().text_range().contains_range(cursor.syntax().text_range()) {
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 {
55 get_path_at_cursor_in_tt(cursor)
58 /// Parses the path the identifier is part of inside a token tree.
59 pub fn get_path_at_cursor_in_tt(cursor: &ast::Ident) -> Option<ast::Path> {
60 let cursor = cursor.syntax();
62 .siblings_with_tokens(Direction::Prev)
63 .filter_map(SyntaxElement::into_token)
64 .take_while(|tok| tok.kind() != T!['('] && tok.kind() != T![,])
66 let path_tokens = first
67 .siblings_with_tokens(Direction::Next)
68 .filter_map(SyntaxElement::into_token)
69 .take_while(|tok| tok != cursor);
71 syntax::hacks::parse_expr_from_str(&path_tokens.chain(iter::once(cursor.clone())).join(""))
72 .and_then(|expr| match expr {
73 ast::Expr::PathExpr(it) => it.path(),
78 /// Picks the token with the highest rank returned by the passed in function.
79 pub fn pick_best_token(
80 tokens: TokenAtOffset<SyntaxToken>,
81 f: impl Fn(SyntaxKind) -> usize,
82 ) -> Option<SyntaxToken> {
83 tokens.max_by_key(move |t| f(t.kind()))
86 /// Converts the mod path struct into its ast representation.
87 pub fn mod_path_to_ast(path: &hir::ModPath) -> ast::Path {
88 let _p = profile::span("mod_path_to_ast");
90 let mut segments = Vec::new();
91 let mut is_abs = false;
93 hir::PathKind::Plain => {}
94 hir::PathKind::Super(0) => segments.push(make::path_segment_self()),
95 hir::PathKind::Super(n) => segments.extend((0..n).map(|_| make::path_segment_super())),
96 hir::PathKind::DollarCrate(_) | hir::PathKind::Crate => {
97 segments.push(make::path_segment_crate())
99 hir::PathKind::Abs => is_abs = true,
105 .map(|segment| make::path_segment(make::name_ref(&segment.to_smol_str()))),
107 make::path_from_segments(segments, is_abs)
110 /// Iterates all `ModuleDef`s and `Impl` blocks of the given file.
111 pub fn visit_file_defs(
112 sema: &Semantics<RootDatabase>,
114 cb: &mut dyn FnMut(Definition),
117 let module = match sema.to_module_def(file_id) {
121 let mut defs: VecDeque<_> = module.declarations(db).into();
122 while let Some(def) = defs.pop_front() {
123 if let ModuleDef::Module(submodule) = def {
124 if let hir::ModuleSource::Module(_) = submodule.definition_source(db).value {
125 defs.extend(submodule.declarations(db));
126 submodule.impl_defs(db).into_iter().for_each(|impl_| cb(impl_.into()));
131 module.impl_defs(db).into_iter().for_each(|impl_| cb(impl_.into()));
134 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
135 pub struct SnippetCap {
140 pub const fn new(allow_snippets: bool) -> Option<SnippetCap> {
142 Some(SnippetCap { _private: () })
149 /// Calls `cb` on each expression inside `expr` that is at "tail position".
150 /// Does not walk into `break` or `return` expressions.
151 /// Note that modifying the tree while iterating it will cause undefined iteration which might
152 /// potentially results in an out of bounds panic.
153 pub fn for_each_tail_expr(expr: &ast::Expr, cb: &mut dyn FnMut(&ast::Expr)) {
155 ast::Expr::BlockExpr(b) => {
158 ast::BlockModifier::Async(_)
159 | ast::BlockModifier::Try(_)
160 | ast::BlockModifier::Const(_),
161 ) => return cb(expr),
163 Some(ast::BlockModifier::Label(label)) => {
164 for_each_break_expr(Some(label), b.stmt_list(), &mut |b| {
165 cb(&ast::Expr::BreakExpr(b))
168 Some(ast::BlockModifier::Unsafe(_)) => (),
171 if let Some(stmt_list) = b.stmt_list() {
172 if let Some(e) = stmt_list.tail_expr() {
173 for_each_tail_expr(&e, cb);
177 ast::Expr::IfExpr(if_) => {
178 let mut if_ = if_.clone();
180 if let Some(block) = if_.then_branch() {
181 for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
183 match if_.else_branch() {
184 Some(ast::ElseBranch::IfExpr(it)) => if_ = it,
185 Some(ast::ElseBranch::Block(block)) => {
186 for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
193 ast::Expr::LoopExpr(l) => {
194 for_each_break_expr(l.label(), l.loop_body().and_then(|it| it.stmt_list()), &mut |b| {
195 cb(&ast::Expr::BreakExpr(b))
198 ast::Expr::MatchExpr(m) => {
199 if let Some(arms) = m.match_arm_list() {
200 arms.arms().filter_map(|arm| arm.expr()).for_each(|e| for_each_tail_expr(&e, cb));
203 ast::Expr::ArrayExpr(_)
204 | ast::Expr::AwaitExpr(_)
205 | ast::Expr::BinExpr(_)
206 | ast::Expr::BoxExpr(_)
207 | ast::Expr::BreakExpr(_)
208 | ast::Expr::CallExpr(_)
209 | ast::Expr::CastExpr(_)
210 | ast::Expr::ClosureExpr(_)
211 | ast::Expr::ContinueExpr(_)
212 | ast::Expr::FieldExpr(_)
213 | ast::Expr::ForExpr(_)
214 | ast::Expr::IndexExpr(_)
215 | ast::Expr::Literal(_)
216 | ast::Expr::MacroCall(_)
217 | ast::Expr::MacroStmts(_)
218 | ast::Expr::MethodCallExpr(_)
219 | ast::Expr::ParenExpr(_)
220 | ast::Expr::PathExpr(_)
221 | ast::Expr::PrefixExpr(_)
222 | ast::Expr::RangeExpr(_)
223 | ast::Expr::RecordExpr(_)
224 | ast::Expr::RefExpr(_)
225 | ast::Expr::ReturnExpr(_)
226 | ast::Expr::TryExpr(_)
227 | ast::Expr::TupleExpr(_)
228 | ast::Expr::WhileExpr(_)
229 | ast::Expr::LetExpr(_)
230 | ast::Expr::YieldExpr(_) => cb(expr),
234 /// Calls `cb` on each break expr inside of `body` that is applicable for the given label.
235 pub fn for_each_break_expr(
236 label: Option<ast::Label>,
237 body: Option<ast::StmtList>,
238 cb: &mut dyn FnMut(ast::BreakExpr),
240 let label = label.and_then(|lbl| lbl.lifetime());
242 if let Some(b) = body {
243 let preorder = &mut b.syntax().preorder();
244 let ev_as_expr = |ev| match ev {
245 WalkEvent::Enter(it) => Some(WalkEvent::Enter(ast::Expr::cast(it)?)),
246 WalkEvent::Leave(it) => Some(WalkEvent::Leave(ast::Expr::cast(it)?)),
248 let eq_label = |lt: Option<ast::Lifetime>| {
249 lt.zip(label.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
251 while let Some(node) = preorder.find_map(ev_as_expr) {
253 WalkEvent::Enter(expr) => match expr {
254 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
257 ast::Expr::BlockExpr(e) if e.label().is_some() => depth += 1,
258 ast::Expr::BreakExpr(b)
259 if (depth == 0 && b.lifetime().is_none()) || eq_label(b.lifetime()) =>
265 WalkEvent::Leave(expr) => match expr {
266 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
269 ast::Expr::BlockExpr(e) if e.label().is_some() => depth -= 1,
277 /// Checks if the given lint is equal or is contained by the other lint which may or may not be a group.
278 pub fn lint_eq_or_in_group(lint: &str, lint_is: &str) -> bool {
283 if let Some(group) = generated_lints::DEFAULT_LINT_GROUPS
285 .chain(generated_lints::CLIPPY_LINT_GROUPS.iter())
286 .chain(generated_lints::RUSTDOC_LINT_GROUPS.iter())
287 .find(|&check| check.lint.label == lint_is)
289 group.children.contains(&lint)
295 /// Parses the input token tree as comma separated plain paths.
296 pub fn parse_tt_as_comma_sep_paths(input: ast::TokenTree) -> Option<Vec<ast::Path>> {
297 let r_paren = input.r_paren_token();
299 input.syntax().children_with_tokens().skip(1).map_while(|it| match it.into_token() {
300 // seeing a keyword means the attribute is unclosed so stop parsing here
301 Some(tok) if tok.kind().is_keyword() => None,
302 // don't include the right token tree parenthesis if it exists
303 tok @ Some(_) if tok == r_paren => None,
304 // only nodes that we can find are other TokenTrees, those are unexpected in this parse though
306 Some(tok) => Some(tok),
308 let input_expressions = tokens.into_iter().group_by(|tok| tok.kind() == T![,]);
309 let paths = input_expressions
311 .filter_map(|(is_sep, group)| (!is_sep).then(|| group))
312 .filter_map(|mut tokens| {
313 syntax::hacks::parse_expr_from_str(&tokens.join("")).and_then(|expr| match expr {
314 ast::Expr::PathExpr(it) => it.path(),