Skip to content

Commit

Permalink
Remove Name::to_smol_str
Browse files Browse the repository at this point in the history
  • Loading branch information
Veykril committed Jul 16, 2024
1 parent df5f177 commit 2346a80
Show file tree
Hide file tree
Showing 54 changed files with 288 additions and 190 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 9 additions & 7 deletions crates/hir-def/src/import_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use itertools::Itertools;
use rustc_hash::FxHashSet;
use smallvec::SmallVec;
use stdx::{format_to, TupleExt};
use syntax::ToSmolStr;
use triomphe::Arc;

use crate::{
Expand Down Expand Up @@ -81,9 +82,9 @@ impl ImportMap {
.iter()
// We've only collected items, whose name cannot be tuple field so unwrapping is fine.
.flat_map(|(&item, (info, _))| {
info.iter()
.enumerate()
.map(move |(idx, info)| (item, info.name.to_smol_str(), idx as u32))
info.iter().enumerate().map(move |(idx, info)| {
(item, info.name.display(db.upcast()).to_smolstr(), idx as u32)
})
})
.collect();
importables.sort_by(|(_, l_info, _), (_, r_info, _)| {
Expand Down Expand Up @@ -412,28 +413,29 @@ pub fn search_dependencies(
for map in &import_maps {
op = op.add(map.fst.search(&automaton));
}
search_maps(&import_maps, op.union(), query)
search_maps(db, &import_maps, op.union(), query)
}
SearchMode::Fuzzy => {
let automaton = fst::automaton::Subsequence::new(&query.lowercased);

for map in &import_maps {
op = op.add(map.fst.search(&automaton));
}
search_maps(&import_maps, op.union(), query)
search_maps(db, &import_maps, op.union(), query)
}
SearchMode::Prefix => {
let automaton = fst::automaton::Str::new(&query.lowercased).starts_with();

for map in &import_maps {
op = op.add(map.fst.search(&automaton));
}
search_maps(&import_maps, op.union(), query)
search_maps(db, &import_maps, op.union(), query)
}
}
}

fn search_maps(
db: &dyn DefDatabase,
import_maps: &[Arc<ImportMap>],
mut stream: fst::map::Union<'_>,
query: &Query,
Expand All @@ -459,7 +461,7 @@ fn search_maps(
query.search_mode.check(
&query.query,
query.case_sensitive,
&info.name.to_smol_str(),
&info.name.display(db.upcast()).to_smolstr(),
)
});
res.extend(iter.map(TupleExt::head));
Expand Down
3 changes: 2 additions & 1 deletion crates/hir-def/src/macro_expansion_tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use hir_expand::{
span_map::SpanMapRef,
InFile, MacroFileId, MacroFileIdExt,
};
use intern::Symbol;
use span::Span;
use stdx::{format_to, format_to_acc};
use syntax::{
Expand Down Expand Up @@ -55,7 +56,7 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream
"#
.into(),
ProcMacro {
name: "identity_when_valid".into(),
name: Symbol::intern("identity_when_valid"),
kind: ProcMacroKind::Attr,
expander: sync::Arc::new(IdentityWhenValidProcMacroExpander),
disabled: false,
Expand Down
2 changes: 1 addition & 1 deletion crates/hir-def/src/nameres/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ pub(super) fn collect_defs(db: &dyn DefDatabase, def_map: DefMap, tree_id: TreeI
.iter()
.enumerate()
.map(|(idx, it)| {
let name = Name::new(&it.name, tt::IdentIsRaw::No, ctx);
let name = Name::new_symbol(it.name.clone(), ctx);
(
name,
if !db.expand_proc_attr_macros() {
Expand Down
3 changes: 2 additions & 1 deletion crates/hir-def/src/nameres/mod_resolution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use arrayvec::ArrayVec;
use base_db::{AnchoredPath, FileId};
use hir_expand::{name::Name, HirFileIdExt, MacroFileIdExt};
use limit::Limit;
use syntax::ToSmolStr as _;

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

Expand Down Expand Up @@ -33,7 +34,7 @@ impl ModDir {
let path = match attr_path {
None => {
let mut path = self.dir_path.clone();
path.push(&name.unescaped().to_smol_str());
path.push(&name.unescaped().display_no_db().to_smolstr());
path
}
Some(attr_path) => {
Expand Down
4 changes: 2 additions & 2 deletions crates/hir-def/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use crate::{
};
use hir_expand::name::Name;
use intern::Interned;
use syntax::ast;
use syntax::{ast, ToSmolStr};

pub use hir_expand::mod_path::{path, ModPath, PathKind};

Expand All @@ -29,7 +29,7 @@ impl Display for ImportAlias {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ImportAlias::Underscore => f.write_str("_"),
ImportAlias::Alias(name) => f.write_str(&name.to_smol_str()),
ImportAlias::Alias(name) => f.write_str(&name.display_no_db().to_smolstr()),
}
}
}
Expand Down
39 changes: 14 additions & 25 deletions crates/hir-expand/src/name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::fmt;

use intern::{sym, Symbol};
use span::SyntaxContextId;
use syntax::{ast, format_smolstr, utils::is_raw_identifier, SmolStr};
use syntax::{ast, utils::is_raw_identifier};

/// `Name` is a wrapper around string, which is used in hir for both references
/// and declarations. In theory, names should also carry hygiene info, but we are
Expand Down Expand Up @@ -59,21 +59,14 @@ impl PartialEq<Name> for Symbol {
pub struct UnescapedName<'a>(&'a Name);

impl UnescapedName<'_> {
/// Returns the textual representation of this name as a [`SmolStr`]. Prefer using this over
/// [`ToString::to_string`] if possible as this conversion is cheaper in the general case.
pub fn to_smol_str(&self) -> SmolStr {
let it = self.0.symbol.as_str();
if let Some(stripped) = it.strip_prefix("r#") {
SmolStr::new(stripped)
} else {
it.into()
}
}

pub fn display(&self, db: &dyn crate::db::ExpandDatabase) -> impl fmt::Display + '_ {
_ = db;
UnescapedDisplay { name: self }
}
#[doc(hidden)]
pub fn display_no_db(&self) -> impl fmt::Display + '_ {
UnescapedDisplay { name: self }
}
}

impl Name {
Expand All @@ -88,7 +81,7 @@ impl Name {
_ = ctx;
Name {
symbol: if raw.yes() {
Symbol::intern(&format_smolstr!("{}{text}", raw.as_str()))
Symbol::intern(&format!("{}{text}", raw.as_str()))
} else {
Symbol::intern(text)
},
Expand Down Expand Up @@ -118,9 +111,7 @@ impl Name {
// Keywords (in the current edition) *can* be used as a name in earlier editions of
// Rust, e.g. "try" in Rust 2015. Even in such cases, we keep track of them in their
// escaped form.
None if is_raw_identifier(raw_text) => {
Name::new_text(&format_smolstr!("r#{}", raw_text))
}
None if is_raw_identifier(raw_text) => Name::new_text(&format!("r#{}", raw_text)),
_ => Name::new_text(raw_text),
}
}
Expand Down Expand Up @@ -151,7 +142,7 @@ impl Name {
/// creating desugared locals and labels. The caller is responsible for picking an index
/// that is stable across re-executions
pub fn generate_new_name(idx: usize) -> Name {
Name::new_text(&format_smolstr!("<ra@gennew>{idx}"))
Name::new_text(&format!("<ra@gennew>{idx}"))
}

/// Returns the tuple index this name represents if it is a tuple field.
Expand All @@ -164,14 +155,6 @@ impl Name {
self.symbol.as_str()
}

// FIXME: Remove this
/// Returns the textual representation of this name as a [`SmolStr`].
/// Prefer using this over [`ToString::to_string`] if possible as this conversion is cheaper in
/// the general case.
pub fn to_smol_str(&self) -> SmolStr {
self.symbol.as_str().into()
}

pub fn unescaped(&self) -> UnescapedName<'_> {
UnescapedName(self)
}
Expand All @@ -185,6 +168,12 @@ impl Name {
Display { name: self }
}

// FIXME: Remove this
#[doc(hidden)]
pub fn display_no_db(&self) -> impl fmt::Display + '_ {
Display { name: self }
}

pub fn symbol(&self) -> &Symbol {
&self.symbol
}
Expand Down
4 changes: 2 additions & 2 deletions crates/hir-expand/src/proc_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ use core::fmt;
use std::{panic::RefUnwindSafe, sync};

use base_db::{CrateId, Env};
use intern::Symbol;
use rustc_hash::FxHashMap;
use span::Span;
use stdx::never;
use syntax::SmolStr;
use triomphe::Arc;

use crate::{db::ExpandDatabase, tt, ExpandError, ExpandResult};
Expand Down Expand Up @@ -53,7 +53,7 @@ pub type ProcMacros = FxHashMap<CrateId, ProcMacroLoadResult>;

#[derive(Debug, Clone)]
pub struct ProcMacro {
pub name: SmolStr,
pub name: Symbol,
pub kind: ProcMacroKind,
pub expander: sync::Arc<dyn ProcMacroExpander>,
pub disabled: bool,
Expand Down
36 changes: 22 additions & 14 deletions crates/hir-ty/src/diagnostics/decl_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use intern::sym;
use stdx::{always, never};
use syntax::{
ast::{self, HasName},
AstNode, AstPtr,
AstNode, AstPtr, ToSmolStr,
};

use crate::db::HirDatabase;
Expand Down Expand Up @@ -326,7 +326,9 @@ impl<'a> DeclValidator<'a> {
let bind_name = &body.bindings[*id].name;
let replacement = Replacement {
current_name: bind_name.clone(),
suggested_text: to_lower_snake_case(&bind_name.to_smol_str())?,
suggested_text: to_lower_snake_case(
&bind_name.display_no_db().to_smolstr(),
)?,
expected_case: CaseType::LowerSnakeCase,
};
Some((pat_id, replacement))
Expand Down Expand Up @@ -406,10 +408,12 @@ impl<'a> DeclValidator<'a> {
let mut struct_fields_replacements = fields
.iter()
.filter_map(|(_, field)| {
to_lower_snake_case(&field.name.to_smol_str()).map(|new_name| Replacement {
current_name: field.name.clone(),
suggested_text: new_name,
expected_case: CaseType::LowerSnakeCase,
to_lower_snake_case(&field.name.display_no_db().to_smolstr()).map(|new_name| {
Replacement {
current_name: field.name.clone(),
suggested_text: new_name,
expected_case: CaseType::LowerSnakeCase,
}
})
})
.peekable();
Expand Down Expand Up @@ -498,7 +502,7 @@ impl<'a> DeclValidator<'a> {
.variants
.iter()
.filter_map(|(_, name)| {
to_camel_case(&name.to_smol_str()).map(|new_name| Replacement {
to_camel_case(&name.display_no_db().to_smolstr()).map(|new_name| Replacement {
current_name: name.clone(),
suggested_text: new_name,
expected_case: CaseType::UpperCamelCase,
Expand Down Expand Up @@ -565,10 +569,12 @@ impl<'a> DeclValidator<'a> {
let mut variant_field_replacements = fields
.iter()
.filter_map(|(_, field)| {
to_lower_snake_case(&field.name.to_smol_str()).map(|new_name| Replacement {
current_name: field.name.clone(),
suggested_text: new_name,
expected_case: CaseType::LowerSnakeCase,
to_lower_snake_case(&field.name.display_no_db().to_smolstr()).map(|new_name| {
Replacement {
current_name: field.name.clone(),
suggested_text: new_name,
expected_case: CaseType::LowerSnakeCase,
}
})
})
.peekable();
Expand Down Expand Up @@ -705,9 +711,11 @@ impl<'a> DeclValidator<'a> {
CaseType::UpperSnakeCase => to_upper_snake_case,
CaseType::UpperCamelCase => to_camel_case,
};
let Some(replacement) = to_expected_case_type(&name.to_smol_str()).map(|new_name| {
Replacement { current_name: name.clone(), suggested_text: new_name, expected_case }
}) else {
let Some(replacement) =
to_expected_case_type(&name.display(self.db.upcast()).to_smolstr()).map(|new_name| {
Replacement { current_name: name.clone(), suggested_text: new_name, expected_case }
})
else {
return;
};

Expand Down
24 changes: 18 additions & 6 deletions crates/hir-ty/src/layout/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use either::Either;
use hir_def::db::DefDatabase;
use project_model::{target_data_layout::RustcDataLayoutConfig, Sysroot};
use rustc_hash::FxHashMap;
use syntax::ToSmolStr;
use test_fixture::WithFixture;
use triomphe::Arc;

Expand Down Expand Up @@ -40,14 +41,20 @@ fn eval_goal(ra_fixture: &str, minicore: &str) -> Result<Arc<Layout>, LayoutErro
let adt_or_type_alias_id = scope.declarations().find_map(|x| match x {
hir_def::ModuleDefId::AdtId(x) => {
let name = match x {
hir_def::AdtId::StructId(x) => db.struct_data(x).name.to_smol_str(),
hir_def::AdtId::UnionId(x) => db.union_data(x).name.to_smol_str(),
hir_def::AdtId::EnumId(x) => db.enum_data(x).name.to_smol_str(),
hir_def::AdtId::StructId(x) => {
db.struct_data(x).name.display_no_db().to_smolstr()
}
hir_def::AdtId::UnionId(x) => {
db.union_data(x).name.display_no_db().to_smolstr()
}
hir_def::AdtId::EnumId(x) => {
db.enum_data(x).name.display_no_db().to_smolstr()
}
};
(name == "Goal").then_some(Either::Left(x))
}
hir_def::ModuleDefId::TypeAliasId(x) => {
let name = db.type_alias_data(x).name.to_smol_str();
let name = db.type_alias_data(x).name.display_no_db().to_smolstr();
(name == "Goal").then_some(Either::Right(x))
}
_ => None,
Expand Down Expand Up @@ -87,14 +94,19 @@ fn eval_expr(ra_fixture: &str, minicore: &str) -> Result<Arc<Layout>, LayoutErro
.declarations()
.find_map(|x| match x {
hir_def::ModuleDefId::FunctionId(x) => {
let name = db.function_data(x).name.to_smol_str();
let name = db.function_data(x).name.display_no_db().to_smolstr();
(name == "main").then_some(x)
}
_ => None,
})
.unwrap();
let hir_body = db.body(function_id.into());
let b = hir_body.bindings.iter().find(|x| x.1.name.to_smol_str() == "goal").unwrap().0;
let b = hir_body
.bindings
.iter()
.find(|x| x.1.name.display_no_db().to_smolstr() == "goal")
.unwrap()
.0;
let infer = db.infer(function_id.into());
let goal_ty = infer.type_of_binding[b].clone();
db.layout_of_ty(goal_ty, db.trait_environment(function_id.into()))
Expand Down
4 changes: 2 additions & 2 deletions crates/hir/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ use span::{Edition, MacroCallId};
use stdx::{impl_from, never};
use syntax::{
ast::{self, HasAttrs as _, HasName},
format_smolstr, AstNode, AstPtr, SmolStr, SyntaxNode, SyntaxNodePtr, TextRange, T,
format_smolstr, AstNode, AstPtr, SmolStr, SyntaxNode, SyntaxNodePtr, TextRange, ToSmolStr, T,
};
use triomphe::Arc;

Expand Down Expand Up @@ -4607,7 +4607,7 @@ impl Type {
) -> impl Iterator<Item = SmolStr> + 'a {
// iterate the lifetime
self.as_adt()
.and_then(|a| a.lifetime(db).map(|lt| lt.name.to_smol_str()))
.and_then(|a| a.lifetime(db).map(|lt| lt.name.display_no_db().to_smolstr()))
.into_iter()
// add the type and const parameters
.chain(self.type_and_const_arguments(db))
Expand Down
Loading

0 comments on commit 2346a80

Please sign in to comment.