1 //! A module with ide helpers for high-level ide features.
3 pub mod generated_lints;
10 use std::{collections::VecDeque, iter};
14 use hir::{ItemInNs, MacroDef, ModuleDef, Name, PathResolution, Semantics};
15 use itertools::Itertools;
17 ast::{self, make, HasLoopBody, Ident},
18 AstNode, AstToken, Direction, SyntaxElement, SyntaxKind, SyntaxToken, TokenAtOffset, WalkEvent,
22 use crate::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 /// Parses and returns the derive path at the cursor position in the given attribute, if it is a derive.
35 /// This special case is required because the derive macro is a compiler builtin that discards the input derives.
37 /// The returned path is synthesized from TokenTree tokens and as such cannot be used with the [`Semantics`].
38 pub fn get_path_in_derive_attr(
39 sema: &hir::Semantics<RootDatabase>,
42 ) -> Option<ast::Path> {
43 let cursor = cursor.syntax();
44 let path = attr.path()?;
45 let tt = attr.token_tree()?;
46 if !tt.syntax().text_range().contains_range(cursor.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 {
57 .siblings_with_tokens(Direction::Prev)
58 .filter_map(SyntaxElement::into_token)
59 .take_while(|tok| tok.kind() != T!['('] && tok.kind() != T![,])
61 let path_tokens = first
62 .siblings_with_tokens(Direction::Next)
63 .filter_map(SyntaxElement::into_token)
64 .take_while(|tok| tok != cursor);
66 ast::Path::parse(&path_tokens.chain(iter::once(cursor.clone())).join("")).ok()
69 /// Parses and resolves the path at the cursor position in the given attribute, if it is a derive.
70 /// This special case is required because the derive macro is a compiler builtin that discards the input derives.
71 pub fn try_resolve_derive_input(
72 sema: &hir::Semantics<RootDatabase>,
75 ) -> Option<PathResolution> {
76 let path = get_path_in_derive_attr(sema, attr, cursor)?;
77 let scope = sema.scope(attr.syntax());
78 // FIXME: This double resolve shouldn't be necessary
79 // It's only here so we prefer macros over other namespaces
80 match scope.speculative_resolve_as_mac(&path) {
81 Some(mac) if mac.kind() == hir::MacroKind::Derive => Some(PathResolution::Macro(mac)),
82 Some(_) => return None,
84 .speculative_resolve(&path)
85 .filter(|res| matches!(res, PathResolution::Def(ModuleDef::Module(_)))),
89 /// Picks the token with the highest rank returned by the passed in function.
90 pub fn pick_best_token(
91 tokens: TokenAtOffset<SyntaxToken>,
92 f: impl Fn(SyntaxKind) -> usize,
93 ) -> Option<SyntaxToken> {
94 tokens.max_by_key(move |t| f(t.kind()))
97 /// Converts the mod path struct into its ast representation.
98 pub fn mod_path_to_ast(path: &hir::ModPath) -> ast::Path {
99 let _p = profile::span("mod_path_to_ast");
101 let mut segments = Vec::new();
102 let mut is_abs = false;
104 hir::PathKind::Plain => {}
105 hir::PathKind::Super(0) => segments.push(make::path_segment_self()),
106 hir::PathKind::Super(n) => segments.extend((0..n).map(|_| make::path_segment_super())),
107 hir::PathKind::DollarCrate(_) | hir::PathKind::Crate => {
108 segments.push(make::path_segment_crate())
110 hir::PathKind::Abs => is_abs = true,
116 .map(|segment| make::path_segment(make::name_ref(&segment.to_string()))),
118 make::path_from_segments(segments, is_abs)
121 /// Iterates all `ModuleDef`s and `Impl` blocks of the given file.
122 pub fn visit_file_defs(
123 sema: &Semantics<RootDatabase>,
125 cb: &mut dyn FnMut(Either<hir::ModuleDef, hir::Impl>),
128 let module = match sema.to_module_def(file_id) {
132 let mut defs: VecDeque<_> = module.declarations(db).into();
133 while let Some(def) = defs.pop_front() {
134 if let ModuleDef::Module(submodule) = def {
135 if let hir::ModuleSource::Module(_) = submodule.definition_source(db).value {
136 defs.extend(submodule.declarations(db));
137 submodule.impl_defs(db).into_iter().for_each(|impl_| cb(Either::Right(impl_)));
140 cb(Either::Left(def));
142 module.impl_defs(db).into_iter().for_each(|impl_| cb(Either::Right(impl_)));
145 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
146 pub struct SnippetCap {
151 pub const fn new(allow_snippets: bool) -> Option<SnippetCap> {
153 Some(SnippetCap { _private: () })
160 /// Calls `cb` on each expression inside `expr` that is at "tail position".
161 /// Does not walk into `break` or `return` expressions.
162 /// Note that modifying the tree while iterating it will cause undefined iteration which might
163 /// potentially results in an out of bounds panic.
164 pub fn for_each_tail_expr(expr: &ast::Expr, cb: &mut dyn FnMut(&ast::Expr)) {
166 ast::Expr::BlockExpr(b) => {
169 ast::BlockModifier::Async(_)
170 | ast::BlockModifier::Try(_)
171 | ast::BlockModifier::Const(_),
172 ) => return cb(expr),
174 Some(ast::BlockModifier::Label(label)) => {
175 for_each_break_expr(Some(label), b.stmt_list(), &mut |b| {
176 cb(&ast::Expr::BreakExpr(b))
179 Some(ast::BlockModifier::Unsafe(_)) => (),
182 if let Some(stmt_list) = b.stmt_list() {
183 if let Some(e) = stmt_list.tail_expr() {
184 for_each_tail_expr(&e, cb);
188 ast::Expr::IfExpr(if_) => {
189 let mut if_ = if_.clone();
191 if let Some(block) = if_.then_branch() {
192 for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
194 match if_.else_branch() {
195 Some(ast::ElseBranch::IfExpr(it)) => if_ = it,
196 Some(ast::ElseBranch::Block(block)) => {
197 for_each_tail_expr(&ast::Expr::BlockExpr(block), cb);
204 ast::Expr::LoopExpr(l) => {
205 for_each_break_expr(l.label(), l.loop_body().and_then(|it| it.stmt_list()), &mut |b| {
206 cb(&ast::Expr::BreakExpr(b))
209 ast::Expr::MatchExpr(m) => {
210 if let Some(arms) = m.match_arm_list() {
211 arms.arms().filter_map(|arm| arm.expr()).for_each(|e| for_each_tail_expr(&e, cb));
214 ast::Expr::ArrayExpr(_)
215 | ast::Expr::AwaitExpr(_)
216 | ast::Expr::BinExpr(_)
217 | ast::Expr::BoxExpr(_)
218 | ast::Expr::BreakExpr(_)
219 | ast::Expr::CallExpr(_)
220 | ast::Expr::CastExpr(_)
221 | ast::Expr::ClosureExpr(_)
222 | ast::Expr::ContinueExpr(_)
223 | ast::Expr::FieldExpr(_)
224 | ast::Expr::ForExpr(_)
225 | ast::Expr::IndexExpr(_)
226 | ast::Expr::Literal(_)
227 | ast::Expr::MacroCall(_)
228 | ast::Expr::MacroStmts(_)
229 | ast::Expr::MethodCallExpr(_)
230 | ast::Expr::ParenExpr(_)
231 | ast::Expr::PathExpr(_)
232 | ast::Expr::PrefixExpr(_)
233 | ast::Expr::RangeExpr(_)
234 | ast::Expr::RecordExpr(_)
235 | ast::Expr::RefExpr(_)
236 | ast::Expr::ReturnExpr(_)
237 | ast::Expr::TryExpr(_)
238 | ast::Expr::TupleExpr(_)
239 | ast::Expr::WhileExpr(_)
240 | ast::Expr::YieldExpr(_) => cb(expr),
244 /// Calls `cb` on each break expr inside of `body` that is applicable for the given label.
245 pub fn for_each_break_expr(
246 label: Option<ast::Label>,
247 body: Option<ast::StmtList>,
248 cb: &mut dyn FnMut(ast::BreakExpr),
250 let label = label.and_then(|lbl| lbl.lifetime());
252 if let Some(b) = body {
253 let preorder = &mut b.syntax().preorder();
254 let ev_as_expr = |ev| match ev {
255 WalkEvent::Enter(it) => Some(WalkEvent::Enter(ast::Expr::cast(it)?)),
256 WalkEvent::Leave(it) => Some(WalkEvent::Leave(ast::Expr::cast(it)?)),
258 let eq_label = |lt: Option<ast::Lifetime>| {
259 lt.zip(label.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
261 while let Some(node) = preorder.find_map(ev_as_expr) {
263 WalkEvent::Enter(expr) => match expr {
264 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
267 ast::Expr::BlockExpr(e) if e.label().is_some() => depth += 1,
268 ast::Expr::BreakExpr(b)
269 if (depth == 0 && b.lifetime().is_none()) || eq_label(b.lifetime()) =>
275 WalkEvent::Leave(expr) => match expr {
276 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
279 ast::Expr::BlockExpr(e) if e.label().is_some() => depth -= 1,