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()))
85 pub fn pick_token<T: AstToken>(mut tokens: TokenAtOffset<SyntaxToken>) -> Option<T> {
86 tokens.find_map(T::cast)
89 /// Converts the mod path struct into its ast representation.
90 pub fn mod_path_to_ast(path: &hir::ModPath) -> ast::Path {
91 let _p = profile::span("mod_path_to_ast");
93 let mut segments = Vec::new();
94 let mut is_abs = false;
96 hir::PathKind::Plain => {}
97 hir::PathKind::Super(0) => segments.push(make::path_segment_self()),
98 hir::PathKind::Super(n) => segments.extend((0..n).map(|_| make::path_segment_super())),
99 hir::PathKind::DollarCrate(_) | hir::PathKind::Crate => {
100 segments.push(make::path_segment_crate())
102 hir::PathKind::Abs => is_abs = true,
108 .map(|segment| make::path_segment(make::name_ref(&segment.to_smol_str()))),
110 make::path_from_segments(segments, is_abs)
113 /// Iterates all `ModuleDef`s and `Impl` blocks of the given file.
114 pub fn visit_file_defs(
115 sema: &Semantics<RootDatabase>,
117 cb: &mut dyn FnMut(Definition),
120 let module = match sema.to_module_def(file_id) {
124 let mut defs: VecDeque<_> = module.declarations(db).into();
125 while let Some(def) = defs.pop_front() {
126 if let ModuleDef::Module(submodule) = def {
127 if let hir::ModuleSource::Module(_) = submodule.definition_source(db).value {
128 defs.extend(submodule.declarations(db));
129 submodule.impl_defs(db).into_iter().for_each(|impl_| cb(impl_.into()));
134 module.impl_defs(db).into_iter().for_each(|impl_| cb(impl_.into()));
137 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
138 pub struct SnippetCap {
143 pub const fn new(allow_snippets: bool) -> Option<SnippetCap> {
145 Some(SnippetCap { _private: () })
152 /// Calls `cb` on each expression inside `expr` that is at "tail position".
153 /// Does not walk into `break` or `return` expressions.
154 /// Note that modifying the tree while iterating it will cause undefined iteration which might
155 /// potentially results in an out of bounds panic.
156 pub fn for_each_tail_expr(expr: &ast::Expr, cb: &mut dyn FnMut(&ast::Expr)) {
158 ast::Expr::BlockExpr(b) => {
161 ast::BlockModifier::Async(_)
162 | ast::BlockModifier::Try(_)
163 | ast::BlockModifier::Const(_),
164 ) => return cb(expr),
166 Some(ast::BlockModifier::Label(label)) => {
167 for_each_break_expr(Some(label), b.stmt_list(), &mut |b| {
168 cb(&ast::Expr::BreakExpr(b))
171 Some(ast::BlockModifier::Unsafe(_)) => (),
174 if let Some(stmt_list) = b.stmt_list() {
175 if let Some(e) = stmt_list.tail_expr() {
176 for_each_tail_expr(&e, cb);
180 ast::Expr::IfExpr(if_) => {
181 let mut if_ = if_.clone();
183 if let Some(block) = if_.then_branch() {
184 for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
186 match if_.else_branch() {
187 Some(ast::ElseBranch::IfExpr(it)) => if_ = it,
188 Some(ast::ElseBranch::Block(block)) => {
189 for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
196 ast::Expr::LoopExpr(l) => {
197 for_each_break_expr(l.label(), l.loop_body().and_then(|it| it.stmt_list()), &mut |b| {
198 cb(&ast::Expr::BreakExpr(b))
201 ast::Expr::MatchExpr(m) => {
202 if let Some(arms) = m.match_arm_list() {
203 arms.arms().filter_map(|arm| arm.expr()).for_each(|e| for_each_tail_expr(&e, cb));
206 ast::Expr::ArrayExpr(_)
207 | ast::Expr::AwaitExpr(_)
208 | ast::Expr::BinExpr(_)
209 | ast::Expr::BoxExpr(_)
210 | ast::Expr::BreakExpr(_)
211 | ast::Expr::CallExpr(_)
212 | ast::Expr::CastExpr(_)
213 | ast::Expr::ClosureExpr(_)
214 | ast::Expr::ContinueExpr(_)
215 | ast::Expr::FieldExpr(_)
216 | ast::Expr::ForExpr(_)
217 | ast::Expr::IndexExpr(_)
218 | ast::Expr::Literal(_)
219 | ast::Expr::MacroCall(_)
220 | ast::Expr::MacroStmts(_)
221 | ast::Expr::MethodCallExpr(_)
222 | ast::Expr::ParenExpr(_)
223 | ast::Expr::PathExpr(_)
224 | ast::Expr::PrefixExpr(_)
225 | ast::Expr::RangeExpr(_)
226 | ast::Expr::RecordExpr(_)
227 | ast::Expr::RefExpr(_)
228 | ast::Expr::ReturnExpr(_)
229 | ast::Expr::TryExpr(_)
230 | ast::Expr::TupleExpr(_)
231 | ast::Expr::WhileExpr(_)
232 | ast::Expr::LetExpr(_)
233 | ast::Expr::YieldExpr(_) => cb(expr),
237 /// Calls `cb` on each break expr inside of `body` that is applicable for the given label.
238 pub fn for_each_break_expr(
239 label: Option<ast::Label>,
240 body: Option<ast::StmtList>,
241 cb: &mut dyn FnMut(ast::BreakExpr),
243 let label = label.and_then(|lbl| lbl.lifetime());
245 if let Some(b) = body {
246 let preorder = &mut b.syntax().preorder();
247 let ev_as_expr = |ev| match ev {
248 WalkEvent::Enter(it) => Some(WalkEvent::Enter(ast::Expr::cast(it)?)),
249 WalkEvent::Leave(it) => Some(WalkEvent::Leave(ast::Expr::cast(it)?)),
251 let eq_label = |lt: Option<ast::Lifetime>| {
252 lt.zip(label.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
254 while let Some(node) = preorder.find_map(ev_as_expr) {
256 WalkEvent::Enter(expr) => match expr {
257 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
260 ast::Expr::BlockExpr(e) if e.label().is_some() => depth += 1,
261 ast::Expr::BreakExpr(b)
262 if (depth == 0 && b.lifetime().is_none()) || eq_label(b.lifetime()) =>
268 WalkEvent::Leave(expr) => match expr {
269 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
272 ast::Expr::BlockExpr(e) if e.label().is_some() => depth -= 1,
280 /// Checks if the given lint is equal or is contained by the other lint which may or may not be a group.
281 pub fn lint_eq_or_in_group(lint: &str, lint_is: &str) -> bool {
286 if let Some(group) = generated_lints::DEFAULT_LINT_GROUPS
288 .chain(generated_lints::CLIPPY_LINT_GROUPS.iter())
289 .chain(generated_lints::RUSTDOC_LINT_GROUPS.iter())
290 .find(|&check| check.lint.label == lint_is)
292 group.children.contains(&lint)
298 /// Parses the input token tree as comma separated plain paths.
299 pub fn parse_tt_as_comma_sep_paths(input: ast::TokenTree) -> Option<Vec<ast::Path>> {
300 let r_paren = input.r_paren_token();
302 input.syntax().children_with_tokens().skip(1).map_while(|it| match it.into_token() {
303 // seeing a keyword means the attribute is unclosed so stop parsing here
304 Some(tok) if tok.kind().is_keyword() => None,
305 // don't include the right token tree parenthesis if it exists
306 tok @ Some(_) if tok == r_paren => None,
307 // only nodes that we can find are other TokenTrees, those are unexpected in this parse though
309 Some(tok) => Some(tok),
311 let input_expressions = tokens.into_iter().group_by(|tok| tok.kind() == T![,]);
312 let paths = input_expressions
314 .filter_map(|(is_sep, group)| (!is_sep).then(|| group))
315 .filter_map(|mut tokens| {
316 syntax::hacks::parse_expr_from_str(&tokens.join("")).and_then(|expr| match expr {
317 ast::Expr::PathExpr(it) => it.path(),