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;
15 use hir::{ItemInNs, MacroDef, ModuleDef, Name, Semantics};
16 use itertools::Itertools;
18 ast::{self, make, HasLoopBody},
19 AstNode, AstToken, SyntaxKind, SyntaxToken, TokenAtOffset, WalkEvent, T,
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 /// Picks the token with the highest rank returned by the passed in function.
35 pub fn pick_best_token(
36 tokens: TokenAtOffset<SyntaxToken>,
37 f: impl Fn(SyntaxKind) -> usize,
38 ) -> Option<SyntaxToken> {
39 tokens.max_by_key(move |t| f(t.kind()))
41 pub fn pick_token<T: AstToken>(mut tokens: TokenAtOffset<SyntaxToken>) -> Option<T> {
42 tokens.find_map(T::cast)
45 /// Converts the mod path struct into its ast representation.
46 pub fn mod_path_to_ast(path: &hir::ModPath) -> ast::Path {
47 let _p = profile::span("mod_path_to_ast");
49 let mut segments = Vec::new();
50 let mut is_abs = false;
52 hir::PathKind::Plain => {}
53 hir::PathKind::Super(0) => segments.push(make::path_segment_self()),
54 hir::PathKind::Super(n) => segments.extend((0..n).map(|_| make::path_segment_super())),
55 hir::PathKind::DollarCrate(_) | hir::PathKind::Crate => {
56 segments.push(make::path_segment_crate())
58 hir::PathKind::Abs => is_abs = true,
64 .map(|segment| make::path_segment(make::name_ref(&segment.to_smol_str()))),
66 make::path_from_segments(segments, is_abs)
69 /// Iterates all `ModuleDef`s and `Impl` blocks of the given file.
70 pub fn visit_file_defs(
71 sema: &Semantics<RootDatabase>,
73 cb: &mut dyn FnMut(Definition),
76 let module = match sema.to_module_def(file_id) {
80 let mut defs: VecDeque<_> = module.declarations(db).into();
81 while let Some(def) = defs.pop_front() {
82 if let ModuleDef::Module(submodule) = def {
83 if let hir::ModuleSource::Module(_) = submodule.definition_source(db).value {
84 defs.extend(submodule.declarations(db));
85 submodule.impl_defs(db).into_iter().for_each(|impl_| cb(impl_.into()));
90 module.impl_defs(db).into_iter().for_each(|impl_| cb(impl_.into()));
93 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
94 pub struct SnippetCap {
99 pub const fn new(allow_snippets: bool) -> Option<SnippetCap> {
101 Some(SnippetCap { _private: () })
108 /// Calls `cb` on each expression inside `expr` that is at "tail position".
109 /// Does not walk into `break` or `return` expressions.
110 /// Note that modifying the tree while iterating it will cause undefined iteration which might
111 /// potentially results in an out of bounds panic.
112 pub fn for_each_tail_expr(expr: &ast::Expr, cb: &mut dyn FnMut(&ast::Expr)) {
114 ast::Expr::BlockExpr(b) => {
117 ast::BlockModifier::Async(_)
118 | ast::BlockModifier::Try(_)
119 | ast::BlockModifier::Const(_),
120 ) => return cb(expr),
122 Some(ast::BlockModifier::Label(label)) => {
123 for_each_break_expr(Some(label), b.stmt_list(), &mut |b| {
127 Some(ast::BlockModifier::Unsafe(_)) => (),
130 if let Some(stmt_list) = b.stmt_list() {
131 if let Some(e) = stmt_list.tail_expr() {
132 for_each_tail_expr(&e, cb);
136 ast::Expr::IfExpr(if_) => {
137 let mut if_ = if_.clone();
139 if let Some(block) = if_.then_branch() {
140 for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
142 match if_.else_branch() {
143 Some(ast::ElseBranch::IfExpr(it)) => if_ = it,
144 Some(ast::ElseBranch::Block(block)) => {
145 for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
152 ast::Expr::LoopExpr(l) => {
153 for_each_break_expr(l.label(), l.loop_body().and_then(|it| it.stmt_list()), &mut |b| {
157 ast::Expr::MatchExpr(m) => {
158 if let Some(arms) = m.match_arm_list() {
159 arms.arms().filter_map(|arm| arm.expr()).for_each(|e| for_each_tail_expr(&e, &mut |b| {
164 ast::Expr::ArrayExpr(_)
165 | ast::Expr::AwaitExpr(_)
166 | ast::Expr::BinExpr(_)
167 | ast::Expr::BoxExpr(_)
168 | ast::Expr::BreakExpr(_)
169 | ast::Expr::CallExpr(_)
170 | ast::Expr::CastExpr(_)
171 | ast::Expr::ClosureExpr(_)
172 | ast::Expr::ContinueExpr(_)
173 | ast::Expr::FieldExpr(_)
174 | ast::Expr::ForExpr(_)
175 | ast::Expr::IndexExpr(_)
176 | ast::Expr::Literal(_)
177 | ast::Expr::MacroCall(_)
178 | ast::Expr::MacroStmts(_)
179 | ast::Expr::MethodCallExpr(_)
180 | ast::Expr::ParenExpr(_)
181 | ast::Expr::PathExpr(_)
182 | ast::Expr::PrefixExpr(_)
183 | ast::Expr::RangeExpr(_)
184 | ast::Expr::RecordExpr(_)
185 | ast::Expr::RefExpr(_)
186 | ast::Expr::ReturnExpr(_)
187 | ast::Expr::TryExpr(_)
188 | ast::Expr::TupleExpr(_)
189 | ast::Expr::WhileExpr(_)
190 | ast::Expr::LetExpr(_)
191 | ast::Expr::YieldExpr(_) => cb(expr),
195 /// Calls `cb` on each break expr inside of `body` that is applicable for the given label.
196 pub fn for_each_break_expr(
197 label: Option<ast::Label>,
198 body: Option<ast::StmtList>,
199 cb: &mut dyn FnMut(ast::Expr),
201 let label = label.and_then(|lbl| lbl.lifetime());
203 if let Some(b) = body {
204 let preorder = &mut b.syntax().preorder();
205 let ev_as_expr = |ev| match ev {
206 WalkEvent::Enter(it) => Some(WalkEvent::Enter(ast::Expr::cast(it)?)),
207 WalkEvent::Leave(it) => Some(WalkEvent::Leave(ast::Expr::cast(it)?)),
209 let eq_label = |lt: Option<ast::Lifetime>| {
210 lt.zip(label.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
212 while let Some(node) = preorder.find_map(ev_as_expr) {
214 WalkEvent::Enter(expr) => match expr {
215 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
218 ast::Expr::BlockExpr(e) if e.label().is_some() => depth += 1,
219 ast::Expr::BreakExpr(b)
220 if (depth == 0 && b.lifetime().is_none()) || eq_label(b.lifetime()) =>
222 cb(ast::Expr::BreakExpr(b));
226 WalkEvent::Leave(expr) => match expr {
227 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
230 ast::Expr::BlockExpr(e) if e.label().is_some() => depth -= 1,
238 /// Checks if the given lint is equal or is contained by the other lint which may or may not be a group.
239 pub fn lint_eq_or_in_group(lint: &str, lint_is: &str) -> bool {
244 if let Some(group) = generated_lints::DEFAULT_LINT_GROUPS
246 .chain(generated_lints::CLIPPY_LINT_GROUPS.iter())
247 .chain(generated_lints::RUSTDOC_LINT_GROUPS.iter())
248 .find(|&check| check.lint.label == lint_is)
250 group.children.contains(&lint)
256 /// Parses the input token tree as comma separated plain paths.
257 pub fn parse_tt_as_comma_sep_paths(input: ast::TokenTree) -> Option<Vec<ast::Path>> {
258 let r_paren = input.r_paren_token();
260 input.syntax().children_with_tokens().skip(1).map_while(|it| match it.into_token() {
261 // seeing a keyword means the attribute is unclosed so stop parsing here
262 Some(tok) if tok.kind().is_keyword() => None,
263 // don't include the right token tree parenthesis if it exists
264 tok @ Some(_) if tok == r_paren => None,
265 // only nodes that we can find are other TokenTrees, those are unexpected in this parse though
267 Some(tok) => Some(tok),
269 let input_expressions = tokens.into_iter().group_by(|tok| tok.kind() == T![,]);
270 let paths = input_expressions
272 .filter_map(|(is_sep, group)| (!is_sep).then(|| group))
273 .filter_map(|mut tokens| {
274 syntax::hacks::parse_expr_from_str(&tokens.join("")).and_then(|expr| match expr {
275 ast::Expr::PathExpr(it) => it.path(),