Skip to content

Commit 4b716bb

Browse files
authored
Merge pull request #18990 from Veykril/push-tqonnqxyrnsv
internal: Cleanup `Name` string rendering
2 parents 0870bfb + 54d1d31 commit 4b716bb

38 files changed

+145
-249
lines changed

src/tools/rust-analyzer/crates/hir-def/src/import_map.rs

+5-10
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ use rustc_hash::FxHashSet;
1010
use smallvec::SmallVec;
1111
use span::Edition;
1212
use stdx::{format_to, TupleExt};
13-
use syntax::ToSmolStr;
1413
use triomphe::Arc;
1514

1615
use crate::{
@@ -88,9 +87,9 @@ impl ImportMap {
8887
.iter()
8988
// We've only collected items, whose name cannot be tuple field so unwrapping is fine.
9089
.flat_map(|(&item, (info, _))| {
91-
info.iter().enumerate().map(move |(idx, info)| {
92-
(item, info.name.unescaped().display(db.upcast()).to_smolstr(), idx as u32)
93-
})
90+
info.iter()
91+
.enumerate()
92+
.map(move |(idx, info)| (item, info.name.as_str(), idx as u32))
9493
})
9594
.collect();
9695
importables.sort_by(|(_, l_info, _), (_, r_info, _)| {
@@ -441,7 +440,7 @@ pub fn search_dependencies(
441440
}
442441

443442
fn search_maps(
444-
db: &dyn DefDatabase,
443+
_db: &dyn DefDatabase,
445444
import_maps: &[Arc<ImportMap>],
446445
mut stream: fst::map::Union<'_>,
447446
query: &Query,
@@ -464,11 +463,7 @@ fn search_maps(
464463
.then(|| (item, &import_infos[info_idx as usize]))
465464
})
466465
.filter(|&(_, info)| {
467-
query.search_mode.check(
468-
&query.query,
469-
query.case_sensitive,
470-
&info.name.unescaped().display(db.upcast()).to_smolstr(),
471-
)
466+
query.search_mode.check(&query.query, query.case_sensitive, info.name.as_str())
472467
});
473468
res.extend(iter.map(TupleExt::head));
474469
}

src/tools/rust-analyzer/crates/hir-def/src/nameres/mod_resolution.rs

+5-14
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ use base_db::AnchoredPath;
44
use hir_expand::{name::Name, HirFileIdExt};
55
use limit::Limit;
66
use span::EditionedFileId;
7-
use syntax::ToSmolStr as _;
87

98
use crate::{db::DefDatabase, HirFileId};
109

@@ -35,7 +34,7 @@ impl ModDir {
3534
let path = match attr_path {
3635
None => {
3736
let mut path = self.dir_path.clone();
38-
path.push(&name.unescaped().display_no_db().to_smolstr());
37+
path.push(name.as_str());
3938
path
4039
}
4140
Some(attr_path) => {
@@ -66,24 +65,16 @@ impl ModDir {
6665
name: &Name,
6766
attr_path: Option<&str>,
6867
) -> Result<(EditionedFileId, bool, ModDir), Box<[String]>> {
69-
let name = name.unescaped();
68+
let name = name.as_str();
7069

7170
let mut candidate_files = ArrayVec::<_, 2>::new();
7271
match attr_path {
7372
Some(attr_path) => {
7473
candidate_files.push(self.dir_path.join_attr(attr_path, self.root_non_dir_owner))
7574
}
7675
None => {
77-
candidate_files.push(format!(
78-
"{}{}.rs",
79-
self.dir_path.0,
80-
name.display(db.upcast())
81-
));
82-
candidate_files.push(format!(
83-
"{}{}/mod.rs",
84-
self.dir_path.0,
85-
name.display(db.upcast())
86-
));
76+
candidate_files.push(format!("{}{}.rs", self.dir_path.0, name));
77+
candidate_files.push(format!("{}{}/mod.rs", self.dir_path.0, name));
8778
}
8879
};
8980

@@ -97,7 +88,7 @@ impl ModDir {
9788
let dir_path = if root_dir_owner {
9889
DirPath::empty()
9990
} else {
100-
DirPath::new(format!("{}/", name.display(db.upcast())))
91+
DirPath::new(format!("{}/", name))
10192
};
10293
if let Some(mod_dir) = self.child(dir_path, !root_dir_owner) {
10394
return Ok((

src/tools/rust-analyzer/crates/hir-expand/src/mod_path.rs

+13-36
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,6 @@ pub struct ModPath {
2323
segments: SmallVec<[Name; 1]>,
2424
}
2525

26-
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
27-
pub struct UnescapedModPath<'a>(&'a ModPath);
28-
29-
impl<'a> UnescapedModPath<'a> {
30-
pub fn display(&'a self, db: &'a dyn crate::db::ExpandDatabase) -> impl fmt::Display + 'a {
31-
UnescapedDisplay { db, path: self }
32-
}
33-
}
34-
3526
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
3627
pub enum PathKind {
3728
Plain,
@@ -135,17 +126,19 @@ impl ModPath {
135126
_ => None,
136127
}
137128
}
138-
139-
pub fn unescaped(&self) -> UnescapedModPath<'_> {
140-
UnescapedModPath(self)
129+
pub fn display_verbatim<'a>(
130+
&'a self,
131+
db: &'a dyn crate::db::ExpandDatabase,
132+
) -> impl fmt::Display + 'a {
133+
Display { db, path: self, edition: None }
141134
}
142135

143136
pub fn display<'a>(
144137
&'a self,
145138
db: &'a dyn crate::db::ExpandDatabase,
146139
edition: Edition,
147140
) -> impl fmt::Display + 'a {
148-
Display { db, path: self, edition }
141+
Display { db, path: self, edition: Some(edition) }
149142
}
150143
}
151144

@@ -158,23 +151,12 @@ impl Extend<Name> for ModPath {
158151
struct Display<'a> {
159152
db: &'a dyn ExpandDatabase,
160153
path: &'a ModPath,
161-
edition: Edition,
154+
edition: Option<Edition>,
162155
}
163156

164157
impl fmt::Display for Display<'_> {
165158
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166-
display_fmt_path(self.db, self.path, f, Escape::IfNeeded(self.edition))
167-
}
168-
}
169-
170-
struct UnescapedDisplay<'a> {
171-
db: &'a dyn ExpandDatabase,
172-
path: &'a UnescapedModPath<'a>,
173-
}
174-
175-
impl fmt::Display for UnescapedDisplay<'_> {
176-
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177-
display_fmt_path(self.db, self.path.0, f, Escape::No)
159+
display_fmt_path(self.db, self.path, f, self.edition)
178160
}
179161
}
180162

@@ -184,16 +166,11 @@ impl From<Name> for ModPath {
184166
}
185167
}
186168

187-
enum Escape {
188-
No,
189-
IfNeeded(Edition),
190-
}
191-
192169
fn display_fmt_path(
193170
db: &dyn ExpandDatabase,
194171
path: &ModPath,
195172
f: &mut fmt::Formatter<'_>,
196-
escaped: Escape,
173+
edition: Option<Edition>,
197174
) -> fmt::Result {
198175
let mut first_segment = true;
199176
let mut add_segment = |s| -> fmt::Result {
@@ -221,10 +198,10 @@ fn display_fmt_path(
221198
f.write_str("::")?;
222199
}
223200
first_segment = false;
224-
match escaped {
225-
Escape::IfNeeded(edition) => segment.display(db, edition).fmt(f)?,
226-
Escape::No => segment.unescaped().display(db).fmt(f)?,
227-
}
201+
match edition {
202+
Some(edition) => segment.display(db, edition).fmt(f)?,
203+
None => fmt::Display::fmt(segment.as_str(), f)?,
204+
};
228205
}
229206
Ok(())
230207
}

src/tools/rust-analyzer/crates/hir-expand/src/name.rs

+31-69
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ use std::fmt;
44

55
use intern::{sym, Symbol};
66
use span::{Edition, SyntaxContextId};
7-
use syntax::ast;
87
use syntax::utils::is_raw_identifier;
8+
use syntax::{ast, format_smolstr};
99

1010
/// `Name` is a wrapper around string, which is used in hir for both references
1111
/// and declarations. In theory, names should also carry hygiene info, but we are
@@ -69,27 +69,8 @@ impl PartialEq<Name> for &Symbol {
6969
}
7070
}
7171

72-
/// Wrapper of `Name` to print the name without "r#" even when it is a raw identifier.
73-
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
74-
pub struct UnescapedName<'a>(&'a Name);
75-
76-
impl<'a> UnescapedName<'a> {
77-
pub fn display(self, db: &dyn crate::db::ExpandDatabase) -> impl fmt::Display + 'a {
78-
_ = db;
79-
UnescapedDisplay { name: self }
80-
}
81-
#[doc(hidden)]
82-
pub fn display_no_db(self) -> impl fmt::Display + 'a {
83-
UnescapedDisplay { name: self }
84-
}
85-
}
86-
8772
impl Name {
88-
/// Note: this is private to make creating name from random string hard.
89-
/// Hopefully, this should allow us to integrate hygiene cleaner in the
90-
/// future, and to switch to interned representation of names.
9173
fn new_text(text: &str) -> Name {
92-
debug_assert!(!text.starts_with("r#"));
9374
Name { symbol: Symbol::intern(text), ctx: () }
9475
}
9576

@@ -99,12 +80,15 @@ impl Name {
9980
// Can't do that for all `SyntaxContextId`s because it breaks Salsa.
10081
ctx.remove_root_edition();
10182
_ = ctx;
102-
Self::new_text(text)
83+
match text.strip_prefix("r#") {
84+
Some(text) => Self::new_text(text),
85+
None => Self::new_text(text),
86+
}
10387
}
10488

10589
pub fn new_root(text: &str) -> Name {
10690
// The edition doesn't matter for hygiene.
107-
Self::new(text.trim_start_matches("r#"), SyntaxContextId::root(Edition::Edition2015))
91+
Self::new(text, SyntaxContextId::root(Edition::Edition2015))
10892
}
10993

11094
pub fn new_tuple_field(idx: usize) -> Name {
@@ -131,12 +115,22 @@ impl Name {
131115
}
132116

133117
pub fn new_lifetime(lt: &ast::Lifetime) -> Name {
134-
Self::new_text(lt.text().as_str().trim_start_matches("r#"))
118+
let text = lt.text();
119+
match text.strip_prefix("'r#") {
120+
Some(text) => Self::new_text(&format_smolstr!("'{text}")),
121+
None => Self::new_text(text.as_str()),
122+
}
135123
}
136124

137-
/// Resolve a name from the text of token.
138-
fn resolve(raw_text: &str) -> Name {
139-
Name::new_text(raw_text.trim_start_matches("r#"))
125+
pub fn new_symbol(symbol: Symbol, ctx: SyntaxContextId) -> Self {
126+
debug_assert!(!symbol.as_str().starts_with("r#"));
127+
_ = ctx;
128+
Self { symbol, ctx: () }
129+
}
130+
131+
// FIXME: This needs to go once we have hygiene
132+
pub fn new_symbol_root(sym: Symbol) -> Self {
133+
Self::new_symbol(sym, SyntaxContextId::root(Edition::Edition2015))
140134
}
141135

142136
/// A fake name for things missing in the source code.
@@ -173,22 +167,19 @@ impl Name {
173167
self.symbol.as_str().parse().ok()
174168
}
175169

170+
/// Whether this name needs to be escaped in the given edition via `r#`.
171+
pub fn needs_escape(&self, edition: Edition) -> bool {
172+
is_raw_identifier(self.symbol.as_str(), edition)
173+
}
174+
176175
/// Returns the text this name represents if it isn't a tuple field.
177176
///
178177
/// Do not use this for user-facing text, use `display` instead to handle editions properly.
178+
// FIXME: This should take a database argument to hide the interning
179179
pub fn as_str(&self) -> &str {
180180
self.symbol.as_str()
181181
}
182182

183-
// FIXME: Remove this
184-
pub fn unescaped(&self) -> UnescapedName<'_> {
185-
UnescapedName(self)
186-
}
187-
188-
pub fn needs_escape(&self, edition: Edition) -> bool {
189-
is_raw_identifier(self.symbol.as_str(), edition)
190-
}
191-
192183
pub fn display<'a>(
193184
&'a self,
194185
db: &dyn crate::db::ExpandDatabase,
@@ -198,7 +189,7 @@ impl Name {
198189
self.display_no_db(edition)
199190
}
200191

201-
// FIXME: Remove this
192+
// FIXME: Remove this in favor of `display`, see fixme on `as_str`
202193
#[doc(hidden)]
203194
pub fn display_no_db(&self, edition: Edition) -> impl fmt::Display + '_ {
204195
Display { name: self, needs_escaping: is_raw_identifier(self.symbol.as_str(), edition) }
@@ -207,24 +198,6 @@ impl Name {
207198
pub fn symbol(&self) -> &Symbol {
208199
&self.symbol
209200
}
210-
211-
pub fn new_symbol(symbol: Symbol, ctx: SyntaxContextId) -> Self {
212-
debug_assert!(!symbol.as_str().starts_with("r#"));
213-
_ = ctx;
214-
Self { symbol, ctx: () }
215-
}
216-
217-
// FIXME: This needs to go once we have hygiene
218-
pub fn new_symbol_root(sym: Symbol) -> Self {
219-
debug_assert!(!sym.as_str().starts_with("r#"));
220-
Self { symbol: sym, ctx: () }
221-
}
222-
223-
// FIXME: Remove this
224-
#[inline]
225-
pub fn eq_ident(&self, ident: &str) -> bool {
226-
self.as_str() == ident.trim_start_matches("r#")
227-
}
228201
}
229202

230203
struct Display<'a> {
@@ -241,17 +214,6 @@ impl fmt::Display for Display<'_> {
241214
}
242215
}
243216

244-
struct UnescapedDisplay<'a> {
245-
name: UnescapedName<'a>,
246-
}
247-
248-
impl fmt::Display for UnescapedDisplay<'_> {
249-
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250-
let symbol = self.name.0.symbol.as_str();
251-
fmt::Display::fmt(symbol, f)
252-
}
253-
}
254-
255217
pub trait AsName {
256218
fn as_name(&self) -> Name;
257219
}
@@ -260,14 +222,14 @@ impl AsName for ast::NameRef {
260222
fn as_name(&self) -> Name {
261223
match self.as_tuple_field() {
262224
Some(idx) => Name::new_tuple_field(idx),
263-
None => Name::resolve(&self.text()),
225+
None => Name::new_root(&self.text()),
264226
}
265227
}
266228
}
267229

268230
impl AsName for ast::Name {
269231
fn as_name(&self) -> Name {
270-
Name::resolve(&self.text())
232+
Name::new_root(&self.text())
271233
}
272234
}
273235

@@ -282,7 +244,7 @@ impl AsName for ast::NameOrNameRef {
282244

283245
impl<Span> AsName for tt::Ident<Span> {
284246
fn as_name(&self) -> Name {
285-
Name::resolve(self.sym.as_str())
247+
Name::new_root(self.sym.as_str())
286248
}
287249
}
288250

@@ -300,6 +262,6 @@ impl AsName for ast::FieldKind {
300262

301263
impl AsName for base_db::Dependency {
302264
fn as_name(&self) -> Name {
303-
Name::new_text(&self.name)
265+
Name::new_root(&self.name)
304266
}
305267
}

0 commit comments

Comments
 (0)