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, Preorder, RustLanguage, 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 /// Picks the token with the highest rank returned by the passed in function.
36 pub fn pick_best_token(
37 tokens: TokenAtOffset<SyntaxToken>,
38 f: impl Fn(SyntaxKind) -> usize,
39 ) -> Option<SyntaxToken> {
40 tokens.max_by_key(move |t| f(t.kind()))
42 pub fn pick_token<T: AstToken>(mut tokens: TokenAtOffset<SyntaxToken>) -> Option<T> {
43 tokens.find_map(T::cast)
46 /// Converts the mod path struct into its ast representation.
47 pub fn mod_path_to_ast(path: &hir::ModPath) -> ast::Path {
48 let _p = profile::span("mod_path_to_ast");
50 let mut segments = Vec::new();
51 let mut is_abs = false;
53 hir::PathKind::Plain => {}
54 hir::PathKind::Super(0) => segments.push(make::path_segment_self()),
55 hir::PathKind::Super(n) => segments.extend((0..n).map(|_| make::path_segment_super())),
56 hir::PathKind::DollarCrate(_) | hir::PathKind::Crate => {
57 segments.push(make::path_segment_crate())
59 hir::PathKind::Abs => is_abs = true,
65 .map(|segment| make::path_segment(make::name_ref(&segment.to_smol_str()))),
67 make::path_from_segments(segments, is_abs)
70 /// Iterates all `ModuleDef`s and `Impl` blocks of the given file.
71 pub fn visit_file_defs(
72 sema: &Semantics<RootDatabase>,
74 cb: &mut dyn FnMut(Definition),
77 let module = match sema.to_module_def(file_id) {
81 let mut defs: VecDeque<_> = module.declarations(db).into();
82 while let Some(def) = defs.pop_front() {
83 if let ModuleDef::Module(submodule) = def {
84 if let hir::ModuleSource::Module(_) = submodule.definition_source(db).value {
85 defs.extend(submodule.declarations(db));
86 submodule.impl_defs(db).into_iter().for_each(|impl_| cb(impl_.into()));
91 module.impl_defs(db).into_iter().for_each(|impl_| cb(impl_.into()));
94 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
95 pub struct SnippetCap {
100 pub const fn new(allow_snippets: bool) -> Option<SnippetCap> {
102 Some(SnippetCap { _private: () })
109 /// Calls `cb` on each expression inside `expr` that is at "tail position".
110 /// Does not walk into `break` or `return` expressions.
111 /// Note that modifying the tree while iterating it will cause undefined iteration which might
112 /// potentially results in an out of bounds panic.
113 pub fn for_each_tail_expr(expr: &ast::Expr, cb: &mut dyn FnMut(&ast::Expr)) {
115 ast::Expr::BlockExpr(b) => {
118 ast::BlockModifier::Async(_)
119 | ast::BlockModifier::Try(_)
120 | ast::BlockModifier::Const(_),
121 ) => return cb(expr),
123 Some(ast::BlockModifier::Label(label)) => {
124 for_each_break_expr(Some(label), b.stmt_list(), &mut |b| {
125 cb(&ast::Expr::BreakExpr(b))
128 Some(ast::BlockModifier::Unsafe(_)) => (),
131 if let Some(stmt_list) = b.stmt_list() {
132 if let Some(e) = stmt_list.tail_expr() {
133 for_each_tail_expr(&e, cb);
137 ast::Expr::IfExpr(if_) => {
138 let mut if_ = if_.clone();
140 if let Some(block) = if_.then_branch() {
141 for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
143 match if_.else_branch() {
144 Some(ast::ElseBranch::IfExpr(it)) => if_ = it,
145 Some(ast::ElseBranch::Block(block)) => {
146 for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
153 ast::Expr::LoopExpr(l) => {
154 for_each_break_expr(l.label(), l.loop_body().and_then(|it| it.stmt_list()), &mut |b| {
155 cb(&ast::Expr::BreakExpr(b))
158 ast::Expr::MatchExpr(m) => {
159 if let Some(arms) = m.match_arm_list() {
160 arms.arms().filter_map(|arm| arm.expr()).for_each(|e| for_each_tail_expr(&e, cb));
163 ast::Expr::ArrayExpr(_)
164 | ast::Expr::AwaitExpr(_)
165 | ast::Expr::BinExpr(_)
166 | ast::Expr::BoxExpr(_)
167 | ast::Expr::BreakExpr(_)
168 | ast::Expr::CallExpr(_)
169 | ast::Expr::CastExpr(_)
170 | ast::Expr::ClosureExpr(_)
171 | ast::Expr::ContinueExpr(_)
172 | ast::Expr::FieldExpr(_)
173 | ast::Expr::ForExpr(_)
174 | ast::Expr::IndexExpr(_)
175 | ast::Expr::Literal(_)
176 | ast::Expr::MacroCall(_)
177 | ast::Expr::MacroStmts(_)
178 | ast::Expr::MethodCallExpr(_)
179 | ast::Expr::ParenExpr(_)
180 | ast::Expr::PathExpr(_)
181 | ast::Expr::PrefixExpr(_)
182 | ast::Expr::RangeExpr(_)
183 | ast::Expr::RecordExpr(_)
184 | ast::Expr::RefExpr(_)
185 | ast::Expr::ReturnExpr(_)
186 | ast::Expr::TryExpr(_)
187 | ast::Expr::TupleExpr(_)
188 | ast::Expr::WhileExpr(_)
189 | ast::Expr::LetExpr(_)
190 | ast::Expr::YieldExpr(_) => cb(expr),
194 pub fn for_each_break_and_continue_expr(
195 label: Option<ast::Label>,
196 body: Option<ast::StmtList>,
197 cb: &mut dyn FnMut(ast::Expr),
199 let label = label.and_then(|lbl| lbl.lifetime());
200 if let Some(b) = body {
201 let tree_depth_iterator = TreeWithDepthIterator::new(b);
202 for (expr, depth) in tree_depth_iterator {
204 ast::Expr::BreakExpr(b)
205 if (depth == 0 && b.lifetime().is_none())
206 || eq_label_lt(&label, &b.lifetime()) =>
208 cb(ast::Expr::BreakExpr(b));
210 ast::Expr::ContinueExpr(c)
211 if (depth == 0 && c.lifetime().is_none())
212 || eq_label_lt(&label, &c.lifetime()) =>
214 cb(ast::Expr::ContinueExpr(c));
222 fn for_each_break_expr(
223 label: Option<ast::Label>,
224 body: Option<ast::StmtList>,
225 cb: &mut dyn FnMut(ast::BreakExpr),
227 let label = label.and_then(|lbl| lbl.lifetime());
228 if let Some(b) = body {
229 let tree_depth_iterator = TreeWithDepthIterator::new(b);
230 for (expr, depth) in tree_depth_iterator {
232 ast::Expr::BreakExpr(b)
233 if (depth == 0 && b.lifetime().is_none())
234 || eq_label_lt(&label, &b.lifetime()) =>
244 fn eq_label_lt(lt1: &Option<ast::Lifetime>, lt2: &Option<ast::Lifetime>) -> bool {
245 lt1.as_ref().zip(lt2.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
248 struct TreeWithDepthIterator {
249 preorder: Preorder<RustLanguage>,
253 impl TreeWithDepthIterator {
254 fn new(body: ast::StmtList) -> Self {
255 let preorder = body.syntax().preorder();
256 Self { preorder, depth: 0 }
260 impl<'a> Iterator for TreeWithDepthIterator {
261 type Item = (ast::Expr, i32);
263 fn next(&mut self) -> Option<Self::Item> {
264 while let Some((event, expr)) = self.preorder.find_map(|ev| match ev {
265 WalkEvent::Enter(it) => Some(WalkEvent::Enter(())).zip(ast::Expr::cast(it)),
266 WalkEvent::Leave(it) => Some(WalkEvent::Leave(())).zip(ast::Expr::cast(it)),
268 match (event, expr) {
271 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_),
277 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_),
281 (WalkEvent::Enter(_), ast::Expr::BlockExpr(e)) if e.label().is_some() => {
284 (WalkEvent::Leave(_), ast::Expr::BlockExpr(e)) if e.label().is_some() => {
287 (WalkEvent::Enter(_), expr) => return Some((expr, self.depth)),
295 /// Checks if the given lint is equal or is contained by the other lint which may or may not be a group.
296 pub fn lint_eq_or_in_group(lint: &str, lint_is: &str) -> bool {
301 if let Some(group) = generated_lints::DEFAULT_LINT_GROUPS
303 .chain(generated_lints::CLIPPY_LINT_GROUPS.iter())
304 .chain(generated_lints::RUSTDOC_LINT_GROUPS.iter())
305 .find(|&check| check.lint.label == lint_is)
307 group.children.contains(&lint)
313 /// Parses the input token tree as comma separated plain paths.
314 pub fn parse_tt_as_comma_sep_paths(input: ast::TokenTree) -> Option<Vec<ast::Path>> {
315 let r_paren = input.r_paren_token();
317 input.syntax().children_with_tokens().skip(1).map_while(|it| match it.into_token() {
318 // seeing a keyword means the attribute is unclosed so stop parsing here
319 Some(tok) if tok.kind().is_keyword() => None,
320 // don't include the right token tree parenthesis if it exists
321 tok @ Some(_) if tok == r_paren => None,
322 // only nodes that we can find are other TokenTrees, those are unexpected in this parse though
324 Some(tok) => Some(tok),
326 let input_expressions = tokens.into_iter().group_by(|tok| tok.kind() == T![,]);
327 let paths = input_expressions
329 .filter_map(|(is_sep, group)| (!is_sep).then(|| group))
330 .filter_map(|mut tokens| {
331 syntax::hacks::parse_expr_from_str(&tokens.join("")).and_then(|expr| match expr {
332 ast::Expr::PathExpr(it) => it.path(),