Skip to content

Commit 65e47bf

Browse files
committed
Remove tuple index variant from name
1 parent 59bcbaf commit 65e47bf

File tree

23 files changed

+58
-120
lines changed

23 files changed

+58
-120
lines changed

crates/hir-def/src/attr.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ impl Attrs {
234234
.iter()
235235
.rev()
236236
.zip(["core", "prelude", "v1", "test"].iter().rev())
237-
.all(|it| it.0.as_str() == Some(it.1))
237+
.all(|(name, path_segment)| name.as_str() == *path_segment)
238238
})
239239
}
240240

@@ -604,7 +604,7 @@ impl<'attr> AttrQuery<'attr> {
604604
let key = self.key;
605605
self.attrs
606606
.iter()
607-
.filter(move |attr| attr.path.as_ident().map_or(false, |s| s.to_smol_str() == key))
607+
.filter(move |attr| attr.path.as_ident().map_or(false, |s| s.as_str() == key))
608608
}
609609

610610
/// Find string value for a specific key inside token tree

crates/hir-def/src/body/scope.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -316,7 +316,7 @@ mod tests {
316316
let actual = scopes
317317
.scope_chain(scope)
318318
.flat_map(|scope| scopes.entries(scope))
319-
.map(|it| it.name().to_smol_str())
319+
.map(|it| it.name().as_str())
320320
.collect::<Vec<_>>()
321321
.join("\n");
322322
let expected = expected.join("\n");

crates/hir-def/src/data.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -502,6 +502,7 @@ impl ExternCrateDeclData {
502502
#[derive(Debug, Clone, PartialEq, Eq)]
503503
pub struct ConstData {
504504
/// `None` for `const _: () = ();`
505+
// FIXME: Consider making this required, using interned `_` as the name
505506
pub name: Option<Name>,
506507
pub type_ref: Interned<TypeRef>,
507508
pub visibility: RawVisibility,

crates/hir-def/src/db.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -276,9 +276,9 @@ fn crate_supports_no_std(db: &dyn DefDatabase, crate_id: CrateId) -> bool {
276276
let item_tree = db.file_item_tree(file.into());
277277
let attrs = item_tree.raw_attrs(AttrOwner::TopLevel);
278278
for attr in &**attrs {
279-
match attr.path().as_ident().and_then(|id| id.as_text()) {
280-
Some(ident) if ident == "no_std" => return true,
281-
Some(ident) if ident == "cfg_attr" => {}
279+
match attr.path().as_ident().map(|id| id.as_str()) {
280+
Some("no_std") => return true,
281+
Some("cfg_attr") => {}
282282
_ => continue,
283283
}
284284

crates/hir-def/src/import_map.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ impl ImportMap {
6464
let mut importables: Vec<_> = map
6565
.iter()
6666
// We've only collected items, whose name cannot be tuple field.
67-
.map(|(&item, info)| (item, info.name.as_str().unwrap().to_ascii_lowercase()))
67+
.map(|(&item, info)| (item, info.name.as_str().to_ascii_lowercase()))
6868
.collect();
6969
importables.sort_by(|(_, lhs_name), (_, rhs_name)| lhs_name.cmp(rhs_name));
7070

@@ -410,16 +410,15 @@ pub fn search_dependencies(
410410
}
411411

412412
// Name shared by the importable items in this group.
413-
let common_importable_name =
414-
common_importable_data.name.to_smol_str().to_ascii_lowercase();
413+
let common_importable_name = common_importable_data.name.as_str().to_ascii_lowercase();
415414
// Add the items from this name group. Those are all subsequent items in
416415
// `importables` whose name match `common_importable_name`.
417416
let iter = importables
418417
.iter()
419418
.copied()
420419
.take_while(|item| {
421420
common_importable_name
422-
== import_map.map[item].name.to_smol_str().to_ascii_lowercase()
421+
== import_map.map[item].name.as_str().to_ascii_lowercase()
423422
})
424423
.filter(|item| {
425424
!query.case_sensitive // we've already checked the common importables name case-insensitively

crates/hir-def/src/lang_item.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ macro_rules! language_item_table {
234234
impl LangItem {
235235
/// Opposite of [`LangItem::name`]
236236
pub fn from_name(name: &hir_expand::name::Name) -> Option<Self> {
237-
Self::from_str(name.as_str()?)
237+
Self::from_str(name.as_str())
238238
}
239239

240240
pub fn path(&self, db: &dyn DefDatabase, start_crate: CrateId) -> Option<Path> {

crates/hir-def/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -745,7 +745,7 @@ impl GeneralConstId {
745745
.const_data(const_id)
746746
.name
747747
.as_ref()
748-
.and_then(|it| it.as_str())
748+
.map(|it| it.as_str())
749749
.unwrap_or("_")
750750
.to_owned(),
751751
GeneralConstId::ConstBlockId(id) => format!("{{anonymous const {id:?}}}"),

crates/hir-def/src/nameres/attr_resolution.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,8 @@ impl DefMap {
7575
let segments = path.segments();
7676

7777
if let Some(name) = segments.first() {
78-
let name = name.to_smol_str();
79-
let pred = |n: &_| *n == name;
78+
let name = name.as_str();
79+
let pred = |n: &_| n == name;
8080

8181
let registered = self.data.registered_tools.iter().map(SmolStr::as_str);
8282
let is_tool = TOOL_MODULES.iter().copied().chain(registered).any(pred);

crates/hir-def/src/nameres/collector.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,7 @@ impl DefCollector<'_> {
309309
continue;
310310
}
311311

312-
if attr_name.as_text().as_deref() == Some("rustc_coherence_is_core") {
312+
if attr_name.as_str() == "rustc_coherence_is_core" {
313313
crate_data.rustc_coherence_is_core = true;
314314
continue;
315315
}

crates/hir-def/src/path.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ impl Display for ImportAlias {
2929
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3030
match self {
3131
ImportAlias::Underscore => f.write_str("_"),
32-
ImportAlias::Alias(name) => f.write_str(&name.to_smol_str()),
32+
ImportAlias::Alias(name) => f.write_str(name.as_str()),
3333
}
3434
}
3535
}

crates/hir-expand/src/name.rs

Lines changed: 16 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -12,32 +12,17 @@ use syntax::{ast, utils::is_raw_identifier, SmolStr};
1212
/// is a raw identifier. Use [`unescaped()`][Name::unescaped] when you need the
1313
/// name without "r#".
1414
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
15-
pub struct Name(Repr);
15+
pub struct Name(SmolStr);
1616

1717
/// Wrapper of `Name` to print the name without "r#" even when it is a raw identifier.
1818
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
1919
pub struct UnescapedName<'a>(&'a Name);
2020

21-
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
22-
enum Repr {
23-
Text(SmolStr),
24-
TupleField(usize),
25-
}
26-
2721
impl UnescapedName<'_> {
2822
/// Returns the textual representation of this name as a [`SmolStr`]. Prefer using this over
2923
/// [`ToString::to_string`] if possible as this conversion is cheaper in the general case.
3024
pub fn to_smol_str(&self) -> SmolStr {
31-
match &self.0 .0 {
32-
Repr::Text(it) => {
33-
if let Some(stripped) = it.strip_prefix("r#") {
34-
SmolStr::new(stripped)
35-
} else {
36-
it.clone()
37-
}
38-
}
39-
Repr::TupleField(it) => SmolStr::new(it.to_string()),
40-
}
25+
self.0.to_smol_str()
4126
}
4227

4328
pub fn display(&self, db: &dyn crate::db::ExpandDatabase) -> impl fmt::Display + '_ {
@@ -51,17 +36,17 @@ impl Name {
5136
/// Hopefully, this should allow us to integrate hygiene cleaner in the
5237
/// future, and to switch to interned representation of names.
5338
const fn new_text(text: SmolStr) -> Name {
54-
Name(Repr::Text(text))
39+
Name(text)
5540
}
5641

5742
// FIXME: See above, unfortunately some places really need this right now
5843
#[doc(hidden)]
5944
pub const fn new_text_dont_use(text: SmolStr) -> Name {
60-
Name(Repr::Text(text))
45+
Name(text)
6146
}
6247

6348
pub fn new_tuple_field(idx: usize) -> Name {
64-
Name(Repr::TupleField(idx))
49+
Name(idx.to_string().into())
6550
}
6651

6752
pub fn new_lifetime(lt: &ast::Lifetime) -> Name {
@@ -123,48 +108,29 @@ impl Name {
123108
}
124109

125110
/// Returns the tuple index this name represents if it is a tuple field.
111+
/// Note this may parse the underlying string as a usize and as such is not necessarily cheap.
126112
pub fn as_tuple_index(&self) -> Option<usize> {
127-
match self.0 {
128-
Repr::TupleField(idx) => Some(idx),
129-
_ => None,
130-
}
113+
self.0.as_str().parse().ok()
131114
}
132115

133-
/// Returns the text this name represents if it isn't a tuple field.
134-
pub fn as_text(&self) -> Option<SmolStr> {
135-
match &self.0 {
136-
Repr::Text(it) => Some(it.clone()),
137-
_ => None,
138-
}
139-
}
140-
141-
/// Returns the text this name represents if it isn't a tuple field.
142-
pub fn as_str(&self) -> Option<&str> {
143-
match &self.0 {
144-
Repr::Text(it) => Some(it),
145-
_ => None,
146-
}
116+
/// Returns the text this name represents.
117+
pub fn as_str(&self) -> &str {
118+
self.0.as_str()
147119
}
148120

149121
/// Returns the textual representation of this name as a [`SmolStr`].
150122
/// Prefer using this over [`ToString::to_string`] if possible as this conversion is cheaper in
151123
/// the general case.
152124
pub fn to_smol_str(&self) -> SmolStr {
153-
match &self.0 {
154-
Repr::Text(it) => it.clone(),
155-
Repr::TupleField(it) => SmolStr::new(it.to_string()),
156-
}
125+
self.0.clone()
157126
}
158127

159128
pub fn unescaped(&self) -> UnescapedName<'_> {
160129
UnescapedName(self)
161130
}
162131

163132
pub fn is_escaped(&self) -> bool {
164-
match &self.0 {
165-
Repr::Text(it) => it.starts_with("r#"),
166-
Repr::TupleField(_) => false,
167-
}
133+
self.0.starts_with("r#")
168134
}
169135

170136
pub fn display<'a>(&'a self, db: &dyn crate::db::ExpandDatabase) -> impl fmt::Display + 'a {
@@ -179,10 +145,7 @@ struct Display<'a> {
179145

180146
impl fmt::Display for Display<'_> {
181147
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182-
match &self.name.0 {
183-
Repr::Text(text) => fmt::Display::fmt(&text, f),
184-
Repr::TupleField(idx) => fmt::Display::fmt(&idx, f),
185-
}
148+
fmt::Display::fmt(&self.name.0, f)
186149
}
187150
}
188151

@@ -192,13 +155,9 @@ struct UnescapedDisplay<'a> {
192155

193156
impl fmt::Display for UnescapedDisplay<'_> {
194157
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195-
match &self.name.0 .0 {
196-
Repr::Text(text) => {
197-
let text = text.strip_prefix("r#").unwrap_or(text);
198-
fmt::Display::fmt(&text, f)
199-
}
200-
Repr::TupleField(idx) => fmt::Display::fmt(&idx, f),
201-
}
158+
let text = &self.name.0 .0;
159+
let text = text.strip_prefix("r#").unwrap_or(text);
160+
fmt::Display::fmt(&text, f)
202161
}
203162
}
204163

crates/hir-ty/src/infer/closure.rs

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -192,11 +192,7 @@ impl CapturedItem {
192192
}
193193
let variant_data = f.parent.variant_data(db.upcast());
194194
let field = match &*variant_data {
195-
VariantData::Record(fields) => fields[f.local_id]
196-
.name
197-
.as_str()
198-
.unwrap_or("[missing field]")
199-
.to_string(),
195+
VariantData::Record(fields) => fields[f.local_id].name.as_str().to_string(),
200196
VariantData::Tuple(fields) => fields
201197
.iter()
202198
.position(|it| it.0 == f.local_id)

crates/hir-ty/src/mir/eval.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2475,10 +2475,7 @@ impl Evaluator<'_> {
24752475
let static_data = self.db.static_data(st);
24762476
let result = if !static_data.is_extern {
24772477
let konst = self.db.const_eval_static(st).map_err(|e| {
2478-
MirEvalError::ConstEvalError(
2479-
static_data.name.as_str().unwrap_or("_").to_owned(),
2480-
Box::new(e),
2481-
)
2478+
MirEvalError::ConstEvalError(static_data.name.as_str().to_owned(), Box::new(e))
24822479
})?;
24832480
self.allocate_const_in_heap(locals, &konst)?
24842481
} else {

crates/hir-ty/src/mir/eval/shim.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ impl Evaluator<'_> {
5656
};
5757
if is_intrinsic {
5858
self.exec_intrinsic(
59-
function_data.name.as_text().unwrap_or_default().as_str(),
59+
function_data.name.as_str(),
6060
args,
6161
generic_args,
6262
destination,
@@ -78,7 +78,7 @@ impl Evaluator<'_> {
7878
};
7979
if is_platform_intrinsic {
8080
self.exec_platform_intrinsic(
81-
function_data.name.as_text().unwrap_or_default().as_str(),
81+
function_data.name.as_str(),
8282
args,
8383
generic_args,
8484
destination,
@@ -96,7 +96,7 @@ impl Evaluator<'_> {
9696
};
9797
if is_extern_c {
9898
self.exec_extern_c(
99-
function_data.name.as_text().unwrap_or_default().as_str(),
99+
function_data.name.as_str(),
100100
args,
101101
generic_args,
102102
destination,
@@ -109,7 +109,7 @@ impl Evaluator<'_> {
109109
.attrs
110110
.iter()
111111
.filter_map(|it| it.path().as_ident())
112-
.filter_map(|it| it.as_str())
112+
.map(|it| it.as_str())
113113
.find(|it| {
114114
[
115115
"rustc_allocator",

crates/hir-ty/src/mir/lower.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1099,9 +1099,9 @@ impl<'ctx> MirLowerCtx<'ctx> {
10991099
.iter()
11001100
.map(|it| {
11011101
let o = match it.1.name.as_str() {
1102-
Some("start") => lp.take(),
1103-
Some("end") => rp.take(),
1104-
Some("exhausted") => {
1102+
"start" => lp.take(),
1103+
"end" => rp.take(),
1104+
"exhausted" => {
11051105
Some(Operand::from_bytes(vec![0], TyBuilder::bool()))
11061106
}
11071107
_ => None,

crates/hir/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1723,7 +1723,7 @@ impl DefWithBody {
17231723
}
17241724
(mir::MutabilityReason::Not, true) => {
17251725
if !infer.mutated_bindings_in_closure.contains(&binding_id) {
1726-
let should_ignore = matches!(body[binding_id].name.as_str(), Some(it) if it.starts_with("_"));
1726+
let should_ignore = body[binding_id].name.as_str().starts_with("_");
17271727
if !should_ignore {
17281728
acc.push(UnusedMut { local }.into())
17291729
}

crates/hir/src/symbols.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ impl<'a> SymbolCollector<'a> {
244244

245245
fn collect_from_trait(&mut self, trait_id: TraitId) {
246246
let trait_data = self.db.trait_data(trait_id);
247-
self.with_container_name(trait_data.name.as_text(), |s| {
247+
self.with_container_name(Some(trait_data.name.to_smol_str()), |s| {
248248
for &(_, assoc_item_id) in &trait_data.items {
249249
s.push_assoc_item(assoc_item_id);
250250
}

crates/ide-assists/src/handlers/replace_method_eager_lazy.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ pub(crate) fn replace_with_lazy_method(acc: &mut Assists, ctx: &AssistContext<'_
4747
None,
4848
None,
4949
|func| {
50-
let valid = func.name(ctx.sema.db).as_str() == Some(&*method_name_lazy)
50+
let valid = func.name(ctx.sema.db).as_str() == &*method_name_lazy
5151
&& func.num_params(ctx.sema.db) == n_params
5252
&& {
5353
let params = func.params_without_self(ctx.sema.db);
@@ -133,7 +133,7 @@ pub(crate) fn replace_with_eager_method(acc: &mut Assists, ctx: &AssistContext<'
133133
None,
134134
None,
135135
|func| {
136-
let valid = func.name(ctx.sema.db).as_str() == Some(&*method_name_eager)
136+
let valid = func.name(ctx.sema.db).as_str() == &*method_name_eager
137137
&& func.num_params(ctx.sema.db) == n_params;
138138
valid.then_some(func)
139139
},

crates/ide-completion/src/completions/use_.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,16 +48,15 @@ pub(crate) fn complete_use_path(
4848
let unknown_is_current = |name: &hir::Name| {
4949
matches!(
5050
name_ref,
51-
Some(name_ref) if name_ref.syntax().text() == name.to_smol_str().as_str()
51+
Some(name_ref) if name_ref.syntax().text() == name.as_str()
5252
)
5353
};
5454
for (name, def) in module_scope {
5555
if !ctx.check_stability(def.attrs(ctx.db).as_deref()) {
5656
continue;
5757
}
58-
let is_name_already_imported = name
59-
.as_text()
60-
.map_or(false, |text| already_imported_names.contains(text.as_str()));
58+
let is_name_already_imported =
59+
already_imported_names.contains(name.as_str());
6160

6261
let add_resolution = match def {
6362
ScopeDef::Unknown if unknown_is_current(&name) => {

0 commit comments

Comments
 (0)