Skip to content

Commit 7a2e449

Browse files
Prefer imports starting with std
1 parent 5dd8f8e commit 7a2e449

File tree

3 files changed

+34
-7
lines changed

3 files changed

+34
-7
lines changed

crates/ra_hir_def/src/find_path.rs

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use crate::{
77
visibility::Visibility,
88
CrateId, ModuleDefId, ModuleId,
99
};
10-
use hir_expand::name::Name;
10+
use hir_expand::name::{known, Name};
1111

1212
const MAX_PATH_LEN: usize = 15;
1313

@@ -102,7 +102,7 @@ fn find_path_inner(
102102
let mut best_path = None;
103103
let mut best_path_len = max_len;
104104
for (module_id, name) in importable_locations {
105-
let mut path = match find_path_inner(
105+
let mut new_path = match find_path_inner(
106106
db,
107107
ItemInNs::Types(ModuleDefId::ModuleId(module_id)),
108108
from,
@@ -111,15 +111,40 @@ fn find_path_inner(
111111
None => continue,
112112
Some(path) => path,
113113
};
114-
path.segments.push(name);
115-
if path_len(&path) < best_path_len {
116-
best_path_len = path_len(&path);
117-
best_path = Some(path);
114+
new_path.segments.push(name);
115+
116+
if prefer_new_path(best_path_len, best_path.as_ref(), &new_path) {
117+
best_path_len = path_len(&new_path);
118+
best_path = Some(new_path);
118119
}
119120
}
120121
best_path
121122
}
122123

124+
fn prefer_new_path(old_path_len: usize, old_path: Option<&ModPath>, new_path: &ModPath) -> bool {
125+
match (old_path.and_then(|mod_path| mod_path.segments.first()), new_path.segments.first()) {
126+
(Some(old_path_start), Some(new_path_start))
127+
if old_path_start == &known::std && use_std_instead(new_path_start) =>
128+
{
129+
false
130+
}
131+
(Some(old_path_start), Some(new_path_start))
132+
if new_path_start == &known::std && use_std_instead(old_path_start) =>
133+
{
134+
true
135+
}
136+
(None, Some(_)) => true,
137+
(Some(_), None) => false,
138+
_ => path_len(new_path) < old_path_len,
139+
}
140+
}
141+
142+
// When std library is present, paths starting with `std::`
143+
// should be preferred over paths starting with `core::` and `alloc::`
144+
fn use_std_instead(name: &Name) -> bool {
145+
name == &known::core || name == &known::alloc
146+
}
147+
123148
fn path_len(path: &ModPath) -> usize {
124149
path.segments.len()
125150
+ match path.kind {

crates/ra_hir_expand/src/name.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,8 @@ pub mod known {
141141
macro_rules,
142142
// Components of known path (value or mod name)
143143
std,
144+
core,
145+
alloc,
144146
iter,
145147
ops,
146148
future,

editors/code/package-lock.json

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)