1 //! A module with ide helpers for high-level ide features.
6 pub mod generated_lints;
8 use std::collections::VecDeque;
12 use hir::{Crate, Enum, ItemInNs, MacroDef, Module, ModuleDef, Name, ScopeDef, Semantics, Trait};
14 ast::{self, make, LoopBodyOwner},
15 AstNode, SyntaxKind, SyntaxToken, TokenAtOffset, WalkEvent,
18 use crate::RootDatabase;
20 pub fn item_name(db: &RootDatabase, item: ItemInNs) -> Option<Name> {
22 ItemInNs::Types(module_def_id) => ModuleDef::from(module_def_id).name(db),
23 ItemInNs::Values(module_def_id) => ModuleDef::from(module_def_id).name(db),
24 ItemInNs::Macros(macro_def_id) => MacroDef::from(macro_def_id).name(db),
28 /// Picks the token with the highest rank returned by the passed in function.
29 pub fn pick_best_token(
30 tokens: TokenAtOffset<SyntaxToken>,
31 f: impl Fn(SyntaxKind) -> usize,
32 ) -> Option<SyntaxToken> {
33 tokens.max_by_key(move |t| f(t.kind()))
36 /// Converts the mod path struct into its ast representation.
37 pub fn mod_path_to_ast(path: &hir::ModPath) -> ast::Path {
38 let _p = profile::span("mod_path_to_ast");
40 let mut segments = Vec::new();
41 let mut is_abs = false;
43 hir::PathKind::Plain => {}
44 hir::PathKind::Super(0) => segments.push(make::path_segment_self()),
45 hir::PathKind::Super(n) => segments.extend((0..n).map(|_| make::path_segment_super())),
46 hir::PathKind::DollarCrate(_) | hir::PathKind::Crate => {
47 segments.push(make::path_segment_crate())
49 hir::PathKind::Abs => is_abs = true,
55 .map(|segment| make::path_segment(make::name_ref(&segment.to_string()))),
57 make::path_from_segments(segments, is_abs)
60 /// Iterates all `ModuleDef`s and `Impl` blocks of the given file.
61 pub fn visit_file_defs(
62 sema: &Semantics<RootDatabase>,
64 cb: &mut dyn FnMut(Either<hir::ModuleDef, hir::Impl>),
67 let module = match sema.to_module_def(file_id) {
71 let mut defs: VecDeque<_> = module.declarations(db).into();
72 while let Some(def) = defs.pop_front() {
73 if let ModuleDef::Module(submodule) = def {
74 if let hir::ModuleSource::Module(_) = submodule.definition_source(db).value {
75 defs.extend(submodule.declarations(db));
76 submodule.impl_defs(db).into_iter().for_each(|impl_| cb(Either::Right(impl_)));
79 cb(Either::Left(def));
81 module.impl_defs(db).into_iter().for_each(|impl_| cb(Either::Right(impl_)));
84 /// Helps with finding well-know things inside the standard library. This is
85 /// somewhat similar to the known paths infra inside hir, but it different; We
86 /// want to make sure that IDE specific paths don't become interesting inside
87 /// the compiler itself as well.
89 /// Note that, by default, rust-analyzer tests **do not** include core or std
90 /// libraries. If you are writing tests for functionality using [`FamousDefs`],
91 /// you'd want to include [minicore](test_utils::MiniCore) declaration at the
92 /// start of your tests:
95 /// //- minicore: iterator, ord, derive
97 pub struct FamousDefs<'a, 'b>(pub &'a Semantics<'b, RootDatabase>, pub Option<Crate>);
99 #[allow(non_snake_case)]
100 impl FamousDefs<'_, '_> {
101 pub fn std(&self) -> Option<Crate> {
102 self.find_crate("std")
105 pub fn core(&self) -> Option<Crate> {
106 self.find_crate("core")
109 pub fn core_cmp_Ord(&self) -> Option<Trait> {
110 self.find_trait("core:cmp:Ord")
113 pub fn core_convert_From(&self) -> Option<Trait> {
114 self.find_trait("core:convert:From")
117 pub fn core_convert_Into(&self) -> Option<Trait> {
118 self.find_trait("core:convert:Into")
121 pub fn core_option_Option(&self) -> Option<Enum> {
122 self.find_enum("core:option:Option")
125 pub fn core_default_Default(&self) -> Option<Trait> {
126 self.find_trait("core:default:Default")
129 pub fn core_iter_Iterator(&self) -> Option<Trait> {
130 self.find_trait("core:iter:traits:iterator:Iterator")
133 pub fn core_iter(&self) -> Option<Module> {
134 self.find_module("core:iter")
137 pub fn core_ops_Deref(&self) -> Option<Trait> {
138 self.find_trait("core:ops:Deref")
141 fn find_trait(&self, path: &str) -> Option<Trait> {
142 match self.find_def(path)? {
143 hir::ScopeDef::ModuleDef(hir::ModuleDef::Trait(it)) => Some(it),
148 fn find_enum(&self, path: &str) -> Option<Enum> {
149 match self.find_def(path)? {
150 hir::ScopeDef::ModuleDef(hir::ModuleDef::Adt(hir::Adt::Enum(it))) => Some(it),
155 fn find_module(&self, path: &str) -> Option<Module> {
156 match self.find_def(path)? {
157 hir::ScopeDef::ModuleDef(hir::ModuleDef::Module(it)) => Some(it),
162 fn find_crate(&self, name: &str) -> Option<Crate> {
166 krate.dependencies(db).into_iter().find(|dep| dep.name.to_string() == name)?.krate;
170 fn find_def(&self, path: &str) -> Option<ScopeDef> {
172 let mut path = path.split(':');
173 let trait_ = path.next_back()?;
174 let std_crate = path.next()?;
175 let std_crate = self.find_crate(std_crate)?;
176 let mut module = std_crate.root_module(db);
177 for segment in path {
178 module = module.children(db).find_map(|child| {
179 let name = child.name(db)?;
180 if name.to_string() == segment {
188 module.scope(db, None).into_iter().find(|(name, _def)| name.to_string() == trait_)?.1;
193 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
194 pub struct SnippetCap {
199 pub const fn new(allow_snippets: bool) -> Option<SnippetCap> {
201 Some(SnippetCap { _private: () })
208 /// Calls `cb` on each expression inside `expr` that is at "tail position".
209 pub fn for_each_tail_expr(expr: &ast::Expr, cb: &mut dyn FnMut(&ast::Expr)) {
211 ast::Expr::BlockExpr(b) => {
212 if let Some(e) = b.tail_expr() {
213 for_each_tail_expr(&e, cb);
216 ast::Expr::EffectExpr(e) => match e.effect() {
217 ast::Effect::Label(label) => {
218 for_each_break_expr(Some(label), e.block_expr(), &mut |b| {
219 cb(&ast::Expr::BreakExpr(b))
221 if let Some(b) = e.block_expr() {
222 for_each_tail_expr(&ast::Expr::BlockExpr(b), cb);
225 ast::Effect::Unsafe(_) => {
226 if let Some(e) = e.block_expr().and_then(|b| b.tail_expr()) {
227 for_each_tail_expr(&e, cb);
230 ast::Effect::Async(_) | ast::Effect::Try(_) | ast::Effect::Const(_) => cb(expr),
232 ast::Expr::IfExpr(if_) => {
233 if_.blocks().for_each(|block| for_each_tail_expr(&ast::Expr::BlockExpr(block), cb))
235 ast::Expr::LoopExpr(l) => {
236 for_each_break_expr(l.label(), l.loop_body(), &mut |b| cb(&ast::Expr::BreakExpr(b)))
238 ast::Expr::MatchExpr(m) => {
239 if let Some(arms) = m.match_arm_list() {
240 arms.arms().filter_map(|arm| arm.expr()).for_each(|e| for_each_tail_expr(&e, cb));
243 ast::Expr::ArrayExpr(_)
244 | ast::Expr::AwaitExpr(_)
245 | ast::Expr::BinExpr(_)
246 | ast::Expr::BoxExpr(_)
247 | ast::Expr::BreakExpr(_)
248 | ast::Expr::CallExpr(_)
249 | ast::Expr::CastExpr(_)
250 | ast::Expr::ClosureExpr(_)
251 | ast::Expr::ContinueExpr(_)
252 | ast::Expr::FieldExpr(_)
253 | ast::Expr::ForExpr(_)
254 | ast::Expr::IndexExpr(_)
255 | ast::Expr::Literal(_)
256 | ast::Expr::MacroCall(_)
257 | ast::Expr::MacroStmts(_)
258 | ast::Expr::MethodCallExpr(_)
259 | ast::Expr::ParenExpr(_)
260 | ast::Expr::PathExpr(_)
261 | ast::Expr::PrefixExpr(_)
262 | ast::Expr::RangeExpr(_)
263 | ast::Expr::RecordExpr(_)
264 | ast::Expr::RefExpr(_)
265 | ast::Expr::ReturnExpr(_)
266 | ast::Expr::TryExpr(_)
267 | ast::Expr::TupleExpr(_)
268 | ast::Expr::WhileExpr(_)
269 | ast::Expr::YieldExpr(_) => cb(expr),
273 /// Calls `cb` on each break expr inside of `body` that is applicable for the given label.
274 pub fn for_each_break_expr(
275 label: Option<ast::Label>,
276 body: Option<ast::BlockExpr>,
277 cb: &mut dyn FnMut(ast::BreakExpr),
279 let label = label.and_then(|lbl| lbl.lifetime());
281 if let Some(b) = body {
282 let preorder = &mut b.syntax().preorder();
283 let ev_as_expr = |ev| match ev {
284 WalkEvent::Enter(it) => Some(WalkEvent::Enter(ast::Expr::cast(it)?)),
285 WalkEvent::Leave(it) => Some(WalkEvent::Leave(ast::Expr::cast(it)?)),
287 let eq_label = |lt: Option<ast::Lifetime>| {
288 lt.zip(label.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
290 while let Some(node) = preorder.find_map(ev_as_expr) {
292 WalkEvent::Enter(expr) => match expr {
293 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
296 ast::Expr::EffectExpr(e) if e.label().is_some() => depth += 1,
297 ast::Expr::BreakExpr(b)
298 if (depth == 0 && b.lifetime().is_none()) || eq_label(b.lifetime()) =>
304 WalkEvent::Leave(expr) => match expr {
305 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
308 ast::Expr::EffectExpr(e) if e.label().is_some() => depth -= 1,