1 //! A module with ide helpers for high-level ide features.
3 pub mod generated_lints;
10 use std::{collections::VecDeque, iter};
13 use hir::{ItemInNs, MacroDef, ModuleDef, Name, PathResolution, Semantics};
14 use itertools::Itertools;
16 ast::{self, make, HasLoopBody, Ident},
17 AstNode, AstToken, Direction, SyntaxElement, SyntaxKind, SyntaxToken, TokenAtOffset, WalkEvent,
21 use crate::{defs::Definition, RootDatabase};
23 pub use self::famous_defs::FamousDefs;
25 pub fn item_name(db: &RootDatabase, item: ItemInNs) -> Option<Name> {
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),
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.
36 /// The returned path is synthesized from TokenTree tokens and as such cannot be used with the [`Semantics`].
37 pub fn get_path_in_derive_attr(
38 sema: &hir::Semantics<RootDatabase>,
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()) {
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 {
56 .siblings_with_tokens(Direction::Prev)
57 .filter_map(SyntaxElement::into_token)
58 .take_while(|tok| tok.kind() != T!['('] && tok.kind() != T![,])
60 let path_tokens = first
61 .siblings_with_tokens(Direction::Next)
62 .filter_map(SyntaxElement::into_token)
63 .take_while(|tok| tok != cursor);
65 ast::Path::parse(&path_tokens.chain(iter::once(cursor.clone())).join("")).ok()
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.
70 pub fn try_resolve_derive_input(
71 sema: &hir::Semantics<RootDatabase>,
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,
83 .speculative_resolve(&path)
84 .filter(|res| matches!(res, PathResolution::Def(ModuleDef::Module(_)))),
88 /// Picks the token with the highest rank returned by the passed in function.
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()))
96 /// Converts the mod path struct into its ast representation.
97 pub fn mod_path_to_ast(path: &hir::ModPath) -> ast::Path {
98 let _p = profile::span("mod_path_to_ast");
100 let mut segments = Vec::new();
101 let mut is_abs = false;
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())
109 hir::PathKind::Abs => is_abs = true,
115 .map(|segment| make::path_segment(make::name_ref(&segment.to_smol_str()))),
117 make::path_from_segments(segments, is_abs)
120 /// Iterates all `ModuleDef`s and `Impl` blocks of the given file.
121 pub fn visit_file_defs(
122 sema: &Semantics<RootDatabase>,
124 cb: &mut dyn FnMut(Definition),
127 let module = match sema.to_module_def(file_id) {
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()));
141 module.impl_defs(db).into_iter().for_each(|impl_| cb(impl_.into()));
144 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
145 pub struct SnippetCap {
150 pub const fn new(allow_snippets: bool) -> Option<SnippetCap> {
152 Some(SnippetCap { _private: () })
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.
163 pub fn for_each_tail_expr(expr: &ast::Expr, cb: &mut dyn FnMut(&ast::Expr)) {
165 ast::Expr::BlockExpr(b) => {
168 ast::BlockModifier::Async(_)
169 | ast::BlockModifier::Try(_)
170 | ast::BlockModifier::Const(_),
171 ) => return cb(expr),
173 Some(ast::BlockModifier::Label(label)) => {
174 for_each_break_expr(Some(label), b.stmt_list(), &mut |b| {
175 cb(&ast::Expr::BreakExpr(b))
178 Some(ast::BlockModifier::Unsafe(_)) => (),
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);
187 ast::Expr::IfExpr(if_) => {
188 let mut if_ = if_.clone();
190 if let Some(block) = if_.then_branch() {
191 for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
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);
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))
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));
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),
243 /// Calls `cb` on each break expr inside of `body` that is applicable for the given label.
244 pub fn for_each_break_expr(
245 label: Option<ast::Label>,
246 body: Option<ast::StmtList>,
247 cb: &mut dyn FnMut(ast::BreakExpr),
249 let label = label.and_then(|lbl| lbl.lifetime());
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)?)),
257 let eq_label = |lt: Option<ast::Lifetime>| {
258 lt.zip(label.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
260 while let Some(node) = preorder.find_map(ev_as_expr) {
262 WalkEvent::Enter(expr) => match expr {
263 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
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()) =>
274 WalkEvent::Leave(expr) => match expr {
275 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
278 ast::Expr::BlockExpr(e) if e.label().is_some() => depth -= 1,
286 /// Checks if the given lint is equal or is contained by the other lint which may or may not be a group.
287 pub fn lint_eq_or_in_group(lint: &str, lint_is: &str) -> bool {
292 if let Some(group) = generated_lints::DEFAULT_LINT_GROUPS
294 .chain(generated_lints::CLIPPY_LINT_GROUPS.iter())
295 .chain(generated_lints::RUSTDOC_LINT_GROUPS.iter())
296 .find(|&check| check.lint.label == lint_is)
298 group.children.contains(&lint)