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| {
124 cb(&ast::Expr::BreakExpr(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| {
154 cb(&ast::Expr::BreakExpr(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, cb));
162 ast::Expr::ArrayExpr(_)
163 | ast::Expr::AwaitExpr(_)
164 | ast::Expr::BinExpr(_)
165 | ast::Expr::BoxExpr(_)
166 | ast::Expr::BreakExpr(_)
167 | ast::Expr::CallExpr(_)
168 | ast::Expr::CastExpr(_)
169 | ast::Expr::ClosureExpr(_)
170 | ast::Expr::ContinueExpr(_)
171 | ast::Expr::FieldExpr(_)
172 | ast::Expr::ForExpr(_)
173 | ast::Expr::IndexExpr(_)
174 | ast::Expr::Literal(_)
175 | ast::Expr::MacroCall(_)
176 | ast::Expr::MacroStmts(_)
177 | ast::Expr::MethodCallExpr(_)
178 | ast::Expr::ParenExpr(_)
179 | ast::Expr::PathExpr(_)
180 | ast::Expr::PrefixExpr(_)
181 | ast::Expr::RangeExpr(_)
182 | ast::Expr::RecordExpr(_)
183 | ast::Expr::RefExpr(_)
184 | ast::Expr::ReturnExpr(_)
185 | ast::Expr::TryExpr(_)
186 | ast::Expr::TupleExpr(_)
187 | ast::Expr::WhileExpr(_)
188 | ast::Expr::LetExpr(_)
189 | ast::Expr::YieldExpr(_) => cb(expr),
193 /// Calls `cb` on each break expr inside of `body` that is applicable for the given label.
194 pub fn for_each_break_expr(
195 label: Option<ast::Label>,
196 body: Option<ast::StmtList>,
197 cb: &mut dyn FnMut(ast::BreakExpr),
199 let label = label.and_then(|lbl| lbl.lifetime());
201 if let Some(b) = body {
202 let preorder = &mut b.syntax().preorder();
203 let ev_as_expr = |ev| match ev {
204 WalkEvent::Enter(it) => Some(WalkEvent::Enter(ast::Expr::cast(it)?)),
205 WalkEvent::Leave(it) => Some(WalkEvent::Leave(ast::Expr::cast(it)?)),
207 let eq_label = |lt: Option<ast::Lifetime>| {
208 lt.zip(label.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
210 while let Some(node) = preorder.find_map(ev_as_expr) {
212 WalkEvent::Enter(expr) => match expr {
213 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
216 ast::Expr::BlockExpr(e) if e.label().is_some() => depth += 1,
217 ast::Expr::BreakExpr(b)
218 if (depth == 0 && b.lifetime().is_none()) || eq_label(b.lifetime()) =>
224 WalkEvent::Leave(expr) => match expr {
225 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
228 ast::Expr::BlockExpr(e) if e.label().is_some() => depth -= 1,
236 /// Checks if the given lint is equal or is contained by the other lint which may or may not be a group.
237 pub fn lint_eq_or_in_group(lint: &str, lint_is: &str) -> bool {
242 if let Some(group) = generated_lints::DEFAULT_LINT_GROUPS
244 .chain(generated_lints::CLIPPY_LINT_GROUPS.iter())
245 .chain(generated_lints::RUSTDOC_LINT_GROUPS.iter())
246 .find(|&check| check.lint.label == lint_is)
248 group.children.contains(&lint)
254 /// Parses the input token tree as comma separated plain paths.
255 pub fn parse_tt_as_comma_sep_paths(input: ast::TokenTree) -> Option<Vec<ast::Path>> {
256 let r_paren = input.r_paren_token();
258 input.syntax().children_with_tokens().skip(1).map_while(|it| match it.into_token() {
259 // seeing a keyword means the attribute is unclosed so stop parsing here
260 Some(tok) if tok.kind().is_keyword() => None,
261 // don't include the right token tree parenthesis if it exists
262 tok @ Some(_) if tok == r_paren => None,
263 // only nodes that we can find are other TokenTrees, those are unexpected in this parse though
265 Some(tok) => Some(tok),
267 let input_expressions = tokens.into_iter().group_by(|tok| tok.kind() == T![,]);
268 let paths = input_expressions
270 .filter_map(|(is_sep, group)| (!is_sep).then(|| group))
271 .filter_map(|mut tokens| {
272 syntax::hacks::parse_expr_from_str(&tokens.join("")).and_then(|expr| match expr {
273 ast::Expr::PathExpr(it) => it.path(),