Remove Name::to_smol_str

This commit is contained in:
Lukas Wirth 2024-07-16 12:43:58 +02:00
parent df5f1777b8
commit 2346a80ab4
54 changed files with 288 additions and 190 deletions

1
Cargo.lock generated
View file

@ -971,6 +971,7 @@ dependencies = [
"crossbeam-channel", "crossbeam-channel",
"hir-expand", "hir-expand",
"ide-db", "ide-db",
"intern",
"itertools", "itertools",
"paths", "paths",
"proc-macro-api", "proc-macro-api",

View file

@ -9,6 +9,7 @@ use itertools::Itertools;
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use smallvec::SmallVec; use smallvec::SmallVec;
use stdx::{format_to, TupleExt}; use stdx::{format_to, TupleExt};
use syntax::ToSmolStr;
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
@ -81,9 +82,9 @@ impl ImportMap {
.iter() .iter()
// We've only collected items, whose name cannot be tuple field so unwrapping is fine. // We've only collected items, whose name cannot be tuple field so unwrapping is fine.
.flat_map(|(&item, (info, _))| { .flat_map(|(&item, (info, _))| {
info.iter() info.iter().enumerate().map(move |(idx, info)| {
.enumerate() (item, info.name.display(db.upcast()).to_smolstr(), idx as u32)
.map(move |(idx, info)| (item, info.name.to_smol_str(), idx as u32)) })
}) })
.collect(); .collect();
importables.sort_by(|(_, l_info, _), (_, r_info, _)| { importables.sort_by(|(_, l_info, _), (_, r_info, _)| {
@ -412,7 +413,7 @@ pub fn search_dependencies(
for map in &import_maps { for map in &import_maps {
op = op.add(map.fst.search(&automaton)); op = op.add(map.fst.search(&automaton));
} }
search_maps(&import_maps, op.union(), query) search_maps(db, &import_maps, op.union(), query)
} }
SearchMode::Fuzzy => { SearchMode::Fuzzy => {
let automaton = fst::automaton::Subsequence::new(&query.lowercased); let automaton = fst::automaton::Subsequence::new(&query.lowercased);
@ -420,7 +421,7 @@ pub fn search_dependencies(
for map in &import_maps { for map in &import_maps {
op = op.add(map.fst.search(&automaton)); op = op.add(map.fst.search(&automaton));
} }
search_maps(&import_maps, op.union(), query) search_maps(db, &import_maps, op.union(), query)
} }
SearchMode::Prefix => { SearchMode::Prefix => {
let automaton = fst::automaton::Str::new(&query.lowercased).starts_with(); let automaton = fst::automaton::Str::new(&query.lowercased).starts_with();
@ -428,12 +429,13 @@ pub fn search_dependencies(
for map in &import_maps { for map in &import_maps {
op = op.add(map.fst.search(&automaton)); 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( fn search_maps(
db: &dyn DefDatabase,
import_maps: &[Arc<ImportMap>], import_maps: &[Arc<ImportMap>],
mut stream: fst::map::Union<'_>, mut stream: fst::map::Union<'_>,
query: &Query, query: &Query,
@ -459,7 +461,7 @@ fn search_maps(
query.search_mode.check( query.search_mode.check(
&query.query, &query.query,
query.case_sensitive, query.case_sensitive,
&info.name.to_smol_str(), &info.name.display(db.upcast()).to_smolstr(),
) )
}); });
res.extend(iter.map(TupleExt::head)); res.extend(iter.map(TupleExt::head));

View file

@ -24,6 +24,7 @@ use hir_expand::{
span_map::SpanMapRef, span_map::SpanMapRef,
InFile, MacroFileId, MacroFileIdExt, InFile, MacroFileId, MacroFileIdExt,
}; };
use intern::Symbol;
use span::Span; use span::Span;
use stdx::{format_to, format_to_acc}; use stdx::{format_to, format_to_acc};
use syntax::{ use syntax::{
@ -55,7 +56,7 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream
"# "#
.into(), .into(),
ProcMacro { ProcMacro {
name: "identity_when_valid".into(), name: Symbol::intern("identity_when_valid"),
kind: ProcMacroKind::Attr, kind: ProcMacroKind::Attr,
expander: sync::Arc::new(IdentityWhenValidProcMacroExpander), expander: sync::Arc::new(IdentityWhenValidProcMacroExpander),
disabled: false, disabled: false,

View file

@ -82,7 +82,7 @@ pub(super) fn collect_defs(db: &dyn DefDatabase, def_map: DefMap, tree_id: TreeI
.iter() .iter()
.enumerate() .enumerate()
.map(|(idx, it)| { .map(|(idx, it)| {
let name = Name::new(&it.name, tt::IdentIsRaw::No, ctx); let name = Name::new_symbol(it.name.clone(), ctx);
( (
name, name,
if !db.expand_proc_attr_macros() { if !db.expand_proc_attr_macros() {

View file

@ -3,6 +3,7 @@ use arrayvec::ArrayVec;
use base_db::{AnchoredPath, FileId}; use base_db::{AnchoredPath, FileId};
use hir_expand::{name::Name, HirFileIdExt, MacroFileIdExt}; use hir_expand::{name::Name, HirFileIdExt, MacroFileIdExt};
use limit::Limit; use limit::Limit;
use syntax::ToSmolStr as _;
use crate::{db::DefDatabase, HirFileId}; use crate::{db::DefDatabase, HirFileId};
@ -33,7 +34,7 @@ impl ModDir {
let path = match attr_path { let path = match attr_path {
None => { None => {
let mut path = self.dir_path.clone(); let mut path = self.dir_path.clone();
path.push(&name.unescaped().to_smol_str()); path.push(&name.unescaped().display_no_db().to_smolstr());
path path
} }
Some(attr_path) => { Some(attr_path) => {

View file

@ -13,7 +13,7 @@ use crate::{
}; };
use hir_expand::name::Name; use hir_expand::name::Name;
use intern::Interned; use intern::Interned;
use syntax::ast; use syntax::{ast, ToSmolStr};
pub use hir_expand::mod_path::{path, ModPath, PathKind}; pub use hir_expand::mod_path::{path, ModPath, PathKind};
@ -29,7 +29,7 @@ impl Display for ImportAlias {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
ImportAlias::Underscore => f.write_str("_"), 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()),
} }
} }
} }

View file

@ -4,7 +4,7 @@ use std::fmt;
use intern::{sym, Symbol}; use intern::{sym, Symbol};
use span::SyntaxContextId; 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 /// `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 /// and declarations. In theory, names should also carry hygiene info, but we are
@ -59,21 +59,14 @@ impl PartialEq<Name> for Symbol {
pub struct UnescapedName<'a>(&'a Name); pub struct UnescapedName<'a>(&'a Name);
impl UnescapedName<'_> { 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 + '_ { pub fn display(&self, db: &dyn crate::db::ExpandDatabase) -> impl fmt::Display + '_ {
_ = db; _ = db;
UnescapedDisplay { name: self } UnescapedDisplay { name: self }
} }
#[doc(hidden)]
pub fn display_no_db(&self) -> impl fmt::Display + '_ {
UnescapedDisplay { name: self }
}
} }
impl Name { impl Name {
@ -88,7 +81,7 @@ impl Name {
_ = ctx; _ = ctx;
Name { Name {
symbol: if raw.yes() { symbol: if raw.yes() {
Symbol::intern(&format_smolstr!("{}{text}", raw.as_str())) Symbol::intern(&format!("{}{text}", raw.as_str()))
} else { } else {
Symbol::intern(text) Symbol::intern(text)
}, },
@ -118,9 +111,7 @@ impl Name {
// Keywords (in the current edition) *can* be used as a name in earlier editions of // 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 // Rust, e.g. "try" in Rust 2015. Even in such cases, we keep track of them in their
// escaped form. // escaped form.
None if is_raw_identifier(raw_text) => { None if is_raw_identifier(raw_text) => Name::new_text(&format!("r#{}", raw_text)),
Name::new_text(&format_smolstr!("r#{}", raw_text))
}
_ => Name::new_text(raw_text), _ => Name::new_text(raw_text),
} }
} }
@ -151,7 +142,7 @@ impl Name {
/// creating desugared locals and labels. The caller is responsible for picking an index /// creating desugared locals and labels. The caller is responsible for picking an index
/// that is stable across re-executions /// that is stable across re-executions
pub fn generate_new_name(idx: usize) -> Name { 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. /// Returns the tuple index this name represents if it is a tuple field.
@ -164,14 +155,6 @@ impl Name {
self.symbol.as_str() 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<'_> { pub fn unescaped(&self) -> UnescapedName<'_> {
UnescapedName(self) UnescapedName(self)
} }
@ -185,6 +168,12 @@ impl Name {
Display { name: self } 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 { pub fn symbol(&self) -> &Symbol {
&self.symbol &self.symbol
} }

View file

@ -4,10 +4,10 @@ use core::fmt;
use std::{panic::RefUnwindSafe, sync}; use std::{panic::RefUnwindSafe, sync};
use base_db::{CrateId, Env}; use base_db::{CrateId, Env};
use intern::Symbol;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use span::Span; use span::Span;
use stdx::never; use stdx::never;
use syntax::SmolStr;
use triomphe::Arc; use triomphe::Arc;
use crate::{db::ExpandDatabase, tt, ExpandError, ExpandResult}; use crate::{db::ExpandDatabase, tt, ExpandError, ExpandResult};
@ -53,7 +53,7 @@ pub type ProcMacros = FxHashMap<CrateId, ProcMacroLoadResult>;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ProcMacro { pub struct ProcMacro {
pub name: SmolStr, pub name: Symbol,
pub kind: ProcMacroKind, pub kind: ProcMacroKind,
pub expander: sync::Arc<dyn ProcMacroExpander>, pub expander: sync::Arc<dyn ProcMacroExpander>,
pub disabled: bool, pub disabled: bool,

View file

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

View file

@ -3,6 +3,7 @@ use either::Either;
use hir_def::db::DefDatabase; use hir_def::db::DefDatabase;
use project_model::{target_data_layout::RustcDataLayoutConfig, Sysroot}; use project_model::{target_data_layout::RustcDataLayoutConfig, Sysroot};
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use syntax::ToSmolStr;
use test_fixture::WithFixture; use test_fixture::WithFixture;
use triomphe::Arc; use triomphe::Arc;
@ -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 { let adt_or_type_alias_id = scope.declarations().find_map(|x| match x {
hir_def::ModuleDefId::AdtId(x) => { hir_def::ModuleDefId::AdtId(x) => {
let name = match x { let name = match x {
hir_def::AdtId::StructId(x) => db.struct_data(x).name.to_smol_str(), hir_def::AdtId::StructId(x) => {
hir_def::AdtId::UnionId(x) => db.union_data(x).name.to_smol_str(), db.struct_data(x).name.display_no_db().to_smolstr()
hir_def::AdtId::EnumId(x) => db.enum_data(x).name.to_smol_str(), }
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)) (name == "Goal").then_some(Either::Left(x))
} }
hir_def::ModuleDefId::TypeAliasId(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)) (name == "Goal").then_some(Either::Right(x))
} }
_ => None, _ => None,
@ -87,14 +94,19 @@ fn eval_expr(ra_fixture: &str, minicore: &str) -> Result<Arc<Layout>, LayoutErro
.declarations() .declarations()
.find_map(|x| match x { .find_map(|x| match x {
hir_def::ModuleDefId::FunctionId(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) (name == "main").then_some(x)
} }
_ => None, _ => None,
}) })
.unwrap(); .unwrap();
let hir_body = db.body(function_id.into()); 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 infer = db.infer(function_id.into());
let goal_ty = infer.type_of_binding[b].clone(); let goal_ty = infer.type_of_binding[b].clone();
db.layout_of_ty(goal_ty, db.trait_environment(function_id.into())) db.layout_of_ty(goal_ty, db.trait_environment(function_id.into()))

View file

@ -82,7 +82,7 @@ use span::{Edition, MacroCallId};
use stdx::{impl_from, never}; use stdx::{impl_from, never};
use syntax::{ use syntax::{
ast::{self, HasAttrs as _, HasName}, 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; use triomphe::Arc;
@ -4607,7 +4607,7 @@ impl Type {
) -> impl Iterator<Item = SmolStr> + 'a { ) -> impl Iterator<Item = SmolStr> + 'a {
// iterate the lifetime // iterate the lifetime
self.as_adt() 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() .into_iter()
// add the type and const parameters // add the type and const parameters
.chain(self.type_and_const_arguments(db)) .chain(self.type_and_const_arguments(db))

View file

@ -10,7 +10,7 @@ use hir_def::{
}; };
use hir_expand::{HirFileId, InFile}; use hir_expand::{HirFileId, InFile};
use hir_ty::{db::HirDatabase, display::HirDisplay}; use hir_ty::{db::HirDatabase, display::HirDisplay};
use syntax::{ast::HasName, AstNode, AstPtr, SmolStr, SyntaxNode, SyntaxNodePtr}; use syntax::{ast::HasName, AstNode, AstPtr, SmolStr, SyntaxNode, SyntaxNodePtr, ToSmolStr};
use crate::{Module, ModuleDef, Semantics}; use crate::{Module, ModuleDef, Semantics};
@ -258,10 +258,18 @@ impl<'a> SymbolCollector<'a> {
fn def_with_body_id_name(&self, body_id: DefWithBodyId) -> Option<SmolStr> { fn def_with_body_id_name(&self, body_id: DefWithBodyId) -> Option<SmolStr> {
match body_id { match body_id {
DefWithBodyId::FunctionId(id) => Some(self.db.function_data(id).name.to_smol_str()), DefWithBodyId::FunctionId(id) => {
DefWithBodyId::StaticId(id) => Some(self.db.static_data(id).name.to_smol_str()), Some(self.db.function_data(id).name.display_no_db().to_smolstr())
DefWithBodyId::ConstId(id) => Some(self.db.const_data(id).name.as_ref()?.to_smol_str()), }
DefWithBodyId::VariantId(id) => Some(self.db.enum_variant_data(id).name.to_smol_str()), DefWithBodyId::StaticId(id) => {
Some(self.db.static_data(id).name.display_no_db().to_smolstr())
}
DefWithBodyId::ConstId(id) => {
Some(self.db.const_data(id).name.as_ref()?.display_no_db().to_smolstr())
}
DefWithBodyId::VariantId(id) => {
Some(self.db.enum_variant_data(id).name.display_no_db().to_smolstr())
}
DefWithBodyId::InTypeConstId(_) => Some("in type const".into()), DefWithBodyId::InTypeConstId(_) => Some("in type const".into()),
} }
} }

View file

@ -7,7 +7,7 @@ use ide_db::{
FxHashMap, FxHashSet, FxHashMap, FxHashSet,
}; };
use itertools::Itertools; use itertools::Itertools;
use syntax::{ast, ted, AstNode, SmolStr, SyntaxNode}; use syntax::{ast, ted, AstNode, SmolStr, SyntaxNode, ToSmolStr};
use text_edit::TextRange; use text_edit::TextRange;
use crate::{ use crate::{
@ -251,7 +251,7 @@ fn generate_field_names(ctx: &AssistContext<'_>, data: &StructEditData) -> Vec<(
.visible_fields .visible_fields
.iter() .iter()
.map(|field| { .map(|field| {
let field_name = field.name(ctx.db()).to_smol_str(); let field_name = field.name(ctx.db()).display_no_db().to_smolstr();
let new_name = new_field_name(field_name.clone(), &data.names_in_scope); let new_name = new_field_name(field_name.clone(), &data.names_in_scope);
(field_name, new_name) (field_name, new_name)
}) })

View file

@ -1,6 +1,6 @@
use syntax::{ use syntax::{
ast::{self, make}, ast::{self, make},
AstNode, AstNode, ToSmolStr,
}; };
use crate::{AssistContext, AssistId, Assists}; use crate::{AssistContext, AssistId, Assists};
@ -45,8 +45,9 @@ pub(crate) fn fill_record_pattern_fields(acc: &mut Assists, ctx: &AssistContext<
let new_field_list = let new_field_list =
make::record_pat_field_list(old_field_list.fields(), None).clone_for_update(); make::record_pat_field_list(old_field_list.fields(), None).clone_for_update();
for (f, _) in missing_fields.iter() { for (f, _) in missing_fields.iter() {
let field = let field = make::record_pat_field_shorthand(make::name_ref(
make::record_pat_field_shorthand(make::name_ref(&f.name(ctx.sema.db).to_smol_str())); &f.name(ctx.sema.db).display_no_db().to_smolstr(),
));
new_field_list.add_field(field.clone_for_update()); new_field_list.add_field(field.clone_for_update());
} }

View file

@ -4,7 +4,7 @@ use hir::{
use ide_db::base_db::FileId; use ide_db::base_db::FileId;
use syntax::{ use syntax::{
ast::{self, edit_in_place::HasVisibilityEdit, make, HasVisibility as _}, ast::{self, edit_in_place::HasVisibilityEdit, make, HasVisibility as _},
AstNode, TextRange, AstNode, TextRange, ToSmolStr,
}; };
use crate::{AssistContext, AssistId, AssistKind, Assists}; use crate::{AssistContext, AssistId, AssistKind, Assists};
@ -48,7 +48,7 @@ fn add_vis_to_referenced_module_def(acc: &mut Assists, ctx: &AssistContext<'_>)
let (_, def) = module let (_, def) = module
.scope(ctx.db(), None) .scope(ctx.db(), None)
.into_iter() .into_iter()
.find(|(name, _)| name.to_smol_str() == name_ref.text().as_str())?; .find(|(name, _)| name.display_no_db().to_smolstr() == name_ref.text().as_str())?;
let ScopeDef::ModuleDef(def) = def else { let ScopeDef::ModuleDef(def) = def else {
return None; return None;
}; };

View file

@ -22,7 +22,7 @@ use syntax::{
WherePred, WherePred,
}, },
ted::{self, Position}, ted::{self, Position},
AstNode, NodeOrToken, SmolStr, SyntaxKind, AstNode, NodeOrToken, SmolStr, SyntaxKind, ToSmolStr,
}; };
// Assist: generate_delegate_trait // Assist: generate_delegate_trait
@ -170,11 +170,11 @@ impl Delegee {
for m in it.module(db).path_to_root(db).iter().rev() { for m in it.module(db).path_to_root(db).iter().rev() {
if let Some(name) = m.name(db) { if let Some(name) = m.name(db) {
s.push_str(&format!("{}::", name.to_smol_str())); s.push_str(&format!("{}::", name.display_no_db().to_smolstr()));
} }
} }
s.push_str(&it.name(db).to_smol_str()); s.push_str(&it.name(db).display_no_db().to_smolstr());
s s
} }
} }
@ -259,7 +259,7 @@ fn generate_impl(
strukt_params.clone(), strukt_params.clone(),
strukt_params.map(|params| params.to_generic_args()), strukt_params.map(|params| params.to_generic_args()),
delegee.is_auto(db), delegee.is_auto(db),
make::ty(&delegee.name(db).to_smol_str()), make::ty(&delegee.name(db).display_no_db().to_smolstr()),
strukt_ty, strukt_ty,
bound_def.where_clause(), bound_def.where_clause(),
ast_strukt.where_clause(), ast_strukt.where_clause(),
@ -349,7 +349,8 @@ fn generate_impl(
let type_gen_args = strukt_params.clone().map(|params| params.to_generic_args()); let type_gen_args = strukt_params.clone().map(|params| params.to_generic_args());
let path_type = make::ty(&trait_.name(db).to_smol_str()).clone_for_update(); let path_type =
make::ty(&trait_.name(db).display_no_db().to_smolstr()).clone_for_update();
transform_impl(ctx, ast_strukt, &old_impl, &transform_args, path_type.syntax())?; transform_impl(ctx, ast_strukt, &old_impl, &transform_args, path_type.syntax())?;
// 3) Generate delegate trait impl // 3) Generate delegate trait impl

View file

@ -26,7 +26,7 @@ use std::iter;
use hir::{sym, HasAttrs, ImportPathConfig, Name, ScopeDef, Variant}; use hir::{sym, HasAttrs, ImportPathConfig, Name, ScopeDef, Variant};
use ide_db::{imports::import_assets::LocatedImport, RootDatabase, SymbolKind}; use ide_db::{imports::import_assets::LocatedImport, RootDatabase, SymbolKind};
use syntax::{ast, SmolStr}; use syntax::{ast, SmolStr, ToSmolStr};
use crate::{ use crate::{
context::{ context::{
@ -541,13 +541,21 @@ impl Completions {
} }
pub(crate) fn add_lifetime(&mut self, ctx: &CompletionContext<'_>, name: hir::Name) { pub(crate) fn add_lifetime(&mut self, ctx: &CompletionContext<'_>, name: hir::Name) {
CompletionItem::new(SymbolKind::LifetimeParam, ctx.source_range(), name.to_smol_str()) CompletionItem::new(
.add_to(self, ctx.db) SymbolKind::LifetimeParam,
ctx.source_range(),
name.display_no_db().to_smolstr(),
)
.add_to(self, ctx.db)
} }
pub(crate) fn add_label(&mut self, ctx: &CompletionContext<'_>, name: hir::Name) { pub(crate) fn add_label(&mut self, ctx: &CompletionContext<'_>, name: hir::Name) {
CompletionItem::new(SymbolKind::Label, ctx.source_range(), name.to_smol_str()) CompletionItem::new(
.add_to(self, ctx.db) SymbolKind::Label,
ctx.source_range(),
name.display_no_db().to_smolstr(),
)
.add_to(self, ctx.db)
} }
pub(crate) fn add_variant_pat( pub(crate) fn add_variant_pat(

View file

@ -2,7 +2,7 @@
use hir::ScopeDef; use hir::ScopeDef;
use ide_db::{documentation::HasDocs, SymbolKind}; use ide_db::{documentation::HasDocs, SymbolKind};
use itertools::Itertools; use itertools::Itertools;
use syntax::SmolStr; use syntax::{SmolStr, ToSmolStr};
use crate::{ use crate::{
context::{CompletionContext, ExistingDerives, PathCompletionCtx, Qualified}, context::{CompletionContext, ExistingDerives, PathCompletionCtx, Qualified},
@ -62,7 +62,7 @@ pub(crate) fn complete_derive_path(
_ => return acc.add_macro(ctx, path_ctx, mac, name), _ => return acc.add_macro(ctx, path_ctx, mac, name),
}; };
let name_ = name.to_smol_str(); let name_ = name.display_no_db().to_smolstr();
let find = DEFAULT_DERIVE_DEPENDENCIES let find = DEFAULT_DERIVE_DEPENDENCIES
.iter() .iter()
.find(|derive_completion| derive_completion.label == name_); .find(|derive_completion| derive_completion.label == name_);
@ -75,7 +75,7 @@ pub(crate) fn complete_derive_path(
!existing_derives !existing_derives
.iter() .iter()
.map(|it| it.name(ctx.db)) .map(|it| it.name(ctx.db))
.any(|it| it.to_smol_str() == dependency) .any(|it| it.display_no_db().to_smolstr() == dependency)
}, },
)); ));
let lookup = components.join(", "); let lookup = components.join(", ");

View file

@ -2,6 +2,7 @@
use hir::Name; use hir::Name;
use ide_db::{documentation::HasDocs, SymbolKind}; use ide_db::{documentation::HasDocs, SymbolKind};
use syntax::ToSmolStr;
use crate::{context::CompletionContext, CompletionItem, CompletionItemKind}; use crate::{context::CompletionContext, CompletionItem, CompletionItemKind};
@ -18,7 +19,7 @@ pub(crate) fn complete_extern_crate(acc: &mut Completions, ctx: &CompletionConte
let mut item = CompletionItem::new( let mut item = CompletionItem::new(
CompletionItemKind::SymbolKind(SymbolKind::Module), CompletionItemKind::SymbolKind(SymbolKind::Module),
ctx.source_range(), ctx.source_range(),
name.to_smol_str(), name.display_no_db().to_smolstr(),
); );
item.set_documentation(module.docs(ctx.db)); item.set_documentation(module.docs(ctx.db));

View file

@ -5,7 +5,7 @@ use ide_db::imports::{
insert_use::ImportScope, insert_use::ImportScope,
}; };
use itertools::Itertools; use itertools::Itertools;
use syntax::{ast, AstNode, SyntaxNode, T}; use syntax::{ast, AstNode, SyntaxNode, ToSmolStr, T};
use crate::{ use crate::{
context::{ context::{
@ -424,7 +424,7 @@ fn compute_fuzzy_completion_order_key(
cov_mark::hit!(certain_fuzzy_order_test); cov_mark::hit!(certain_fuzzy_order_test);
let import_name = match proposed_mod_path.segments().last() { let import_name = match proposed_mod_path.segments().last() {
// FIXME: nasty alloc, this is a hot path! // FIXME: nasty alloc, this is a hot path!
Some(name) => name.to_smol_str().to_ascii_lowercase(), Some(name) => name.display_no_db().to_smolstr().to_ascii_lowercase(),
None => return usize::MAX, None => return usize::MAX,
}; };
match import_name.match_indices(user_input_lowercased).next() { match import_name.match_indices(user_input_lowercased).next() {

View file

@ -3,7 +3,7 @@
use hir::{ModuleDef, ScopeDef}; use hir::{ModuleDef, ScopeDef};
use ide_db::{syntax_helpers::format_string::is_format_string, SymbolKind}; use ide_db::{syntax_helpers::format_string::is_format_string, SymbolKind};
use itertools::Itertools; use itertools::Itertools;
use syntax::{ast, AstToken, TextRange, TextSize}; use syntax::{ast, AstToken, TextRange, TextSize, ToSmolStr};
use crate::{context::CompletionContext, CompletionItem, CompletionItemKind, Completions}; use crate::{context::CompletionContext, CompletionItem, CompletionItemKind, Completions};
@ -32,8 +32,12 @@ pub(crate) fn format_string(
let source_range = TextRange::new(brace_offset, cursor); let source_range = TextRange::new(brace_offset, cursor);
ctx.locals.iter().sorted_by_key(|&(k, _)| k.clone()).for_each(|(name, _)| { ctx.locals.iter().sorted_by_key(|&(k, _)| k.clone()).for_each(|(name, _)| {
CompletionItem::new(CompletionItemKind::Binding, source_range, name.to_smol_str()) CompletionItem::new(
.add_to(acc, ctx.db); CompletionItemKind::Binding,
source_range,
name.display_no_db().to_smolstr(),
)
.add_to(acc, ctx.db);
}); });
ctx.scope.process_all_names(&mut |name, scope| { ctx.scope.process_all_names(&mut |name, scope| {
if let ScopeDef::ModuleDef(module_def) = scope { if let ScopeDef::ModuleDef(module_def) = scope {
@ -46,7 +50,7 @@ pub(crate) fn format_string(
CompletionItem::new( CompletionItem::new(
CompletionItemKind::SymbolKind(symbol_kind), CompletionItemKind::SymbolKind(symbol_kind),
source_range, source_range,
name.to_smol_str(), name.display_no_db().to_smolstr(),
) )
.add_to(acc, ctx.db); .add_to(acc, ctx.db);
} }

View file

@ -38,7 +38,7 @@ use ide_db::{
}; };
use syntax::{ use syntax::{
ast::{self, edit_in_place::AttrsOwnerEdit, HasTypeBounds}, ast::{self, edit_in_place::AttrsOwnerEdit, HasTypeBounds},
format_smolstr, AstNode, SmolStr, SyntaxElement, SyntaxKind, TextRange, T, format_smolstr, AstNode, SmolStr, SyntaxElement, SyntaxKind, TextRange, ToSmolStr, T,
}; };
use text_edit::TextEdit; use text_edit::TextEdit;
@ -252,7 +252,7 @@ fn add_type_alias_impl(
type_alias: hir::TypeAlias, type_alias: hir::TypeAlias,
impl_def: hir::Impl, impl_def: hir::Impl,
) { ) {
let alias_name = type_alias.name(ctx.db).unescaped().to_smol_str(); let alias_name = type_alias.name(ctx.db).unescaped().display(ctx.db).to_smolstr();
let label = format_smolstr!("type {alias_name} ="); let label = format_smolstr!("type {alias_name} =");
@ -314,7 +314,7 @@ fn add_const_impl(
const_: hir::Const, const_: hir::Const,
impl_def: hir::Impl, impl_def: hir::Impl,
) { ) {
let const_name = const_.name(ctx.db).map(|n| n.to_smol_str()); let const_name = const_.name(ctx.db).map(|n| n.display_no_db().to_smolstr());
if let Some(const_name) = const_name { if let Some(const_name) = const_name {
if let Some(source) = ctx.sema.source(const_) { if let Some(source) = ctx.sema.source(const_) {

View file

@ -8,7 +8,7 @@
//! show up for normal completions, or they won't show completions other than lifetimes depending //! show up for normal completions, or they won't show completions other than lifetimes depending
//! on the fixture input. //! on the fixture input.
use hir::{sym, Name, ScopeDef}; use hir::{sym, Name, ScopeDef};
use syntax::{ast, TokenText}; use syntax::{ast, ToSmolStr, TokenText};
use crate::{ use crate::{
completions::Completions, completions::Completions,
@ -41,7 +41,7 @@ pub(crate) fn complete_lifetime(
if matches!( if matches!(
res, res,
ScopeDef::GenericParam(hir::GenericParam::LifetimeParam(_)) ScopeDef::GenericParam(hir::GenericParam::LifetimeParam(_))
if param_lifetime != Some(&*name.to_smol_str()) if param_lifetime != Some(&*name.display_no_db().to_smolstr())
) { ) {
acc.add_lifetime(ctx, name); acc.add_lifetime(ctx, name);
} }

View file

@ -7,7 +7,7 @@ use ide_db::{
base_db::{SourceDatabaseExt, VfsPath}, base_db::{SourceDatabaseExt, VfsPath},
FxHashSet, RootDatabase, SymbolKind, FxHashSet, RootDatabase, SymbolKind,
}; };
use syntax::{ast, AstNode, SyntaxKind}; use syntax::{ast, AstNode, SyntaxKind, ToSmolStr};
use crate::{context::CompletionContext, CompletionItem, Completions}; use crate::{context::CompletionContext, CompletionItem, Completions};
@ -139,7 +139,7 @@ fn directory_to_look_for_submodules(
module_chain_to_containing_module_file(module, db) module_chain_to_containing_module_file(module, db)
.into_iter() .into_iter()
.filter_map(|module| module.name(db)) .filter_map(|module| module.name(db))
.try_fold(base_directory, |path, name| path.join(&name.to_smol_str())) .try_fold(base_directory, |path, name| path.join(&name.display_no_db().to_smolstr()))
} }
fn module_chain_to_containing_module_file( fn module_chain_to_containing_module_file(

View file

@ -48,7 +48,7 @@ pub(crate) fn complete_use_path(
let unknown_is_current = |name: &hir::Name| { let unknown_is_current = |name: &hir::Name| {
matches!( matches!(
name_ref, name_ref,
Some(name_ref) if name_ref.syntax().text() == name.to_smol_str().as_str() Some(name_ref) if name_ref.syntax().text() == name.as_str()
) )
}; };
for (name, def) in module_scope { for (name, def) in module_scope {

View file

@ -17,7 +17,7 @@ use ide_db::{
imports::import_assets::LocatedImport, imports::import_assets::LocatedImport,
RootDatabase, SnippetCap, SymbolKind, RootDatabase, SnippetCap, SymbolKind,
}; };
use syntax::{ast, format_smolstr, AstNode, SmolStr, SyntaxKind, TextRange}; use syntax::{ast, format_smolstr, AstNode, SmolStr, SyntaxKind, TextRange, ToSmolStr};
use text_edit::TextEdit; use text_edit::TextEdit;
use crate::{ use crate::{
@ -133,7 +133,8 @@ pub(crate) fn render_field(
let db = ctx.db(); let db = ctx.db();
let is_deprecated = ctx.is_deprecated(field); let is_deprecated = ctx.is_deprecated(field);
let name = field.name(db); let name = field.name(db);
let (name, escaped_name) = (name.unescaped().to_smol_str(), name.to_smol_str()); let (name, escaped_name) =
(name.unescaped().display(db).to_smolstr(), name.display_no_db().to_smolstr());
let mut item = CompletionItem::new( let mut item = CompletionItem::new(
SymbolKind::Field, SymbolKind::Field,
ctx.source_range(), ctx.source_range(),
@ -399,10 +400,10 @@ fn render_resolution_path(
let config = completion.config; let config = completion.config;
let requires_import = import_to_add.is_some(); let requires_import = import_to_add.is_some();
let name = local_name.to_smol_str(); let name = local_name.display_no_db().to_smolstr();
let mut item = render_resolution_simple_(ctx, &local_name, import_to_add, resolution); let mut item = render_resolution_simple_(ctx, &local_name, import_to_add, resolution);
if local_name.is_escaped() { if local_name.is_escaped() {
item.insert_text(local_name.to_smol_str()); item.insert_text(local_name.display_no_db().to_smolstr());
} }
// Add `<>` for generic types // Add `<>` for generic types
let type_path_no_ty_args = matches!( let type_path_no_ty_args = matches!(
@ -484,8 +485,11 @@ fn render_resolution_simple_(
let ctx = ctx.import_to_add(import_to_add); let ctx = ctx.import_to_add(import_to_add);
let kind = res_to_kind(resolution); let kind = res_to_kind(resolution);
let mut item = let mut item = CompletionItem::new(
CompletionItem::new(kind, ctx.source_range(), local_name.unescaped().to_smol_str()); kind,
ctx.source_range(),
local_name.unescaped().display(db).to_smolstr(),
);
item.set_relevance(ctx.completion_relevance()) item.set_relevance(ctx.completion_relevance())
.set_documentation(scope_def_docs(db, resolution)) .set_documentation(scope_def_docs(db, resolution))
.set_deprecated(scope_def_is_deprecated(&ctx, resolution)); .set_deprecated(scope_def_is_deprecated(&ctx, resolution));

View file

@ -2,6 +2,7 @@
use hir::{AsAssocItem, HirDisplay}; use hir::{AsAssocItem, HirDisplay};
use ide_db::SymbolKind; use ide_db::SymbolKind;
use syntax::ToSmolStr;
use crate::{item::CompletionItem, render::RenderContext}; use crate::{item::CompletionItem, render::RenderContext};
@ -13,7 +14,8 @@ pub(crate) fn render_const(ctx: RenderContext<'_>, const_: hir::Const) -> Option
fn render(ctx: RenderContext<'_>, const_: hir::Const) -> Option<CompletionItem> { fn render(ctx: RenderContext<'_>, const_: hir::Const) -> Option<CompletionItem> {
let db = ctx.db(); let db = ctx.db();
let name = const_.name(db)?; let name = const_.name(db)?;
let (name, escaped_name) = (name.unescaped().to_smol_str(), name.to_smol_str()); let (name, escaped_name) =
(name.unescaped().display(db).to_smolstr(), name.display(db).to_smolstr());
let detail = const_.display(db).to_string(); let detail = const_.display(db).to_string();
let mut item = CompletionItem::new(SymbolKind::Const, ctx.source_range(), name); let mut item = CompletionItem::new(SymbolKind::Const, ctx.source_range(), name);
@ -24,7 +26,7 @@ fn render(ctx: RenderContext<'_>, const_: hir::Const) -> Option<CompletionItem>
if let Some(actm) = const_.as_assoc_item(db) { if let Some(actm) = const_.as_assoc_item(db) {
if let Some(trt) = actm.container_or_implemented_trait(db) { if let Some(trt) = actm.container_or_implemented_trait(db) {
item.trait_name(trt.name(db).to_smol_str()); item.trait_name(trt.name(db).display_no_db().to_smolstr());
} }
} }
item.insert_text(escaped_name); item.insert_text(escaped_name);

View file

@ -4,7 +4,7 @@ use hir::{db::HirDatabase, AsAssocItem, HirDisplay};
use ide_db::{SnippetCap, SymbolKind}; use ide_db::{SnippetCap, SymbolKind};
use itertools::Itertools; use itertools::Itertools;
use stdx::{format_to, to_lower_snake_case}; use stdx::{format_to, to_lower_snake_case};
use syntax::{format_smolstr, AstNode, SmolStr}; use syntax::{format_smolstr, AstNode, SmolStr, ToSmolStr};
use crate::{ use crate::{
context::{CompletionContext, DotAccess, DotAccessKind, PathCompletionCtx, PathKind}, context::{CompletionContext, DotAccess, DotAccessKind, PathCompletionCtx, PathKind},
@ -64,7 +64,7 @@ fn render(
), ),
format_smolstr!("{}.{}", receiver.display(ctx.db()), name.display(ctx.db())), format_smolstr!("{}.{}", receiver.display(ctx.db()), name.display(ctx.db())),
), ),
_ => (name.unescaped().to_smol_str(), name.to_smol_str()), _ => (name.unescaped().display(db).to_smolstr(), name.display(db).to_smolstr()),
}; };
let has_self_param = func.self_param(db).is_some(); let has_self_param = func.self_param(db).is_some();
let mut item = CompletionItem::new( let mut item = CompletionItem::new(
@ -148,7 +148,7 @@ fn render(
item.set_documentation(ctx.docs(func)) item.set_documentation(ctx.docs(func))
.set_deprecated(ctx.is_deprecated(func) || ctx.is_deprecated_assoc_item(func)) .set_deprecated(ctx.is_deprecated(func) || ctx.is_deprecated_assoc_item(func))
.detail(detail) .detail(detail)
.lookup_by(name.unescaped().to_smol_str()); .lookup_by(name.unescaped().display(db).to_smolstr());
if let Some((cap, (self_param, params))) = complete_call_parens { if let Some((cap, (self_param, params))) = complete_call_parens {
add_call_parens(&mut item, completion, cap, call, escaped_call, self_param, params); add_call_parens(&mut item, completion, cap, call, escaped_call, self_param, params);
@ -161,7 +161,7 @@ fn render(
None => { None => {
if let Some(actm) = assoc_item { if let Some(actm) = assoc_item {
if let Some(trt) = actm.container_or_implemented_trait(db) { if let Some(trt) = actm.container_or_implemented_trait(db) {
item.trait_name(trt.name(db).to_smol_str()); item.trait_name(trt.name(db).display_no_db().to_smolstr());
} }
} }
} }
@ -219,7 +219,7 @@ pub(super) fn add_call_parens<'b>(
params.iter().enumerate().format_with(", ", |(index, param), f| { params.iter().enumerate().format_with(", ", |(index, param), f| {
match param.name(ctx.db) { match param.name(ctx.db) {
Some(n) => { Some(n) => {
let smol_str = n.to_smol_str(); let smol_str = n.display_no_db().to_smolstr();
let text = smol_str.as_str().trim_start_matches('_'); let text = smol_str.as_str().trim_start_matches('_');
let ref_ = ref_of_param(ctx, text, param.ty()); let ref_ = ref_of_param(ctx, text, param.ty());
f(&format_args!("${{{}:{ref_}{text}}}", index + offset)) f(&format_args!("${{{}:{ref_}{text}}}", index + offset))

View file

@ -2,7 +2,7 @@
use hir::HirDisplay; use hir::HirDisplay;
use ide_db::{documentation::Documentation, SymbolKind}; use ide_db::{documentation::Documentation, SymbolKind};
use syntax::{format_smolstr, SmolStr}; use syntax::{format_smolstr, SmolStr, ToSmolStr};
use crate::{ use crate::{
context::{PathCompletionCtx, PathKind, PatternContext}, context::{PathCompletionCtx, PathKind, PatternContext},
@ -46,7 +46,8 @@ fn render(
ctx.source_range() ctx.source_range()
}; };
let (name, escaped_name) = (name.unescaped().to_smol_str(), name.to_smol_str()); let (name, escaped_name) =
(name.unescaped().display(ctx.db()).to_smolstr(), name.display(ctx.db()).to_smolstr());
let docs = ctx.docs(macro_); let docs = ctx.docs(macro_);
let docs_str = docs.as_ref().map(Documentation::as_str).unwrap_or_default(); let docs_str = docs.as_ref().map(Documentation::as_str).unwrap_or_default();
let is_fn_like = macro_.is_fn_like(completion.db); let is_fn_like = macro_.is_fn_like(completion.db);

View file

@ -3,7 +3,7 @@
use hir::{db::HirDatabase, Name, StructKind}; use hir::{db::HirDatabase, Name, StructKind};
use ide_db::{documentation::HasDocs, SnippetCap}; use ide_db::{documentation::HasDocs, SnippetCap};
use itertools::Itertools; use itertools::Itertools;
use syntax::SmolStr; use syntax::{SmolStr, ToSmolStr};
use crate::{ use crate::{
context::{ParamContext, ParamKind, PathCompletionCtx, PatternContext}, context::{ParamContext, ParamKind, PathCompletionCtx, PatternContext},
@ -31,7 +31,8 @@ pub(crate) fn render_struct_pat(
} }
let name = local_name.unwrap_or_else(|| strukt.name(ctx.db())); let name = local_name.unwrap_or_else(|| strukt.name(ctx.db()));
let (name, escaped_name) = (name.unescaped().to_smol_str(), name.to_smol_str()); let (name, escaped_name) =
(name.unescaped().display(ctx.db()).to_smolstr(), name.display(ctx.db()).to_smolstr());
let kind = strukt.kind(ctx.db()); let kind = strukt.kind(ctx.db());
let label = format_literal_label(name.as_str(), kind, ctx.snippet_cap()); let label = format_literal_label(name.as_str(), kind, ctx.snippet_cap());
let lookup = format_literal_lookup(name.as_str(), kind); let lookup = format_literal_lookup(name.as_str(), kind);
@ -63,7 +64,11 @@ pub(crate) fn render_variant_pat(
), ),
None => { None => {
let name = local_name.unwrap_or_else(|| variant.name(ctx.db())); let name = local_name.unwrap_or_else(|| variant.name(ctx.db()));
(name.unescaped().to_smol_str(), name.to_smol_str()) let it = (
name.unescaped().display(ctx.db()).to_smolstr(),
name.display(ctx.db()).to_smolstr(),
);
it
} }
}; };
@ -184,7 +189,7 @@ fn render_record_as_pat(
None => { None => {
format!( format!(
"{name} {{ {}{} }}", "{name} {{ {}{} }}",
fields.map(|field| field.name(db).to_smol_str()).format(", "), fields.map(|field| field.name(db).display_no_db().to_smolstr()).format(", "),
if fields_omitted { ", .." } else { "" }, if fields_omitted { ", .." } else { "" },
name = name name = name
) )

View file

@ -2,7 +2,7 @@
use hir::{AsAssocItem, HirDisplay}; use hir::{AsAssocItem, HirDisplay};
use ide_db::SymbolKind; use ide_db::SymbolKind;
use syntax::SmolStr; use syntax::{SmolStr, ToSmolStr};
use crate::{item::CompletionItem, render::RenderContext}; use crate::{item::CompletionItem, render::RenderContext};
@ -32,11 +32,11 @@ fn render(
let name = type_alias.name(db); let name = type_alias.name(db);
let (name, escaped_name) = if with_eq { let (name, escaped_name) = if with_eq {
( (
SmolStr::from_iter([&name.unescaped().to_smol_str(), " = "]), SmolStr::from_iter([&name.unescaped().display(db).to_smolstr(), " = "]),
SmolStr::from_iter([&name.to_smol_str(), " = "]), SmolStr::from_iter([&name.display_no_db().to_smolstr(), " = "]),
) )
} else { } else {
(name.unescaped().to_smol_str(), name.to_smol_str()) (name.unescaped().display(db).to_smolstr(), name.display_no_db().to_smolstr())
}; };
let detail = type_alias.display(db).to_string(); let detail = type_alias.display(db).to_string();
@ -48,7 +48,7 @@ fn render(
if let Some(actm) = type_alias.as_assoc_item(db) { if let Some(actm) = type_alias.as_assoc_item(db) {
if let Some(trt) = actm.container_or_implemented_trait(db) { if let Some(trt) = actm.container_or_implemented_trait(db) {
item.trait_name(trt.name(db).to_smol_str()); item.trait_name(trt.name(db).display_no_db().to_smolstr());
} }
} }
item.insert_text(escaped_name); item.insert_text(escaped_name);

View file

@ -3,6 +3,7 @@
use hir::{HirDisplay, Name, StructKind}; use hir::{HirDisplay, Name, StructKind};
use ide_db::SymbolKind; use ide_db::SymbolKind;
use itertools::Itertools; use itertools::Itertools;
use syntax::ToSmolStr;
use crate::{ use crate::{
render::{ render::{
@ -26,8 +27,12 @@ pub(crate) fn render_union_literal(
(name.unescaped().display(ctx.db()).to_string(), name.display(ctx.db()).to_string()) (name.unescaped().display(ctx.db()).to_string(), name.display(ctx.db()).to_string())
} }
}; };
let label = format_literal_label(&name.to_smol_str(), StructKind::Record, ctx.snippet_cap()); let label = format_literal_label(
let lookup = format_literal_lookup(&name.to_smol_str(), StructKind::Record); &name.display_no_db().to_smolstr(),
StructKind::Record,
ctx.snippet_cap(),
);
let lookup = format_literal_lookup(&name.display_no_db().to_smolstr(), StructKind::Record);
let mut item = CompletionItem::new( let mut item = CompletionItem::new(
CompletionItemKind::SymbolKind(SymbolKind::Union), CompletionItemKind::SymbolKind(SymbolKind::Union),
ctx.source_range(), ctx.source_range(),
@ -47,7 +52,10 @@ pub(crate) fn render_union_literal(
format!( format!(
"{} {{ ${{1|{}|}}: ${{2:()}} }}$0", "{} {{ ${{1|{}|}}: ${{2:()}} }}$0",
escaped_qualified_name, escaped_qualified_name,
fields.iter().map(|field| field.name(ctx.db()).to_smol_str()).format(",") fields
.iter()
.map(|field| field.name(ctx.db()).display_no_db().to_smolstr())
.format(",")
) )
} else { } else {
format!( format!(

View file

@ -17,7 +17,7 @@ use hir::{
use stdx::{format_to, impl_from}; use stdx::{format_to, impl_from};
use syntax::{ use syntax::{
ast::{self, AstNode}, ast::{self, AstNode},
match_ast, SyntaxKind, SyntaxNode, SyntaxToken, match_ast, SyntaxKind, SyntaxNode, SyntaxToken, ToSmolStr,
}; };
use crate::documentation::{Documentation, HasDocs}; use crate::documentation::{Documentation, HasDocs};
@ -670,7 +670,7 @@ impl NameRefClass {
hir::AssocItem::TypeAlias(it) => Some(it), hir::AssocItem::TypeAlias(it) => Some(it),
_ => None, _ => None,
}) })
.find(|alias| alias.name(sema.db).to_smol_str() == name_ref.text().as_str()) .find(|alias| alias.name(sema.db).display_no_db().to_smolstr() == name_ref.text().as_str())
{ {
return Some(NameRefClass::Definition(Definition::TypeAlias(ty))); return Some(NameRefClass::Definition(Definition::TypeAlias(ty)));
} }

View file

@ -2,6 +2,7 @@
use base_db::{CrateOrigin, LangCrateOrigin, SourceDatabase}; use base_db::{CrateOrigin, LangCrateOrigin, SourceDatabase};
use hir::{Crate, Enum, Function, Macro, Module, ScopeDef, Semantics, Trait}; use hir::{Crate, Enum, Function, Macro, Module, ScopeDef, Semantics, Trait};
use syntax::ToSmolStr;
use crate::RootDatabase; use crate::RootDatabase;
@ -198,15 +199,18 @@ impl FamousDefs<'_, '_> {
for segment in path { for segment in path {
module = module.children(db).find_map(|child| { module = module.children(db).find_map(|child| {
let name = child.name(db)?; let name = child.name(db)?;
if name.to_smol_str() == segment { if name.display_no_db().to_smolstr() == segment {
Some(child) Some(child)
} else { } else {
None None
} }
})?; })?;
} }
let def = let def = module
module.scope(db, None).into_iter().find(|(name, _def)| name.to_smol_str() == trait_)?.1; .scope(db, None)
.into_iter()
.find(|(name, _def)| name.display_no_db().to_smolstr() == trait_)?
.1;
Some(def) Some(def)
} }
} }

View file

@ -6,7 +6,7 @@ use base_db::{FileId, SourceDatabaseExt};
use hir::{Crate, DescendPreference, ItemInNs, ModuleDef, Name, Semantics}; use hir::{Crate, DescendPreference, ItemInNs, ModuleDef, Name, Semantics};
use syntax::{ use syntax::{
ast::{self, make}, ast::{self, make},
AstToken, SyntaxKind, SyntaxToken, TokenAtOffset, AstToken, SyntaxKind, SyntaxToken, ToSmolStr, TokenAtOffset,
}; };
use crate::{ use crate::{
@ -50,9 +50,9 @@ pub fn mod_path_to_ast(path: &hir::ModPath) -> ast::Path {
} }
segments.extend( segments.extend(
path.segments() path.segments().iter().map(|segment| {
.iter() make::path_segment(make::name_ref(&segment.display_no_db().to_smolstr()))
.map(|segment| make::path_segment(make::name_ref(&segment.to_smol_str()))), }),
); );
make::path_from_segments(segments, is_abs) make::path_from_segments(segments, is_abs)
} }

View file

@ -9,7 +9,7 @@ use itertools::{EitherOrBoth, Itertools};
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use syntax::{ use syntax::{
ast::{self, make, HasName}, ast::{self, make, HasName},
AstNode, SmolStr, SyntaxNode, AstNode, SmolStr, SyntaxNode, ToSmolStr,
}; };
use crate::{ use crate::{
@ -459,7 +459,7 @@ fn find_import_for_segment(
unresolved_first_segment: &str, unresolved_first_segment: &str,
) -> Option<ItemInNs> { ) -> Option<ItemInNs> {
let segment_is_name = item_name(db, original_item) let segment_is_name = item_name(db, original_item)
.map(|name| name.to_smol_str() == unresolved_first_segment) .map(|name| name.display_no_db().to_smolstr() == unresolved_first_segment)
.unwrap_or(false); .unwrap_or(false);
Some(if segment_is_name { Some(if segment_is_name {
@ -483,7 +483,7 @@ fn module_with_segment_name(
}; };
while let Some(module) = current_module { while let Some(module) = current_module {
if let Some(module_name) = module.name(db) { if let Some(module_name) = module.name(db) {
if module_name.to_smol_str() == segment_name { if module_name.display_no_db().to_smolstr() == segment_name {
return Some(module); return Some(module);
} }
} }

View file

@ -15,7 +15,7 @@ use memchr::memmem::Finder;
use nohash_hasher::IntMap; use nohash_hasher::IntMap;
use once_cell::unsync::Lazy; use once_cell::unsync::Lazy;
use parser::SyntaxKind; use parser::SyntaxKind;
use syntax::{ast, match_ast, AstNode, AstToken, SyntaxElement, TextRange, TextSize}; use syntax::{ast, match_ast, AstNode, AstToken, SyntaxElement, TextRange, TextSize, ToSmolStr};
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
@ -468,7 +468,10 @@ impl<'a> FindUsages<'a> {
}; };
// We need to unescape the name in case it is written without "r#" in earlier // We need to unescape the name in case it is written without "r#" in earlier
// editions of Rust where it isn't a keyword. // editions of Rust where it isn't a keyword.
self.def.name(sema.db).or_else(self_kw_refs).map(|it| it.unescaped().to_smol_str()) self.def
.name(sema.db)
.or_else(self_kw_refs)
.map(|it| it.unescaped().display(sema.db).to_smolstr())
} }
}; };
let name = match &name { let name = match &name {

View file

@ -5,7 +5,10 @@
use std::iter; use std::iter;
use hir::Semantics; use hir::Semantics;
use syntax::ast::{self, make, Pat}; use syntax::{
ast::{self, make, Pat},
ToSmolStr,
};
use crate::RootDatabase; use crate::RootDatabase;
@ -26,7 +29,7 @@ impl TryEnum {
_ => return None, _ => return None,
}; };
TryEnum::ALL.iter().find_map(|&var| { TryEnum::ALL.iter().find_map(|&var| {
if enum_.name(sema.db).to_smol_str() == var.type_name() { if enum_.name(sema.db).display_no_db().to_smolstr() == var.type_name() {
return Some(var); return Some(var);
} }
None None

View file

@ -1,7 +1,10 @@
//! Functionality for generating trivial constructors //! Functionality for generating trivial constructors
use hir::StructKind; use hir::StructKind;
use syntax::ast::{make, Expr, Path}; use syntax::{
ast::{make, Expr, Path},
ToSmolStr,
};
/// given a type return the trivial constructor (if one exists) /// given a type return the trivial constructor (if one exists)
pub fn use_trivial_constructor( pub fn use_trivial_constructor(
@ -15,7 +18,9 @@ pub fn use_trivial_constructor(
if variant.kind(db) == hir::StructKind::Unit { if variant.kind(db) == hir::StructKind::Unit {
let path = make::path_qualified( let path = make::path_qualified(
path, path,
make::path_segment(make::name_ref(&variant.name(db).to_smol_str())), make::path_segment(make::name_ref(
&variant.name(db).display_no_db().to_smolstr(),
)),
); );
return Some(make::expr_path(path)); return Some(make::expr_path(path));

View file

@ -11,7 +11,7 @@ use stdx::format_to;
use syntax::{ use syntax::{
algo, algo,
ast::{self, make}, ast::{self, make},
AstNode, SyntaxNode, SyntaxNodePtr, AstNode, SyntaxNode, SyntaxNodePtr, ToSmolStr,
}; };
use text_edit::TextEdit; use text_edit::TextEdit;
@ -146,7 +146,7 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Option<Vec<Ass
} }
}; };
let field = make::record_expr_field( let field = make::record_expr_field(
make::name_ref(&f.name(ctx.sema.db).to_smol_str()), make::name_ref(&f.name(ctx.sema.db).display_no_db().to_smolstr()),
field_expr, field_expr,
); );
new_field_list.add_field(field.clone_for_update()); new_field_list.add_field(field.clone_for_update());
@ -160,7 +160,7 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::MissingFields) -> Option<Vec<Ass
let new_field_list = old_field_list.clone_for_update(); let new_field_list = old_field_list.clone_for_update();
for (f, _) in missing_fields.iter() { for (f, _) in missing_fields.iter() {
let field = make::record_pat_field_shorthand(make::name_ref( let field = make::record_pat_field_shorthand(make::name_ref(
&f.name(ctx.sema.db).to_smol_str(), &f.name(ctx.sema.db).display_no_db().to_smolstr(),
)); ));
new_field_list.add_field(field.clone_for_update()); new_field_list.add_field(field.clone_for_update());
} }

View file

@ -4,6 +4,7 @@ use ide_db::{
label::Label, label::Label,
source_change::SourceChangeBuilder, source_change::SourceChangeBuilder,
}; };
use syntax::ToSmolStr;
use text_edit::TextRange; use text_edit::TextRange;
use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext}; use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext};
@ -21,7 +22,7 @@ pub(crate) fn trait_impl_redundant_assoc_item(
let assoc_item = d.assoc_item.1; let assoc_item = d.assoc_item.1;
let default_range = d.impl_.syntax_node_ptr().text_range(); let default_range = d.impl_.syntax_node_ptr().text_range();
let trait_name = d.trait_.name(db).to_smol_str(); let trait_name = d.trait_.name(db).display_no_db().to_smolstr();
let (redundant_item_name, diagnostic_range, redundant_item_def) = match assoc_item { let (redundant_item_name, diagnostic_range, redundant_item_def) = match assoc_item {
hir::AssocItem::Function(id) => { hir::AssocItem::Function(id) => {
@ -45,7 +46,10 @@ pub(crate) fn trait_impl_redundant_assoc_item(
( (
format!("`type {redundant_assoc_item_name}`"), format!("`type {redundant_assoc_item_name}`"),
type_alias.source(db).map(|it| it.syntax().text_range()).unwrap_or(default_range), type_alias.source(db).map(|it| it.syntax().text_range()).unwrap_or(default_range),
format!("\n type {};", type_alias.name(ctx.sema.db).to_smol_str()), format!(
"\n type {};",
type_alias.name(ctx.sema.db).display_no_db().to_smolstr()
),
) )
} }
}; };

View file

@ -11,7 +11,7 @@ use ide_db::{
use paths::Utf8Component; use paths::Utf8Component;
use syntax::{ use syntax::{
ast::{self, edit::IndentLevel, HasModuleItem, HasName}, ast::{self, edit::IndentLevel, HasModuleItem, HasName},
AstNode, TextRange, AstNode, TextRange, ToSmolStr,
}; };
use text_edit::TextEdit; use text_edit::TextEdit;
@ -106,7 +106,8 @@ fn fixes(ctx: &DiagnosticsContext<'_>, file_id: FileId) -> Option<Vec<Assist>> {
// shouldn't occur // shouldn't occur
_ => continue 'crates, _ => continue 'crates,
}; };
match current.children.iter().find(|(name, _)| name.to_smol_str() == seg) { match current.children.iter().find(|(name, _)| name.display_no_db().to_smolstr() == seg)
{
Some((_, &child)) => current = &crate_def_map[child], Some((_, &child)) => current = &crate_def_map[child],
None => continue 'crates, None => continue 'crates,
} }
@ -156,7 +157,11 @@ fn fixes(ctx: &DiagnosticsContext<'_>, file_id: FileId) -> Option<Vec<Assist>> {
// try finding a parent that has an inline tree from here on // try finding a parent that has an inline tree from here on
let mut current = module; let mut current = module;
for s in stack.iter().rev() { for s in stack.iter().rev() {
match module.children.iter().find(|(name, _)| name.to_smol_str() == s) { match module
.children
.iter()
.find(|(name, _)| name.display_no_db().to_smolstr() == s)
{
Some((_, child)) => { Some((_, child)) => {
current = &crate_def_map[*child]; current = &crate_def_map[*child];
} }

View file

@ -7,7 +7,7 @@ use ide_db::{
}; };
use syntax::{ use syntax::{
ast::{self, make, HasArgList}, ast::{self, make, HasArgList},
AstNode, SmolStr, TextRange, format_smolstr, AstNode, SmolStr, TextRange, ToSmolStr,
}; };
use text_edit::TextEdit; use text_edit::TextEdit;
@ -154,14 +154,16 @@ fn assoc_func_fix(ctx: &DiagnosticsContext<'_>, d: &hir::UnresolvedMethodCall) -
_ => false, _ => false,
}; };
let mut receiver_type_adt_name = receiver_type.as_adt()?.name(db).to_smol_str().to_string(); let mut receiver_type_adt_name =
receiver_type.as_adt()?.name(db).display_no_db().to_smolstr();
let generic_parameters: Vec<SmolStr> = receiver_type.generic_parameters(db).collect(); let generic_parameters: Vec<SmolStr> = receiver_type.generic_parameters(db).collect();
// if receiver should be pass as first arg in the assoc func, // if receiver should be pass as first arg in the assoc func,
// we could omit generic parameters cause compiler can deduce it automatically // we could omit generic parameters cause compiler can deduce it automatically
if !need_to_take_receiver_as_first_arg && !generic_parameters.is_empty() { if !need_to_take_receiver_as_first_arg && !generic_parameters.is_empty() {
let generic_parameters = generic_parameters.join(", "); let generic_parameters = generic_parameters.join(", ");
receiver_type_adt_name = format!("{receiver_type_adt_name}::<{generic_parameters}>"); receiver_type_adt_name =
format_smolstr!("{receiver_type_adt_name}::<{generic_parameters}>");
} }
let method_name = call.name_ref()?; let method_name = call.name_ref()?;

View file

@ -238,7 +238,7 @@ impl<'db> ResolutionScope<'db> {
None, None,
|assoc_item| { |assoc_item| {
let item_name = assoc_item.name(self.scope.db)?; let item_name = assoc_item.name(self.scope.db)?;
if item_name.to_smol_str().as_str() == name.text() { if item_name.as_str() == name.text() {
Some(hir::PathResolution::Def(assoc_item.into())) Some(hir::PathResolution::Def(assoc_item.into()))
} else { } else {
None None

View file

@ -14,7 +14,7 @@ use ide_db::{base_db::FileRange, RootDatabase};
use syntax::{ use syntax::{
ast::{self, AstNode}, ast::{self, AstNode},
match_ast, match_ast, ToSmolStr,
}; };
use crate::{InlayHint, InlayHintLabel, InlayHintPosition, InlayHintsConfig, InlayKind}; use crate::{InlayHint, InlayHintLabel, InlayHintPosition, InlayHintsConfig, InlayKind};
@ -88,7 +88,7 @@ pub(super) fn hints(
.and_then(|d| { .and_then(|d| {
Some(FileRange { file_id: d.file_id.file_id()?, range: d.value.text_range() }) Some(FileRange { file_id: d.file_id.file_id()?, range: d.value.text_range() })
}); });
let name = binding.name.to_smol_str(); let name = binding.name.display_no_db().to_smolstr();
if name.starts_with("<ra@") { if name.starts_with("<ra@") {
continue; // Ignore desugared variables continue; // Ignore desugared variables
} }

View file

@ -10,7 +10,10 @@ use hir::{Callable, Semantics};
use ide_db::{base_db::FileRange, RootDatabase}; use ide_db::{base_db::FileRange, RootDatabase};
use stdx::to_lower_snake_case; use stdx::to_lower_snake_case;
use syntax::ast::{self, AstNode, HasArgList, HasName, UnaryOp}; use syntax::{
ast::{self, AstNode, HasArgList, HasName, UnaryOp},
ToSmolStr,
};
use crate::{InlayHint, InlayHintLabel, InlayHintPosition, InlayHintsConfig, InlayKind}; use crate::{InlayHint, InlayHintLabel, InlayHintPosition, InlayHintsConfig, InlayKind};
@ -118,7 +121,7 @@ fn should_hide_param_name_hint(
} }
let fn_name = match callable.kind() { let fn_name = match callable.kind() {
hir::CallableKind::Function(it) => Some(it.name(sema.db).to_smol_str()), hir::CallableKind::Function(it) => Some(it.name(sema.db).display_no_db().to_smolstr()),
_ => None, _ => None,
}; };
let fn_name = fn_name.as_deref(); let fn_name = fn_name.as_deref();

View file

@ -17,7 +17,7 @@ use ide_db::{
use stdx::never; use stdx::never;
use syntax::{ use syntax::{
ast::{self, HasName}, ast::{self, HasName},
format_smolstr, AstNode, SmolStr, SyntaxNode, TextRange, format_smolstr, AstNode, SmolStr, SyntaxNode, TextRange, ToSmolStr,
}; };
/// `NavigationTarget` represents an element in the editor's UI which you can /// `NavigationTarget` represents an element in the editor's UI which you can
@ -98,7 +98,7 @@ impl NavigationTarget {
db: &RootDatabase, db: &RootDatabase,
module: hir::Module, module: hir::Module,
) -> UpmappingResult<NavigationTarget> { ) -> UpmappingResult<NavigationTarget> {
let name = module.name(db).map(|it| it.to_smol_str()).unwrap_or_default(); let name = module.name(db).map(|it| it.display_no_db().to_smolstr()).unwrap_or_default();
match module.declaration_source(db) { match module.declaration_source(db) {
Some(InFile { value, file_id }) => { Some(InFile { value, file_id }) => {
orig_range_with_focus(db, file_id, value.syntax(), value.name()).map( orig_range_with_focus(db, file_id, value.syntax(), value.name()).map(
@ -190,7 +190,7 @@ impl TryToNav for FileSymbol {
.is_alias .is_alias
.then(|| self.def.name(db)) .then(|| self.def.name(db))
.flatten() .flatten()
.map_or_else(|| self.name.clone(), |it| it.to_smol_str()), .map_or_else(|| self.name.clone(), |it| it.display_no_db().to_smolstr()),
alias: self.is_alias.then(|| self.name.clone()), alias: self.is_alias.then(|| self.name.clone()),
kind: Some(hir::ModuleDefId::from(self.def).into()), kind: Some(hir::ModuleDefId::from(self.def).into()),
full_range, full_range,
@ -274,9 +274,9 @@ pub(crate) trait ToNavFromAst: Sized {
fn container_name(db: &RootDatabase, t: impl HasContainer) -> Option<SmolStr> { fn container_name(db: &RootDatabase, t: impl HasContainer) -> Option<SmolStr> {
match t.container(db) { match t.container(db) {
hir::ItemContainer::Trait(it) => Some(it.name(db).to_smol_str()), hir::ItemContainer::Trait(it) => Some(it.name(db).display_no_db().to_smolstr()),
// FIXME: Handle owners of blocks correctly here // FIXME: Handle owners of blocks correctly here
hir::ItemContainer::Module(it) => it.name(db).map(|name| name.to_smol_str()), hir::ItemContainer::Module(it) => it.name(db).map(|name| name.display_no_db().to_smolstr()),
_ => None, _ => None,
} }
} }
@ -367,7 +367,7 @@ impl ToNav for hir::Module {
fn to_nav(&self, db: &RootDatabase) -> UpmappingResult<NavigationTarget> { fn to_nav(&self, db: &RootDatabase) -> UpmappingResult<NavigationTarget> {
let InFile { file_id, value } = self.definition_source(db); let InFile { file_id, value } = self.definition_source(db);
let name = self.name(db).map(|it| it.to_smol_str()).unwrap_or_default(); let name = self.name(db).map(|it| it.display_no_db().to_smolstr()).unwrap_or_default();
let (syntax, focus) = match &value { let (syntax, focus) = match &value {
ModuleSource::SourceFile(node) => (node.syntax(), None), ModuleSource::SourceFile(node) => (node.syntax(), None),
ModuleSource::Module(node) => (node.syntax(), node.name()), ModuleSource::Module(node) => (node.syntax(), node.name()),
@ -424,7 +424,10 @@ impl TryToNav for hir::ExternCrateDecl {
|(FileRange { file_id, range: full_range }, focus_range)| { |(FileRange { file_id, range: full_range }, focus_range)| {
let mut res = NavigationTarget::from_syntax( let mut res = NavigationTarget::from_syntax(
file_id, file_id,
self.alias_or_name(db).unwrap_or_else(|| self.name(db)).to_smol_str(), self.alias_or_name(db)
.unwrap_or_else(|| self.name(db))
.display_no_db()
.to_smolstr(),
focus_range, focus_range,
full_range, full_range,
SymbolKind::Module, SymbolKind::Module,
@ -532,7 +535,7 @@ impl ToNav for LocalSource {
orig_range_with_focus(db, file_id, node, name).map( orig_range_with_focus(db, file_id, node, name).map(
|(FileRange { file_id, range: full_range }, focus_range)| { |(FileRange { file_id, range: full_range }, focus_range)| {
let name = local.name(db).to_smol_str(); let name = local.name(db).display_no_db().to_smolstr();
let kind = if local.is_self(db) { let kind = if local.is_self(db) {
SymbolKind::SelfParam SymbolKind::SelfParam
} else if local.is_param(db) { } else if local.is_param(db) {
@ -565,7 +568,7 @@ impl ToNav for hir::Local {
impl TryToNav for hir::Label { impl TryToNav for hir::Label {
fn try_to_nav(&self, db: &RootDatabase) -> Option<UpmappingResult<NavigationTarget>> { fn try_to_nav(&self, db: &RootDatabase) -> Option<UpmappingResult<NavigationTarget>> {
let InFile { file_id, value } = self.source(db)?; let InFile { file_id, value } = self.source(db)?;
let name = self.name(db).to_smol_str(); let name = self.name(db).display_no_db().to_smolstr();
Some(orig_range_with_focus(db, file_id, value.syntax(), value.lifetime()).map( Some(orig_range_with_focus(db, file_id, value.syntax(), value.lifetime()).map(
|(FileRange { file_id, range: full_range }, focus_range)| NavigationTarget { |(FileRange { file_id, range: full_range }, focus_range)| NavigationTarget {
@ -586,7 +589,7 @@ impl TryToNav for hir::Label {
impl TryToNav for hir::TypeParam { impl TryToNav for hir::TypeParam {
fn try_to_nav(&self, db: &RootDatabase) -> Option<UpmappingResult<NavigationTarget>> { fn try_to_nav(&self, db: &RootDatabase) -> Option<UpmappingResult<NavigationTarget>> {
let InFile { file_id, value } = self.merge().source(db)?; let InFile { file_id, value } = self.merge().source(db)?;
let name = self.name(db).to_smol_str(); let name = self.name(db).display_no_db().to_smolstr();
let value = match value { let value = match value {
Either::Left(ast::TypeOrConstParam::Type(x)) => Either::Left(x), Either::Left(ast::TypeOrConstParam::Type(x)) => Either::Left(x),
@ -628,7 +631,7 @@ impl TryToNav for hir::TypeOrConstParam {
impl TryToNav for hir::LifetimeParam { impl TryToNav for hir::LifetimeParam {
fn try_to_nav(&self, db: &RootDatabase) -> Option<UpmappingResult<NavigationTarget>> { fn try_to_nav(&self, db: &RootDatabase) -> Option<UpmappingResult<NavigationTarget>> {
let InFile { file_id, value } = self.source(db)?; let InFile { file_id, value } = self.source(db)?;
let name = self.name(db).to_smol_str(); let name = self.name(db).display_no_db().to_smolstr();
Some(orig_range(db, file_id, value.syntax()).map( Some(orig_range(db, file_id, value.syntax()).map(
|(FileRange { file_id, range: full_range }, focus_range)| NavigationTarget { |(FileRange { file_id, range: full_range }, focus_range)| NavigationTarget {
@ -649,7 +652,7 @@ impl TryToNav for hir::LifetimeParam {
impl TryToNav for hir::ConstParam { impl TryToNav for hir::ConstParam {
fn try_to_nav(&self, db: &RootDatabase) -> Option<UpmappingResult<NavigationTarget>> { fn try_to_nav(&self, db: &RootDatabase) -> Option<UpmappingResult<NavigationTarget>> {
let InFile { file_id, value } = self.merge().source(db)?; let InFile { file_id, value } = self.merge().source(db)?;
let name = self.name(db).to_smol_str(); let name = self.name(db).display_no_db().to_smolstr();
let value = match value { let value = match value {
Either::Left(ast::TypeOrConstParam::Const(x)) => x, Either::Left(ast::TypeOrConstParam::Const(x)) => x,

View file

@ -16,6 +16,7 @@ use itertools::Itertools;
use stdx::{always, never}; use stdx::{always, never};
use syntax::{ use syntax::{
ast, utils::is_raw_identifier, AstNode, SmolStr, SyntaxKind, SyntaxNode, TextRange, TextSize, ast, utils::is_raw_identifier, AstNode, SmolStr, SyntaxKind, SyntaxNode, TextRange, TextSize,
ToSmolStr,
}; };
use text_edit::TextEdit; use text_edit::TextEdit;
@ -266,7 +267,7 @@ fn find_definitions(
// if the name differs from the definitions name it has to be an alias // if the name differs from the definitions name it has to be an alias
if def if def
.name(sema.db) .name(sema.db)
.map_or(false, |it| it.to_smol_str() != name_ref.text().as_str()) .map_or(false, |it| it.display_no_db().to_smolstr() != name_ref.text().as_str())
{ {
Err(format_err!("Renaming aliases is currently unsupported")) Err(format_err!("Renaming aliases is currently unsupported"))
} else { } else {

View file

@ -19,7 +19,7 @@ use span::TextSize;
use stdx::{always, format_to}; use stdx::{always, format_to};
use syntax::{ use syntax::{
ast::{self, AstNode}, ast::{self, AstNode},
SmolStr, SyntaxNode, SmolStr, SyntaxNode, ToSmolStr,
}; };
use crate::{references, FileId, NavigationTarget, ToNav, TryToNav}; use crate::{references, FileId, NavigationTarget, ToNav, TryToNav};
@ -332,7 +332,7 @@ pub(crate) fn runnable_fn(
}; };
canonical_path canonical_path
.map(TestId::Path) .map(TestId::Path)
.unwrap_or(TestId::Name(def.name(sema.db).to_smol_str())) .unwrap_or(TestId::Name(def.name(sema.db).display_no_db().to_smolstr()))
}; };
if def.is_test(sema.db) { if def.is_test(sema.db) {
@ -481,7 +481,8 @@ fn module_def_doctest(db: &RootDatabase, def: Definition) -> Option<Runnable> {
Some(path) Some(path)
})(); })();
let test_id = path.map_or_else(|| TestId::Name(def_name.to_smol_str()), TestId::Path); let test_id =
path.map_or_else(|| TestId::Name(def_name.display_no_db().to_smolstr()), TestId::Path);
let mut nav = match def { let mut nav = match def {
Definition::Module(def) => NavigationTarget::from_module_to_decl(db, def), Definition::Module(def) => NavigationTarget::from_module_to_decl(db, def),

View file

@ -19,7 +19,7 @@ use syntax::{
algo, algo,
ast::{self, AstChildren, HasArgList}, ast::{self, AstChildren, HasArgList},
match_ast, AstNode, Direction, NodeOrToken, SyntaxElementChildren, SyntaxNode, SyntaxToken, match_ast, AstNode, Direction, NodeOrToken, SyntaxElementChildren, SyntaxNode, SyntaxToken,
TextRange, TextSize, T, TextRange, TextSize, ToSmolStr, T,
}; };
use crate::RootDatabase; use crate::RootDatabase;
@ -379,7 +379,7 @@ fn add_assoc_type_bindings(
for item in tr.items_with_supertraits(db) { for item in tr.items_with_supertraits(db) {
if let AssocItem::TypeAlias(ty) = item { if let AssocItem::TypeAlias(ty) = item {
let name = ty.name(db).to_smol_str(); let name = ty.name(db).display_no_db().to_smolstr();
if !present_bindings.contains(&*name) { if !present_bindings.contains(&*name) {
buf.clear(); buf.clear();
format_to!(buf, "{} = …", name); format_to!(buf, "{} = …", name);

View file

@ -27,6 +27,7 @@ span.workspace = true
tt.workspace = true tt.workspace = true
vfs-notify.workspace = true vfs-notify.workspace = true
vfs.workspace = true vfs.workspace = true
intern.workspace = true
[features] [features]
in-rust-tree = ["hir-expand/in-rust-tree"] in-rust-tree = ["hir-expand/in-rust-tree"]

View file

@ -428,14 +428,19 @@ fn expander_to_proc_macro(
expander: proc_macro_api::ProcMacro, expander: proc_macro_api::ProcMacro,
ignored_macros: &[Box<str>], ignored_macros: &[Box<str>],
) -> ProcMacro { ) -> ProcMacro {
let name = From::from(expander.name()); let name = expander.name();
let kind = match expander.kind() { let kind = match expander.kind() {
proc_macro_api::ProcMacroKind::CustomDerive => ProcMacroKind::CustomDerive, proc_macro_api::ProcMacroKind::CustomDerive => ProcMacroKind::CustomDerive,
proc_macro_api::ProcMacroKind::Bang => ProcMacroKind::Bang, proc_macro_api::ProcMacroKind::Bang => ProcMacroKind::Bang,
proc_macro_api::ProcMacroKind::Attr => ProcMacroKind::Attr, proc_macro_api::ProcMacroKind::Attr => ProcMacroKind::Attr,
}; };
let disabled = ignored_macros.iter().any(|replace| **replace == name); let disabled = ignored_macros.iter().any(|replace| **replace == *name);
ProcMacro { name, kind, expander: sync::Arc::new(Expander(expander)), disabled } ProcMacro {
name: intern::Symbol::intern(name),
kind,
expander: sync::Arc::new(Expander(expander)),
disabled,
}
} }
#[derive(Debug)] #[derive(Debug)]

View file

@ -65,7 +65,7 @@ pub use rowan::{
TokenAtOffset, WalkEvent, TokenAtOffset, WalkEvent,
}; };
pub use rustc_lexer::unescape; pub use rustc_lexer::unescape;
pub use smol_str::{format_smolstr, SmolStr}; pub use smol_str::{format_smolstr, SmolStr, ToSmolStr};
/// `Parse` is the result of the parsing: a syntax tree and a collection of /// `Parse` is the result of the parsing: a syntax tree and a collection of
/// errors. /// errors.

View file

@ -370,7 +370,7 @@ pub fn identity(_attr: TokenStream, item: TokenStream) -> TokenStream {
"# "#
.into(), .into(),
ProcMacro { ProcMacro {
name: "identity".into(), name: Symbol::intern("identity"),
kind: ProcMacroKind::Attr, kind: ProcMacroKind::Attr,
expander: sync::Arc::new(IdentityProcMacroExpander), expander: sync::Arc::new(IdentityProcMacroExpander),
disabled: false, disabled: false,
@ -385,7 +385,7 @@ pub fn derive_identity(item: TokenStream) -> TokenStream {
"# "#
.into(), .into(),
ProcMacro { ProcMacro {
name: "DeriveIdentity".into(), name: Symbol::intern("DeriveIdentity"),
kind: ProcMacroKind::CustomDerive, kind: ProcMacroKind::CustomDerive,
expander: sync::Arc::new(IdentityProcMacroExpander), expander: sync::Arc::new(IdentityProcMacroExpander),
disabled: false, disabled: false,
@ -400,7 +400,7 @@ pub fn input_replace(attr: TokenStream, _item: TokenStream) -> TokenStream {
"# "#
.into(), .into(),
ProcMacro { ProcMacro {
name: "input_replace".into(), name: Symbol::intern("input_replace"),
kind: ProcMacroKind::Attr, kind: ProcMacroKind::Attr,
expander: sync::Arc::new(AttributeInputReplaceProcMacroExpander), expander: sync::Arc::new(AttributeInputReplaceProcMacroExpander),
disabled: false, disabled: false,
@ -415,7 +415,7 @@ pub fn mirror(input: TokenStream) -> TokenStream {
"# "#
.into(), .into(),
ProcMacro { ProcMacro {
name: "mirror".into(), name: Symbol::intern("mirror"),
kind: ProcMacroKind::Bang, kind: ProcMacroKind::Bang,
expander: sync::Arc::new(MirrorProcMacroExpander), expander: sync::Arc::new(MirrorProcMacroExpander),
disabled: false, disabled: false,
@ -430,7 +430,7 @@ pub fn shorten(input: TokenStream) -> TokenStream {
"# "#
.into(), .into(),
ProcMacro { ProcMacro {
name: "shorten".into(), name: Symbol::intern("shorten"),
kind: ProcMacroKind::Bang, kind: ProcMacroKind::Bang,
expander: sync::Arc::new(ShortenProcMacroExpander), expander: sync::Arc::new(ShortenProcMacroExpander),
disabled: false, disabled: false,
@ -448,7 +448,8 @@ fn filter_test_proc_macros(
let mut proc_macros = Vec::new(); let mut proc_macros = Vec::new();
for (c, p) in proc_macro_defs { for (c, p) in proc_macro_defs {
if !proc_macro_names.iter().any(|name| name == &stdx::to_lower_snake_case(&p.name)) { if !proc_macro_names.iter().any(|name| name == &stdx::to_lower_snake_case(p.name.as_str()))
{
continue; continue;
} }
proc_macros.push(p); proc_macros.push(p);