Skip to content

Commit c51a3c7

Browse files
bors[bot]Veykril
andauthored
Merge #10358
10358: internal: Remove inherent methods from ast nodes that do non-syntactic complex tasks r=Veykril a=Veykril Co-authored-by: Lukas Wirth <[email protected]>
2 parents cd7b26c + 151afdf commit c51a3c7

File tree

15 files changed

+392
-365
lines changed

15 files changed

+392
-365
lines changed

crates/ide/src/folding_ranges.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use ide_db::helpers::node_ext::vis_eq;
12
use rustc_hash::FxHashSet;
23

34
use syntax::{
@@ -198,7 +199,7 @@ where
198199
fn eq_visibility(vis0: Option<ast::Visibility>, vis1: Option<ast::Visibility>) -> bool {
199200
match (vis0, vis1) {
200201
(None, None) => true,
201-
(Some(vis0), Some(vis1)) => vis0.is_eq_to(&vis1),
202+
(Some(vis0), Some(vis1)) => vis_eq(&vis0, &vis1),
202203
_ => false,
203204
}
204205
}

crates/ide/src/highlight_related.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use hir::Semantics;
22
use ide_db::{
33
base_db::FilePosition,
44
defs::{Definition, NameClass, NameRefClass},
5-
helpers::{for_each_break_expr, for_each_tail_expr, pick_best_token},
5+
helpers::{for_each_break_expr, for_each_tail_expr, node_ext::walk_expr, pick_best_token},
66
search::{FileReference, ReferenceAccess, SearchScope},
77
RootDatabase,
88
};
@@ -122,7 +122,7 @@ fn highlight_exit_points(
122122
) -> Option<Vec<HighlightedRange>> {
123123
let mut highlights = Vec::new();
124124
let body = body?;
125-
body.walk(&mut |expr| match expr {
125+
walk_expr(&body, &mut |expr| match expr {
126126
ast::Expr::ReturnExpr(expr) => {
127127
if let Some(token) = expr.return_token() {
128128
highlights.push(HighlightedRange { access: None, range: token.text_range() });
@@ -243,7 +243,7 @@ fn highlight_yield_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
243243
let mut highlights =
244244
vec![HighlightedRange { access: None, range: async_token?.text_range() }];
245245
if let Some(body) = body {
246-
body.walk(&mut |expr| {
246+
walk_expr(&body, &mut |expr| {
247247
if let ast::Expr::AwaitExpr(expr) = expr {
248248
if let Some(token) = expr.await_token() {
249249
highlights

crates/ide/src/join_lines.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use std::convert::TryFrom;
22

33
use ide_assists::utils::extract_trivial_expression;
4+
use ide_db::helpers::node_ext::expr_as_name_ref;
45
use itertools::Itertools;
56
use syntax::{
67
ast::{self, AstNode, AstToken, IsString},
@@ -263,7 +264,7 @@ fn join_assignments(
263264
return None;
264265
}
265266
let lhs = bin_expr.lhs()?;
266-
let name_ref = lhs.name_ref()?;
267+
let name_ref = expr_as_name_ref(&lhs)?;
267268

268269
if name_ref.to_string() != let_ident_pat.syntax().to_string() {
269270
cov_mark::hit!(join_assignments_mismatch);

crates/ide_assists/src/handlers/add_explicit_type.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use hir::HirDisplay;
2+
use ide_db::helpers::node_ext::walk_ty;
23
use syntax::ast::{self, AstNode, LetStmt, Param};
34

45
use crate::{AssistContext, AssistId, AssistKind, Assists};
@@ -46,7 +47,7 @@ pub(crate) fn add_explicit_type(acc: &mut Assists, ctx: &AssistContext) -> Optio
4647
// Don't enable the assist if there is a type ascription without any placeholders
4748
if let Some(ty) = &ascribed_ty {
4849
let mut contains_infer_ty = false;
49-
ty.walk(&mut |ty| contains_infer_ty |= matches!(ty, ast::Type::InferType(_)));
50+
walk_ty(ty, &mut |ty| contains_infer_ty |= matches!(ty, ast::Type::InferType(_)));
5051
if !contains_infer_ty {
5152
cov_mark::hit!(add_explicit_type_not_applicable_if_ty_already_specified);
5253
return None;

crates/ide_assists/src/handlers/convert_bool_then.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
use hir::{known, AsAssocItem, Semantics};
22
use ide_db::{
3-
helpers::{for_each_tail_expr, FamousDefs},
3+
helpers::{
4+
for_each_tail_expr,
5+
node_ext::{block_as_lone_tail, preorder_expr},
6+
FamousDefs,
7+
},
48
RootDatabase,
59
};
610
use itertools::Itertools;
@@ -218,7 +222,7 @@ fn is_invalid_body(
218222
expr: &ast::Expr,
219223
) -> bool {
220224
let mut invalid = false;
221-
expr.preorder(&mut |e| {
225+
preorder_expr(expr, &mut |e| {
222226
invalid |=
223227
matches!(e, syntax::WalkEvent::Enter(ast::Expr::TryExpr(_) | ast::Expr::ReturnExpr(_)));
224228
invalid
@@ -252,7 +256,7 @@ fn block_is_none_variant(
252256
block: &ast::BlockExpr,
253257
none_variant: hir::Variant,
254258
) -> bool {
255-
block.as_lone_tail().and_then(|e| match e {
259+
block_as_lone_tail(block).and_then(|e| match e {
256260
ast::Expr::PathExpr(pat) => match sema.resolve_path(&pat.path()?)? {
257261
hir::PathResolution::Def(hir::ModuleDef::Variant(v)) => Some(v),
258262
_ => None,

crates/ide_assists/src/handlers/extract_function.rs

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use either::Either;
55
use hir::{HirDisplay, InFile, Local, Semantics, TypeInfo};
66
use ide_db::{
77
defs::{Definition, NameRefClass},
8+
helpers::node_ext::{preorder_expr, walk_expr, walk_pat, walk_patterns_in_expr},
89
search::{FileReference, ReferenceAccess, SearchScope},
910
RootDatabase,
1011
};
@@ -478,7 +479,7 @@ impl FunctionBody {
478479

479480
fn walk_expr(&self, cb: &mut dyn FnMut(ast::Expr)) {
480481
match self {
481-
FunctionBody::Expr(expr) => expr.walk(cb),
482+
FunctionBody::Expr(expr) => walk_expr(expr, cb),
482483
FunctionBody::Span { parent, text_range } => {
483484
parent
484485
.statements()
@@ -488,20 +489,20 @@ impl FunctionBody {
488489
ast::Stmt::Item(_) => None,
489490
ast::Stmt::LetStmt(stmt) => stmt.initializer(),
490491
})
491-
.for_each(|expr| expr.walk(cb));
492+
.for_each(|expr| walk_expr(&expr, cb));
492493
if let Some(expr) = parent
493494
.tail_expr()
494495
.filter(|it| text_range.contains_range(it.syntax().text_range()))
495496
{
496-
expr.walk(cb);
497+
walk_expr(&expr, cb);
497498
}
498499
}
499500
}
500501
}
501502

502503
fn preorder_expr(&self, cb: &mut dyn FnMut(WalkEvent<ast::Expr>) -> bool) {
503504
match self {
504-
FunctionBody::Expr(expr) => expr.preorder(cb),
505+
FunctionBody::Expr(expr) => preorder_expr(expr, cb),
505506
FunctionBody::Span { parent, text_range } => {
506507
parent
507508
.statements()
@@ -511,45 +512,45 @@ impl FunctionBody {
511512
ast::Stmt::Item(_) => None,
512513
ast::Stmt::LetStmt(stmt) => stmt.initializer(),
513514
})
514-
.for_each(|expr| expr.preorder(cb));
515+
.for_each(|expr| preorder_expr(&expr, cb));
515516
if let Some(expr) = parent
516517
.tail_expr()
517518
.filter(|it| text_range.contains_range(it.syntax().text_range()))
518519
{
519-
expr.preorder(cb);
520+
preorder_expr(&expr, cb);
520521
}
521522
}
522523
}
523524
}
524525

525526
fn walk_pat(&self, cb: &mut dyn FnMut(ast::Pat)) {
526527
match self {
527-
FunctionBody::Expr(expr) => expr.walk_patterns(cb),
528+
FunctionBody::Expr(expr) => walk_patterns_in_expr(expr, cb),
528529
FunctionBody::Span { parent, text_range } => {
529530
parent
530531
.statements()
531532
.filter(|stmt| text_range.contains_range(stmt.syntax().text_range()))
532533
.for_each(|stmt| match stmt {
533534
ast::Stmt::ExprStmt(expr_stmt) => {
534535
if let Some(expr) = expr_stmt.expr() {
535-
expr.walk_patterns(cb)
536+
walk_patterns_in_expr(&expr, cb)
536537
}
537538
}
538539
ast::Stmt::Item(_) => (),
539540
ast::Stmt::LetStmt(stmt) => {
540541
if let Some(pat) = stmt.pat() {
541-
pat.walk(cb);
542+
walk_pat(&pat, cb);
542543
}
543544
if let Some(expr) = stmt.initializer() {
544-
expr.walk_patterns(cb);
545+
walk_patterns_in_expr(&expr, cb);
545546
}
546547
}
547548
});
548549
if let Some(expr) = parent
549550
.tail_expr()
550551
.filter(|it| text_range.contains_range(it.syntax().text_range()))
551552
{
552-
expr.walk_patterns(cb);
553+
walk_patterns_in_expr(&expr, cb);
553554
}
554555
}
555556
}

crates/ide_assists/src/handlers/extract_type_alias.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use either::Either;
2+
use ide_db::helpers::node_ext::walk_ty;
23
use itertools::Itertools;
34
use syntax::{
45
ast::{self, edit::IndentLevel, AstNode, GenericParamsOwner, NameOwner},
@@ -120,7 +121,7 @@ fn collect_used_generics<'gp>(
120121
}
121122

122123
let mut generics = Vec::new();
123-
ty.walk(&mut |ty| match ty {
124+
walk_ty(ty, &mut |ty| match ty {
124125
ast::Type::PathType(ty) => {
125126
if let Some(path) = ty.path() {
126127
if let Some(name_ref) = path.as_single_name_ref() {

crates/ide_assists/src/handlers/wrap_return_type_in_result.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use std::iter;
22

3-
use ide_db::helpers::{for_each_tail_expr, FamousDefs};
3+
use ide_db::helpers::{for_each_tail_expr, node_ext::walk_expr, FamousDefs};
44
use syntax::{
55
ast::{self, make, Expr},
66
match_ast, AstNode,
@@ -54,7 +54,7 @@ pub(crate) fn wrap_return_type_in_result(acc: &mut Assists, ctx: &AssistContext)
5454

5555
let mut exprs_to_wrap = Vec::new();
5656
let tail_cb = &mut |e: &_| tail_cb_impl(&mut exprs_to_wrap, e);
57-
body.walk(&mut |expr| {
57+
walk_expr(&body, &mut |expr| {
5858
if let Expr::ReturnExpr(ret_expr) = expr {
5959
if let Some(ret_expr_arg) = &ret_expr.expr() {
6060
for_each_tail_expr(ret_expr_arg, tail_cb);

crates/ide_db/src/helpers.rs

Lines changed: 7 additions & 120 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,26 @@
11
//! A module with ide helpers for high-level ide features.
2+
pub mod famous_defs;
3+
pub mod generated_lints;
24
pub mod import_assets;
35
pub mod insert_use;
46
pub mod merge_imports;
7+
pub mod node_ext;
58
pub mod rust_doc;
6-
pub mod generated_lints;
79

810
use std::collections::VecDeque;
911

1012
use base_db::FileId;
1113
use either::Either;
12-
use hir::{Crate, Enum, ItemInNs, MacroDef, Module, ModuleDef, Name, ScopeDef, Semantics, Trait};
14+
use hir::{ItemInNs, MacroDef, ModuleDef, Name, Semantics};
1315
use syntax::{
1416
ast::{self, make, LoopBodyOwner},
1517
AstNode, Direction, SyntaxElement, SyntaxKind, SyntaxToken, TokenAtOffset, WalkEvent, T,
1618
};
1719

1820
use crate::RootDatabase;
1921

22+
pub use self::famous_defs::FamousDefs;
23+
2024
pub fn item_name(db: &RootDatabase, item: ItemInNs) -> Option<Name> {
2125
match item {
2226
ItemInNs::Types(module_def_id) => ModuleDef::from(module_def_id).name(db),
@@ -27,7 +31,7 @@ pub fn item_name(db: &RootDatabase, item: ItemInNs) -> Option<Name> {
2731

2832
/// Resolves the path at the cursor token as a derive macro if it inside a token tree of a derive attribute.
2933
pub fn try_resolve_derive_input_at(
30-
sema: &Semantics<RootDatabase>,
34+
sema: &hir::Semantics<RootDatabase>,
3135
derive_attr: &ast::Attr,
3236
cursor: &SyntaxToken,
3337
) -> Option<MacroDef> {
@@ -113,123 +117,6 @@ pub fn visit_file_defs(
113117
module.impl_defs(db).into_iter().for_each(|impl_| cb(Either::Right(impl_)));
114118
}
115119

116-
/// Helps with finding well-know things inside the standard library. This is
117-
/// somewhat similar to the known paths infra inside hir, but it different; We
118-
/// want to make sure that IDE specific paths don't become interesting inside
119-
/// the compiler itself as well.
120-
///
121-
/// Note that, by default, rust-analyzer tests **do not** include core or std
122-
/// libraries. If you are writing tests for functionality using [`FamousDefs`],
123-
/// you'd want to include minicore (see `test_utils::MiniCore`) declaration at
124-
/// the start of your tests:
125-
///
126-
/// ```
127-
/// //- minicore: iterator, ord, derive
128-
/// ```
129-
pub struct FamousDefs<'a, 'b>(pub &'a Semantics<'b, RootDatabase>, pub Option<Crate>);
130-
131-
#[allow(non_snake_case)]
132-
impl FamousDefs<'_, '_> {
133-
pub fn std(&self) -> Option<Crate> {
134-
self.find_crate("std")
135-
}
136-
137-
pub fn core(&self) -> Option<Crate> {
138-
self.find_crate("core")
139-
}
140-
141-
pub fn core_cmp_Ord(&self) -> Option<Trait> {
142-
self.find_trait("core:cmp:Ord")
143-
}
144-
145-
pub fn core_convert_From(&self) -> Option<Trait> {
146-
self.find_trait("core:convert:From")
147-
}
148-
149-
pub fn core_convert_Into(&self) -> Option<Trait> {
150-
self.find_trait("core:convert:Into")
151-
}
152-
153-
pub fn core_option_Option(&self) -> Option<Enum> {
154-
self.find_enum("core:option:Option")
155-
}
156-
157-
pub fn core_result_Result(&self) -> Option<Enum> {
158-
self.find_enum("core:result:Result")
159-
}
160-
161-
pub fn core_default_Default(&self) -> Option<Trait> {
162-
self.find_trait("core:default:Default")
163-
}
164-
165-
pub fn core_iter_Iterator(&self) -> Option<Trait> {
166-
self.find_trait("core:iter:traits:iterator:Iterator")
167-
}
168-
169-
pub fn core_iter_IntoIterator(&self) -> Option<Trait> {
170-
self.find_trait("core:iter:traits:collect:IntoIterator")
171-
}
172-
173-
pub fn core_iter(&self) -> Option<Module> {
174-
self.find_module("core:iter")
175-
}
176-
177-
pub fn core_ops_Deref(&self) -> Option<Trait> {
178-
self.find_trait("core:ops:Deref")
179-
}
180-
181-
fn find_trait(&self, path: &str) -> Option<Trait> {
182-
match self.find_def(path)? {
183-
hir::ScopeDef::ModuleDef(hir::ModuleDef::Trait(it)) => Some(it),
184-
_ => None,
185-
}
186-
}
187-
188-
fn find_enum(&self, path: &str) -> Option<Enum> {
189-
match self.find_def(path)? {
190-
hir::ScopeDef::ModuleDef(hir::ModuleDef::Adt(hir::Adt::Enum(it))) => Some(it),
191-
_ => None,
192-
}
193-
}
194-
195-
fn find_module(&self, path: &str) -> Option<Module> {
196-
match self.find_def(path)? {
197-
hir::ScopeDef::ModuleDef(hir::ModuleDef::Module(it)) => Some(it),
198-
_ => None,
199-
}
200-
}
201-
202-
fn find_crate(&self, name: &str) -> Option<Crate> {
203-
let krate = self.1?;
204-
let db = self.0.db;
205-
let res =
206-
krate.dependencies(db).into_iter().find(|dep| dep.name.to_string() == name)?.krate;
207-
Some(res)
208-
}
209-
210-
fn find_def(&self, path: &str) -> Option<ScopeDef> {
211-
let db = self.0.db;
212-
let mut path = path.split(':');
213-
let trait_ = path.next_back()?;
214-
let std_crate = path.next()?;
215-
let std_crate = self.find_crate(std_crate)?;
216-
let mut module = std_crate.root_module(db);
217-
for segment in path {
218-
module = module.children(db).find_map(|child| {
219-
let name = child.name(db)?;
220-
if name.to_string() == segment {
221-
Some(child)
222-
} else {
223-
None
224-
}
225-
})?;
226-
}
227-
let def =
228-
module.scope(db, None).into_iter().find(|(name, _def)| name.to_string() == trait_)?.1;
229-
Some(def)
230-
}
231-
}
232-
233120
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
234121
pub struct SnippetCap {
235122
_private: (),

0 commit comments

Comments
 (0)