Rollup merge of #65776 - nnethercote:rename-LocalInternedString-and-more, r=estebank

Rename `LocalInternedString` and more

This PR renames `LocalInternedString` as `SymbolStr`, removes an unnecessary `impl` from it, improves comments, and cleans up some `SymbolStr` uses.

r? @estebank
This commit is contained in:
Mazdak Farrokhzad 2019-11-06 07:03:01 +01:00 committed by GitHub
commit a0b4b4dafa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
41 changed files with 103 additions and 114 deletions

View File

@ -525,7 +525,7 @@ impl<'tcx> DepNodeParams<'tcx> for CrateNum {
} }
fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String {
tcx.crate_name(*self).as_str().to_string() tcx.crate_name(*self).to_string()
} }
} }

View File

@ -3382,7 +3382,7 @@ pub fn is_range_literal(sess: &Session, expr: &hir::Expr) -> bool {
// either in std or core, i.e. has either a `::std::ops::Range` or // either in std or core, i.e. has either a `::std::ops::Range` or
// `::core::ops::Range` prefix. // `::core::ops::Range` prefix.
fn is_range_path(path: &Path) -> bool { fn is_range_path(path: &Path) -> bool {
let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.as_str().to_string()).collect(); let segs: Vec<_> = path.segments.iter().map(|seg| seg.ident.to_string()).collect();
let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect(); let segs: Vec<_> = segs.iter().map(|seg| &**seg).collect();
// "{{root}}" is the equivalent of `::` prefix in `Path`. // "{{root}}" is the equivalent of `::` prefix in `Path`.
@ -3423,7 +3423,7 @@ pub fn is_range_literal(sess: &Session, expr: &hir::Expr) -> bool {
ExprKind::Call(ref func, _) => { ExprKind::Call(ref func, _) => {
if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind { if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.kind {
if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind { if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.kind {
let new_call = segment.ident.as_str() == "new"; let new_call = segment.ident.name == sym::new;
return is_range_path(&path) && is_lit(sess, &expr.span) && new_call; return is_range_path(&path) && is_lit(sess, &expr.span) && new_call;
} }
} }

View File

@ -564,7 +564,7 @@ impl<'a> State<'a> {
} }
hir::ItemKind::GlobalAsm(ref ga) => { hir::ItemKind::GlobalAsm(ref ga) => {
self.head(visibility_qualified(&item.vis, "global asm")); self.head(visibility_qualified(&item.vis, "global asm"));
self.s.word(ga.asm.as_str().to_string()); self.s.word(ga.asm.to_string());
self.end() self.end()
} }
hir::ItemKind::TyAlias(ref ty, ref generics) => { hir::ItemKind::TyAlias(ref ty, ref generics) => {
@ -1855,7 +1855,7 @@ impl<'a> State<'a> {
self.commasep(Inconsistent, &decl.inputs, |s, ty| { self.commasep(Inconsistent, &decl.inputs, |s, ty| {
s.ibox(INDENT_UNIT); s.ibox(INDENT_UNIT);
if let Some(arg_name) = arg_names.get(i) { if let Some(arg_name) = arg_names.get(i) {
s.s.word(arg_name.as_str().to_string()); s.s.word(arg_name.to_string());
s.s.word(":"); s.s.word(":");
s.s.space(); s.s.space();
} else if let Some(body_id) = body_id { } else if let Some(body_id) = body_id {

View File

@ -9,7 +9,7 @@ use std::mem;
use syntax::ast; use syntax::ast;
use syntax::feature_gate; use syntax::feature_gate;
use syntax::parse::token; use syntax::parse::token;
use syntax::symbol::LocalInternedString; use syntax::symbol::SymbolStr;
use syntax::tokenstream; use syntax::tokenstream;
use syntax_pos::SourceFile; use syntax_pos::SourceFile;
@ -18,7 +18,7 @@ use crate::hir::def_id::{DefId, CrateNum, CRATE_DEF_INDEX};
use smallvec::SmallVec; use smallvec::SmallVec;
use rustc_data_structures::stable_hasher::{HashStable, ToStableHashKey, StableHasher}; use rustc_data_structures::stable_hasher::{HashStable, ToStableHashKey, StableHasher};
impl<'a> HashStable<StableHashingContext<'a>> for LocalInternedString { impl<'a> HashStable<StableHashingContext<'a>> for SymbolStr {
#[inline] #[inline]
fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
let str = self as &str; let str = self as &str;
@ -26,13 +26,13 @@ impl<'a> HashStable<StableHashingContext<'a>> for LocalInternedString {
} }
} }
impl<'a> ToStableHashKey<StableHashingContext<'a>> for LocalInternedString { impl<'a> ToStableHashKey<StableHashingContext<'a>> for SymbolStr {
type KeyType = LocalInternedString; type KeyType = SymbolStr;
#[inline] #[inline]
fn to_stable_hash_key(&self, fn to_stable_hash_key(&self,
_: &StableHashingContext<'a>) _: &StableHashingContext<'a>)
-> LocalInternedString { -> SymbolStr {
self.clone() self.clone()
} }
} }
@ -45,12 +45,12 @@ impl<'a> HashStable<StableHashingContext<'a>> for ast::Name {
} }
impl<'a> ToStableHashKey<StableHashingContext<'a>> for ast::Name { impl<'a> ToStableHashKey<StableHashingContext<'a>> for ast::Name {
type KeyType = LocalInternedString; type KeyType = SymbolStr;
#[inline] #[inline]
fn to_stable_hash_key(&self, fn to_stable_hash_key(&self,
_: &StableHashingContext<'a>) _: &StableHashingContext<'a>)
-> LocalInternedString { -> SymbolStr {
self.as_str() self.as_str()
} }
} }

View File

@ -486,7 +486,7 @@ impl CodegenUnitNameBuilder<'tcx> {
if self.tcx.sess.opts.debugging_opts.human_readable_cgu_names { if self.tcx.sess.opts.debugging_opts.human_readable_cgu_names {
cgu_name cgu_name
} else { } else {
let cgu_name = &cgu_name.as_str()[..]; let cgu_name = &cgu_name.as_str();
Symbol::intern(&CodegenUnit::mangle_name(cgu_name)) Symbol::intern(&CodegenUnit::mangle_name(cgu_name))
} }
} }

View File

@ -1130,7 +1130,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
let restrict_msg = "consider further restricting this bound"; let restrict_msg = "consider further restricting this bound";
let param_name = self_ty.to_string(); let param_name = self_ty.to_string();
for param in generics.params.iter().filter(|p| { for param in generics.params.iter().filter(|p| {
&param_name == std::convert::AsRef::<str>::as_ref(&p.name.ident().as_str()) p.name.ident().as_str() == param_name
}) { }) {
if param_name.starts_with("impl ") { if param_name.starts_with("impl ") {
// `impl Trait` in argument: // `impl Trait` in argument:

View File

@ -180,7 +180,7 @@ impl<'tcx> OnUnimplementedDirective {
c.ident().map_or(false, |ident| { c.ident().map_or(false, |ident| {
options.contains(&( options.contains(&(
ident.name, ident.name,
c.value_str().map(|s| s.as_str().to_string()) c.value_str().map(|s| s.to_string())
)) ))
}) })
}) { }) {

View File

@ -264,7 +264,7 @@ impl<'sess> OnDiskCache<'sess> {
let sorted_cnums = sorted_cnums_including_local_crate(tcx); let sorted_cnums = sorted_cnums_including_local_crate(tcx);
let prev_cnums: Vec<_> = sorted_cnums.iter() let prev_cnums: Vec<_> = sorted_cnums.iter()
.map(|&cnum| { .map(|&cnum| {
let crate_name = tcx.original_crate_name(cnum).as_str().to_string(); let crate_name = tcx.original_crate_name(cnum).to_string();
let crate_disambiguator = tcx.crate_disambiguator(cnum); let crate_disambiguator = tcx.crate_disambiguator(cnum);
(cnum.as_u32(), crate_name, crate_disambiguator) (cnum.as_u32(), crate_name, crate_disambiguator)
}) })

View File

@ -314,7 +314,7 @@ pub fn from_fn_attrs(
codegen_fn_attrs.target_features codegen_fn_attrs.target_features
.iter() .iter()
.map(|f| { .map(|f| {
let feature = &*f.as_str(); let feature = &f.as_str();
format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature)) format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
}) })
) )

View File

@ -34,11 +34,11 @@ pub fn item_namespace(cx: &CodegenCx<'ll, '_>, def_id: DefId) -> &'ll DIScope {
}); });
let namespace_name = match def_key.disambiguated_data.data { let namespace_name = match def_key.disambiguated_data.data {
DefPathData::CrateRoot => cx.tcx.crate_name(def_id.krate).as_str(), DefPathData::CrateRoot => cx.tcx.crate_name(def_id.krate),
data => data.as_symbol().as_str() data => data.as_symbol()
}; };
let namespace_name = SmallCStr::new(&namespace_name); let namespace_name = SmallCStr::new(&namespace_name.as_str());
let scope = unsafe { let scope = unsafe {
llvm::LLVMRustDIBuilderCreateNameSpace( llvm::LLVMRustDIBuilderCreateNameSpace(

View File

@ -53,7 +53,7 @@ impl Command {
} }
pub fn sym_arg(&mut self, arg: Symbol) -> &mut Command { pub fn sym_arg(&mut self, arg: Symbol) -> &mut Command {
self.arg(&arg.as_str()); self.arg(&*arg.as_str());
self self
} }

View File

@ -129,9 +129,9 @@ fn reachable_non_generics_provider(
// //
// In general though we won't link right if these // In general though we won't link right if these
// symbols are stripped, and LTO currently strips them. // symbols are stripped, and LTO currently strips them.
if &*name == "rust_eh_personality" || if name == "rust_eh_personality" ||
&*name == "rust_eh_register_frames" || name == "rust_eh_register_frames" ||
&*name == "rust_eh_unregister_frames" { name == "rust_eh_unregister_frames" {
SymbolExportLevel::C SymbolExportLevel::C
} else { } else {
SymbolExportLevel::Rust SymbolExportLevel::Rust

View File

@ -552,8 +552,7 @@ pub fn codegen_crate<B: ExtraBackendMethods>(
} else if let Some(kind) = *tcx.sess.allocator_kind.get() { } else if let Some(kind) = *tcx.sess.allocator_kind.get() {
let llmod_id = cgu_name_builder.build_cgu_name(LOCAL_CRATE, let llmod_id = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
&["crate"], &["crate"],
Some("allocator")).as_str() Some("allocator")).to_string();
.to_string();
let mut modules = backend.new_metadata(tcx, &llmod_id); let mut modules = backend.new_metadata(tcx, &llmod_id);
time(tcx.sess, "write allocator module", || { time(tcx.sess, "write allocator module", || {
backend.codegen_allocator(tcx, &mut modules, kind) backend.codegen_allocator(tcx, &mut modules, kind)
@ -576,8 +575,7 @@ pub fn codegen_crate<B: ExtraBackendMethods>(
// Codegen the encoded metadata. // Codegen the encoded metadata.
let metadata_cgu_name = cgu_name_builder.build_cgu_name(LOCAL_CRATE, let metadata_cgu_name = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
&["crate"], &["crate"],
Some("metadata")).as_str() Some("metadata")).to_string();
.to_string();
let mut metadata_llvm_module = backend.new_metadata(tcx, &metadata_cgu_name); let mut metadata_llvm_module = backend.new_metadata(tcx, &metadata_cgu_name);
time(tcx.sess, "write compressed metadata", || { time(tcx.sess, "write compressed metadata", || {
backend.write_compressed_metadata(tcx, &ongoing_codegen.metadata, backend.write_compressed_metadata(tcx, &ongoing_codegen.metadata,

View File

@ -121,9 +121,10 @@ fn get_symbol_hash<'tcx>(
substs.hash_stable(&mut hcx, &mut hasher); substs.hash_stable(&mut hcx, &mut hasher);
if let Some(instantiating_crate) = instantiating_crate { if let Some(instantiating_crate) = instantiating_crate {
(&tcx.original_crate_name(instantiating_crate).as_str()[..]) tcx.original_crate_name(instantiating_crate).as_str()
.hash_stable(&mut hcx, &mut hasher);
tcx.crate_disambiguator(instantiating_crate)
.hash_stable(&mut hcx, &mut hasher); .hash_stable(&mut hcx, &mut hasher);
(&tcx.crate_disambiguator(instantiating_crate)).hash_stable(&mut hcx, &mut hasher);
} }
// We want to avoid accidental collision between different types of instances. // We want to avoid accidental collision between different types of instances.

View File

@ -31,10 +31,6 @@ use syntax::symbol::{Symbol, sym};
use rustc::ich::{ATTR_PARTITION_REUSED, ATTR_PARTITION_CODEGENED, use rustc::ich::{ATTR_PARTITION_REUSED, ATTR_PARTITION_CODEGENED,
ATTR_EXPECTED_CGU_REUSE}; ATTR_EXPECTED_CGU_REUSE};
const MODULE: Symbol = sym::module;
const CFG: Symbol = sym::cfg;
const KIND: Symbol = sym::kind;
pub fn assert_module_sources(tcx: TyCtxt<'_>) { pub fn assert_module_sources(tcx: TyCtxt<'_>) {
tcx.dep_graph.with_ignore(|| { tcx.dep_graph.with_ignore(|| {
if tcx.sess.opts.incremental.is_none() { if tcx.sess.opts.incremental.is_none() {
@ -71,7 +67,7 @@ impl AssertModuleSource<'tcx> {
} else if attr.check_name(ATTR_PARTITION_CODEGENED) { } else if attr.check_name(ATTR_PARTITION_CODEGENED) {
(CguReuse::No, ComparisonKind::Exact) (CguReuse::No, ComparisonKind::Exact)
} else if attr.check_name(ATTR_EXPECTED_CGU_REUSE) { } else if attr.check_name(ATTR_EXPECTED_CGU_REUSE) {
match &self.field(attr, KIND).as_str()[..] { match &*self.field(attr, sym::kind).as_str() {
"no" => (CguReuse::No, ComparisonKind::Exact), "no" => (CguReuse::No, ComparisonKind::Exact),
"pre-lto" => (CguReuse::PreLto, ComparisonKind::Exact), "pre-lto" => (CguReuse::PreLto, ComparisonKind::Exact),
"post-lto" => (CguReuse::PostLto, ComparisonKind::Exact), "post-lto" => (CguReuse::PostLto, ComparisonKind::Exact),
@ -98,8 +94,8 @@ impl AssertModuleSource<'tcx> {
return; return;
} }
let user_path = self.field(attr, MODULE).as_str().to_string(); let user_path = self.field(attr, sym::module).to_string();
let crate_name = self.tcx.crate_name(LOCAL_CRATE).as_str().to_string(); let crate_name = self.tcx.crate_name(LOCAL_CRATE).to_string();
if !user_path.starts_with(&crate_name) { if !user_path.starts_with(&crate_name) {
let msg = format!("Found malformed codegen unit name `{}`. \ let msg = format!("Found malformed codegen unit name `{}`. \
@ -125,7 +121,7 @@ impl AssertModuleSource<'tcx> {
cgu_path_components, cgu_path_components,
cgu_special_suffix); cgu_special_suffix);
debug!("mapping '{}' to cgu name '{}'", self.field(attr, MODULE), cgu_name); debug!("mapping '{}' to cgu name '{}'", self.field(attr, sym::module), cgu_name);
if !self.available_cgus.contains(&cgu_name) { if !self.available_cgus.contains(&cgu_name) {
self.tcx.sess.span_err(attr.span, self.tcx.sess.span_err(attr.span,
@ -135,7 +131,7 @@ impl AssertModuleSource<'tcx> {
cgu_name, cgu_name,
self.available_cgus self.available_cgus
.iter() .iter()
.map(|cgu| cgu.as_str().to_string()) .map(|cgu| cgu.to_string())
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", "))); .join(", ")));
} }
@ -169,7 +165,7 @@ impl AssertModuleSource<'tcx> {
/// cfg flag called `foo`. /// cfg flag called `foo`.
fn check_config(&self, attr: &ast::Attribute) -> bool { fn check_config(&self, attr: &ast::Attribute) -> bool {
let config = &self.tcx.sess.parse_sess.config; let config = &self.tcx.sess.parse_sess.config;
let value = self.field(attr, CFG); let value = self.field(attr, sym::cfg);
debug!("check_config(config={:?}, value={:?})", config, value); debug!("check_config(config={:?}, value={:?})", config, value);
if config.iter().any(|&(name, _)| name == value) { if config.iter().any(|&(name, _)| name == value) {
debug!("check_config: matched"); debug!("check_config: matched");

View File

@ -303,7 +303,7 @@ impl DirtyCleanVisitor<'tcx> {
for item in attr.meta_item_list().unwrap_or_else(Vec::new) { for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
if item.check_name(LABEL) { if item.check_name(LABEL) {
let value = expect_associated_value(self.tcx, &item); let value = expect_associated_value(self.tcx, &item);
return Some(self.resolve_labels(&item, value.as_str().as_ref())); return Some(self.resolve_labels(&item, &value.as_str()));
} }
} }
None None
@ -314,7 +314,7 @@ impl DirtyCleanVisitor<'tcx> {
for item in attr.meta_item_list().unwrap_or_else(Vec::new) { for item in attr.meta_item_list().unwrap_or_else(Vec::new) {
if item.check_name(EXCEPT) { if item.check_name(EXCEPT) {
let value = expect_associated_value(self.tcx, &item); let value = expect_associated_value(self.tcx, &item);
return self.resolve_labels(&item, value.as_str().as_ref()); return self.resolve_labels(&item, &value.as_str());
} }
} }
// if no `label` or `except` is given, only the node's group are asserted // if no `label` or `except` is given, only the node's group are asserted

View File

@ -1476,14 +1476,12 @@ impl KeywordIdents {
let mut lint = cx.struct_span_lint( let mut lint = cx.struct_span_lint(
KEYWORD_IDENTS, KEYWORD_IDENTS,
ident.span, ident.span,
&format!("`{}` is a keyword in the {} edition", &format!("`{}` is a keyword in the {} edition", ident, next_edition),
ident.as_str(),
next_edition),
); );
lint.span_suggestion( lint.span_suggestion(
ident.span, ident.span,
"you can use a raw identifier to stay compatible", "you can use a raw identifier to stay compatible",
format!("r#{}", ident.as_str()), format!("r#{}", ident),
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
lint.emit() lint.emit()

View File

@ -121,7 +121,7 @@ impl<'a> CrateLoader<'a> {
// `source` stores paths which are normalized which may be different // `source` stores paths which are normalized which may be different
// from the strings on the command line. // from the strings on the command line.
let source = &self.cstore.get_crate_data(cnum).source; let source = &self.cstore.get_crate_data(cnum).source;
if let Some(entry) = self.sess.opts.externs.get(&*name.as_str()) { if let Some(entry) = self.sess.opts.externs.get(&name.as_str()) {
// Only use `--extern crate_name=path` here, not `--extern crate_name`. // Only use `--extern crate_name=path` here, not `--extern crate_name`.
let found = entry.locations.iter().filter_map(|l| l.as_ref()).any(|l| { let found = entry.locations.iter().filter_map(|l| l.as_ref()).any(|l| {
let l = fs::canonicalize(l).ok(); let l = fs::canonicalize(l).ok();

View File

@ -68,7 +68,7 @@ impl ItemLikeVisitor<'tcx> for Collector<'tcx> {
Some(name) => name, Some(name) => name,
None => continue, // skip like historical compilers None => continue, // skip like historical compilers
}; };
lib.kind = match &kind.as_str()[..] { lib.kind = match &*kind.as_str() {
"static" => cstore::NativeStatic, "static" => cstore::NativeStatic,
"static-nobundle" => cstore::NativeStaticNobundle, "static-nobundle" => cstore::NativeStaticNobundle,
"dylib" => cstore::NativeUnknown, "dylib" => cstore::NativeUnknown,

View File

@ -974,7 +974,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
let mut err = self.cannot_borrow_across_destructor(borrow_span); let mut err = self.cannot_borrow_across_destructor(borrow_span);
let what_was_dropped = match self.describe_place(place.as_ref()) { let what_was_dropped = match self.describe_place(place.as_ref()) {
Some(name) => format!("`{}`", name.as_str()), Some(name) => format!("`{}`", name),
None => String::from("temporary value"), None => String::from("temporary value"),
}; };

View File

@ -95,7 +95,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
) -> InterpResult<'tcx, bool> { ) -> InterpResult<'tcx, bool> {
let substs = instance.substs; let substs = instance.substs;
let intrinsic_name = &self.tcx.item_name(instance.def_id()).as_str()[..]; let intrinsic_name = &*self.tcx.item_name(instance.def_id()).as_str();
match intrinsic_name { match intrinsic_name {
"caller_location" => { "caller_location" => {
let caller = self.tcx.sess.source_map().lookup_char_pos(span.lo()); let caller = self.tcx.sess.source_map().lookup_char_pos(span.lo());

View File

@ -642,8 +642,8 @@ pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: DefId) {
struct_span_err!( struct_span_err!(
tcx.sess, source_info.span, E0133, tcx.sess, source_info.span, E0133,
"{} is unsafe and requires unsafe function or block", description) "{} is unsafe and requires unsafe function or block", description)
.span_label(source_info.span, &description.as_str()[..]) .span_label(source_info.span, &*description.as_str())
.note(&details.as_str()[..]) .note(&details.as_str())
.emit(); .emit();
} }
UnsafetyViolationKind::ExternStatic(lint_hir_id) => { UnsafetyViolationKind::ExternStatic(lint_hir_id) => {
@ -651,8 +651,8 @@ pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: DefId) {
lint_hir_id, lint_hir_id,
source_info.span, source_info.span,
&format!("{} is unsafe and requires unsafe function or block \ &format!("{} is unsafe and requires unsafe function or block \
(error E0133)", &description.as_str()[..]), (error E0133)", description),
&details.as_str()[..]); &details.as_str());
} }
UnsafetyViolationKind::BorrowPacked(lint_hir_id) => { UnsafetyViolationKind::BorrowPacked(lint_hir_id) => {
if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) { if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
@ -662,8 +662,8 @@ pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: DefId) {
lint_hir_id, lint_hir_id,
source_info.span, source_info.span,
&format!("{} is unsafe and requires unsafe function or block \ &format!("{} is unsafe and requires unsafe function or block \
(error E0133)", &description.as_str()[..]), (error E0133)", description),
&details.as_str()[..]); &details.as_str());
} }
} }
} }

View File

@ -537,7 +537,7 @@ impl Qualif for IsNotPromotable {
Abi::RustIntrinsic | Abi::RustIntrinsic |
Abi::PlatformIntrinsic => { Abi::PlatformIntrinsic => {
assert!(!cx.tcx.is_const_fn(def_id)); assert!(!cx.tcx.is_const_fn(def_id));
match &cx.tcx.item_name(def_id).as_str()[..] { match &*cx.tcx.item_name(def_id).as_str() {
| "size_of" | "size_of"
| "min_align_of" | "min_align_of"
| "needs_drop" | "needs_drop"
@ -1477,7 +1477,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Checker<'a, 'tcx> {
Abi::RustIntrinsic | Abi::RustIntrinsic |
Abi::PlatformIntrinsic => { Abi::PlatformIntrinsic => {
assert!(!self.tcx.is_const_fn(def_id)); assert!(!self.tcx.is_const_fn(def_id));
match &self.tcx.item_name(def_id).as_str()[..] { match &*self.tcx.item_name(def_id).as_str() {
// special intrinsic that can be called diretly without an intrinsic // special intrinsic that can be called diretly without an intrinsic
// feature gate needs a language feature gate // feature gate needs a language feature gate
"transmute" => { "transmute" => {

View File

@ -402,7 +402,7 @@ fn check_terminator(
/// ///
/// Adding more intrinsics requires sign-off from @rust-lang/lang. /// Adding more intrinsics requires sign-off from @rust-lang/lang.
fn is_intrinsic_whitelisted(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool { fn is_intrinsic_whitelisted(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
match &tcx.item_name(def_id).as_str()[..] { match &*tcx.item_name(def_id).as_str() {
| "size_of" | "size_of"
| "min_align_of" | "min_align_of"
| "needs_drop" | "needs_drop"

View File

@ -1876,7 +1876,7 @@ impl<'a, 'b> LateResolutionVisitor<'a, '_> {
None None
} }
}); });
find_best_match_for_name(names, &*ident.as_str(), None) find_best_match_for_name(names, &ident.as_str(), None)
}); });
self.r.record_partial_res(expr.id, PartialRes::new(Res::Err)); self.r.record_partial_res(expr.id, PartialRes::new(Res::Err));
self.r.report_error( self.r.report_error(

View File

@ -308,7 +308,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}) = parent { }) = parent {
if let Ok(src) = cm.span_to_snippet(sp) { if let Ok(src) = cm.span_to_snippet(sp) {
for field in fields { for field in fields {
if field.ident.as_str() == src.as_str() && field.is_shorthand { if field.ident.as_str() == src && field.is_shorthand {
return true; return true;
} }
} }
@ -409,13 +409,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let mut sugg_sp = sp; let mut sugg_sp = sp;
if let hir::ExprKind::MethodCall(segment, _sp, args) = &expr.kind { if let hir::ExprKind::MethodCall(segment, _sp, args) = &expr.kind {
let clone_trait = self.tcx.lang_items().clone_trait().unwrap(); let clone_trait = self.tcx.lang_items().clone_trait().unwrap();
if let ([arg], Some(true), "clone") = ( if let ([arg], Some(true), sym::clone) = (
&args[..], &args[..],
self.tables.borrow().type_dependent_def_id(expr.hir_id).map(|did| { self.tables.borrow().type_dependent_def_id(expr.hir_id).map(|did| {
let ai = self.tcx.associated_item(did); let ai = self.tcx.associated_item(did);
ai.container == ty::TraitContainer(clone_trait) ai.container == ty::TraitContainer(clone_trait)
}), }),
&segment.ident.as_str()[..], segment.ident.name,
) { ) {
// If this expression had a clone call when suggesting borrowing // If this expression had a clone call when suggesting borrowing
// we want to suggest removing it because it'd now be unecessary. // we want to suggest removing it because it'd now be unecessary.

View File

@ -835,11 +835,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
sp, sp,
&message(format!( &message(format!(
"restrict type parameter `{}` with", "restrict type parameter `{}` with",
param.name.ident().as_str(), param.name.ident(),
)), )),
candidates.iter().map(|t| format!( candidates.iter().map(|t| format!(
"{}{} {}{}", "{}{} {}{}",
param.name.ident().as_str(), param.name.ident(),
if impl_trait { " +" } else { ":" }, if impl_trait { " +" } else { ":" },
self.tcx.def_path_str(t.def_id), self.tcx.def_path_str(t.def_id),
if has_bounds.is_some() { " + "} else { "" }, if has_bounds.is_some() { " + "} else { "" },

View File

@ -978,7 +978,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
); );
// we don't want to throw `E0027` in case we have thrown `E0026` for them // we don't want to throw `E0027` in case we have thrown `E0026` for them
unmentioned_fields.retain(|&x| x.as_str() != suggested_name.as_str()); unmentioned_fields.retain(|&x| x.name != suggested_name);
} }
} }
} }

View File

@ -2408,7 +2408,7 @@ fn compute_sig_of_foreign_fn_decl<'tcx>(
abi: abi::Abi, abi: abi::Abi,
) -> ty::PolyFnSig<'tcx> { ) -> ty::PolyFnSig<'tcx> {
let unsafety = if abi == abi::Abi::RustIntrinsic { let unsafety = if abi == abi::Abi::RustIntrinsic {
intrinsic_operation_unsafety(&*tcx.item_name(def_id).as_str()) intrinsic_operation_unsafety(&tcx.item_name(def_id).as_str())
} else { } else {
hir::Unsafety::Unsafe hir::Unsafety::Unsafe
}; };

View File

@ -404,7 +404,7 @@ impl<'a> fmt::Display for Html<'a> {
if !human_readable.is_empty() { if !human_readable.is_empty() {
fmt.write_str(human_readable) fmt.write_str(human_readable)
} else if let Some(v) = value { } else if let Some(v) = value {
write!(fmt, "<code>{}=\"{}\"</code>", Escape(n), Escape(&*v.as_str())) write!(fmt, "<code>{}=\"{}\"</code>", Escape(n), Escape(&v.as_str()))
} else { } else {
write!(fmt, "<code>{}</code>", Escape(n)) write!(fmt, "<code>{}</code>", Escape(n))
} }

View File

@ -1167,7 +1167,7 @@ fn external_path(cx: &DocContext<'_>, name: Symbol, trait_did: Option<DefId>, ha
global: false, global: false,
res: Res::Err, res: Res::Err,
segments: vec![PathSegment { segments: vec![PathSegment {
name: name.as_str().to_string(), name: name.to_string(),
args: external_generic_args(cx, trait_did, has_self, bindings, substs) args: external_generic_args(cx, trait_did, has_self, bindings, substs)
}], }],
} }
@ -3704,7 +3704,7 @@ fn qpath_to_string(p: &hir::QPath) -> String {
s.push_str("::"); s.push_str("::");
} }
if seg.ident.name != kw::PathRoot { if seg.ident.name != kw::PathRoot {
s.push_str(&*seg.ident.as_str()); s.push_str(&seg.ident.as_str());
} }
} }
s s

View File

@ -2964,7 +2964,7 @@ fn render_attribute(attr: &ast::MetaItem) -> Option<String> {
if attr.is_word() { if attr.is_word() {
Some(path) Some(path)
} else if let Some(v) = attr.value_str() { } else if let Some(v) = attr.value_str() {
Some(format!("{} = {:?}", path, v.as_str())) Some(format!("{} = {:?}", path, v))
} else if let Some(values) = attr.meta_item_list() { } else if let Some(values) = attr.meta_item_list() {
let display: Vec<_> = values.iter().filter_map(|attr| { let display: Vec<_> = values.iter().filter_map(|attr| {
attr.meta_item().and_then(|mi| render_attribute(mi)) attr.meta_item().and_then(|mi| render_attribute(mi))

View File

@ -90,7 +90,7 @@ impl fmt::Debug for Lifetime {
impl fmt::Display for Lifetime { impl fmt::Display for Lifetime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.ident.name.as_str()) write!(f, "{}", self.ident.name)
} }
} }

View File

@ -823,7 +823,7 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute],
} }
if let Some(allowed) = allow_features.as_ref() { if let Some(allowed) = allow_features.as_ref() {
if allowed.iter().find(|&f| f == &name.as_str() as &str).is_none() { if allowed.iter().find(|&f| name.as_str() == *f).is_none() {
span_err!(span_handler, mi.span(), E0725, span_err!(span_handler, mi.span(), E0725,
"the feature `{}` is not in the list of allowed features", "the feature `{}` is not in the list of allowed features",
name); name);

View File

@ -134,9 +134,9 @@ impl LitKind {
let (kind, symbol, suffix) = match *self { let (kind, symbol, suffix) = match *self {
LitKind::Str(symbol, ast::StrStyle::Cooked) => { LitKind::Str(symbol, ast::StrStyle::Cooked) => {
// Don't re-intern unless the escaped string is different. // Don't re-intern unless the escaped string is different.
let s: &str = &symbol.as_str(); let s = symbol.as_str();
let escaped = s.escape_default().to_string(); let escaped = s.escape_default().to_string();
let symbol = if escaped == *s { symbol } else { Symbol::intern(&escaped) }; let symbol = if s == escaped { symbol } else { Symbol::intern(&escaped) };
(token::Str, symbol, None) (token::Str, symbol, None)
} }
LitKind::Str(symbol, ast::StrStyle::Raw(n)) => { LitKind::Str(symbol, ast::StrStyle::Raw(n)) => {

View File

@ -210,7 +210,7 @@ impl<'a> Parser<'a> {
// `/` to `\`. // `/` to `\`.
#[cfg(windows)] #[cfg(windows)]
let s = s.replace("/", "\\"); let s = s.replace("/", "\\");
Some(dir_path.join(s)) Some(dir_path.join(&*s))
} else { } else {
None None
} }
@ -229,7 +229,7 @@ impl<'a> Parser<'a> {
// `./<id>.rs` and `./<id>/mod.rs`. // `./<id>.rs` and `./<id>/mod.rs`.
let relative_prefix_string; let relative_prefix_string;
let relative_prefix = if let Some(ident) = relative { let relative_prefix = if let Some(ident) = relative {
relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR); relative_prefix_string = format!("{}{}", ident, path::MAIN_SEPARATOR);
&relative_prefix_string &relative_prefix_string
} else { } else {
"" ""
@ -314,7 +314,7 @@ impl<'a> Parser<'a> {
fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) { fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
if let Some(path) = attr::first_attr_value_str_by_name(attrs, sym::path) { if let Some(path) = attr::first_attr_value_str_by_name(attrs, sym::path) {
self.directory.path.to_mut().push(&path.as_str()); self.directory.path.to_mut().push(&*path.as_str());
self.directory.ownership = DirectoryOwnership::Owned { relative: None }; self.directory.ownership = DirectoryOwnership::Owned { relative: None };
} else { } else {
// We have to push on the current module name in the case of relative // We have to push on the current module name in the case of relative
@ -325,10 +325,10 @@ impl<'a> Parser<'a> {
// directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`. // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership { if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
if let Some(ident) = relative.take() { // remove the relative offset if let Some(ident) = relative.take() { // remove the relative offset
self.directory.path.to_mut().push(ident.as_str()); self.directory.path.to_mut().push(&*ident.as_str());
} }
} }
self.directory.path.to_mut().push(&id.as_str()); self.directory.path.to_mut().push(&*id.as_str());
} }
} }
} }

View File

@ -623,7 +623,7 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
} }
self.maybe_print_comment(attr.span.lo()); self.maybe_print_comment(attr.span.lo());
if attr.is_sugared_doc { if attr.is_sugared_doc {
self.word(attr.value_str().unwrap().as_str().to_string()); self.word(attr.value_str().unwrap().to_string());
self.hardbreak() self.hardbreak()
} else { } else {
match attr.style { match attr.style {
@ -1234,7 +1234,7 @@ impl<'a> State<'a> {
} }
ast::ItemKind::GlobalAsm(ref ga) => { ast::ItemKind::GlobalAsm(ref ga) => {
self.head(visibility_qualified(&item.vis, "global_asm!")); self.head(visibility_qualified(&item.vis, "global_asm!"));
self.s.word(ga.asm.as_str().to_string()); self.s.word(ga.asm.to_string());
self.end(); self.end();
} }
ast::ItemKind::TyAlias(ref ty, ref generics) => { ast::ItemKind::TyAlias(ref ty, ref generics) => {
@ -2335,7 +2335,7 @@ impl<'a> State<'a> {
} }
crate fn print_name(&mut self, name: ast::Name) { crate fn print_name(&mut self, name: ast::Name) {
self.s.word(name.as_str().to_string()); self.s.word(name.to_string());
self.ann.post(self, AnnNode::Name(&name)) self.ann.post(self, AnnNode::Name(&name))
} }

View File

@ -225,7 +225,7 @@ fn generic_extension<'cx>(
}; };
let mut p = Parser::new(cx.parse_sess(), tts, Some(directory), true, false, None); let mut p = Parser::new(cx.parse_sess(), tts, Some(directory), true, false, None);
p.root_module_name = p.root_module_name =
cx.current_expansion.module.mod_path.last().map(|id| id.as_str().to_string()); cx.current_expansion.module.mod_path.last().map(|id| id.to_string());
p.last_type_ascription = cx.current_expansion.prior_type_ascription; p.last_type_ascription = cx.current_expansion.prior_type_ascription;
p.process_potential_macro_variable(); p.process_potential_macro_variable();

View File

@ -21,7 +21,7 @@ pub fn expand_option_env<'cx>(cx: &'cx mut ExtCtxt<'_>,
}; };
let sp = cx.with_def_site_ctxt(sp); let sp = cx.with_def_site_ctxt(sp);
let e = match env::var(&*var.as_str()) { let e = match env::var(&var.as_str()) {
Err(..) => { Err(..) => {
let lt = cx.lifetime(sp, Ident::new(kw::StaticLifetime, sp)); let lt = cx.lifetime(sp, Ident::new(kw::StaticLifetime, sp));
cx.expr_path(cx.path_all(sp, cx.expr_path(cx.path_all(sp,

View File

@ -994,7 +994,7 @@ pub fn expand_preparsed_format_args(
vec![] vec![]
}; };
let fmt_str = &*fmt_str.as_str(); // for the suggestions below let fmt_str = &fmt_str.as_str(); // for the suggestions below
let mut parser = parse::Parser::new(fmt_str, str_style, skips, append_newline); let mut parser = parse::Parser::new(fmt_str, str_style, skips, append_newline);
let mut unverified_pieces = Vec::new(); let mut unverified_pieces = Vec::new();

View File

@ -806,9 +806,9 @@ impl Ident {
Ident::new(self.name, self.span.modern_and_legacy()) Ident::new(self.name, self.span.modern_and_legacy())
} }
/// Convert the name to a `LocalInternedString`. This is a slowish /// Convert the name to a `SymbolStr`. This is a slowish operation because
/// operation because it requires locking the symbol interner. /// it requires locking the symbol interner.
pub fn as_str(self) -> LocalInternedString { pub fn as_str(self) -> SymbolStr {
self.name.as_str() self.name.as_str()
} }
} }
@ -896,11 +896,11 @@ impl Symbol {
}) })
} }
/// Convert to a `LocalInternedString`. This is a slowish operation because /// Convert to a `SymbolStr`. This is a slowish operation because it
/// it requires locking the symbol interner. /// requires locking the symbol interner.
pub fn as_str(self) -> LocalInternedString { pub fn as_str(self) -> SymbolStr {
with_interner(|interner| unsafe { with_interner(|interner| unsafe {
LocalInternedString { SymbolStr {
string: std::mem::transmute::<&str, &str>(interner.get(self)) string: std::mem::transmute::<&str, &str>(interner.get(self))
} }
}) })
@ -973,6 +973,7 @@ impl Interner {
self.names.insert(string, name); self.names.insert(string, name);
name name
} }
// Get the symbol as a string. `Symbol::as_str()` should be used in // Get the symbol as a string. `Symbol::as_str()` should be used in
// preference to this function. // preference to this function.
pub fn get(&self, symbol: Symbol) -> &str { pub fn get(&self, symbol: Symbol) -> &str {
@ -1078,7 +1079,6 @@ impl Ident {
} }
} }
// If an interner exists, return it. Otherwise, prepare a fresh one.
#[inline] #[inline]
fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T { fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock())) GLOBALS.with(|globals| f(&mut *globals.symbol_interner.lock()))
@ -1092,46 +1092,42 @@ fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
/// safely treat `string` which points to interner data, as an immortal string, /// safely treat `string` which points to interner data, as an immortal string,
/// as long as this type never crosses between threads. /// as long as this type never crosses between threads.
// //
// FIXME: ensure that the interner outlives any thread which uses // FIXME: ensure that the interner outlives any thread which uses `SymbolStr`,
// `LocalInternedString`, by creating a new thread right after constructing the // by creating a new thread right after constructing the interner.
// interner.
#[derive(Clone, Eq, PartialOrd, Ord)] #[derive(Clone, Eq, PartialOrd, Ord)]
pub struct LocalInternedString { pub struct SymbolStr {
string: &'static str, string: &'static str,
} }
impl<U: ?Sized> std::convert::AsRef<U> for LocalInternedString // This impl allows a `SymbolStr` to be directly equated with a `String` or
where // `&str`.
str: std::convert::AsRef<U> impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for SymbolStr {
{
#[inline]
fn as_ref(&self) -> &U {
self.string.as_ref()
}
}
impl<T: std::ops::Deref<Target = str>> std::cmp::PartialEq<T> for LocalInternedString {
fn eq(&self, other: &T) -> bool { fn eq(&self, other: &T) -> bool {
self.string == other.deref() self.string == other.deref()
} }
} }
impl !Send for LocalInternedString {} impl !Send for SymbolStr {}
impl !Sync for LocalInternedString {} impl !Sync for SymbolStr {}
impl std::ops::Deref for LocalInternedString { /// This impl means that if `ss` is a `SymbolStr`:
/// - `*ss` is a `str`;
/// - `&*ss` is a `&str`;
/// - `&ss as &str` is a `&str`, which means that `&ss` can be passed to a
/// function expecting a `&str`.
impl std::ops::Deref for SymbolStr {
type Target = str; type Target = str;
#[inline] #[inline]
fn deref(&self) -> &str { self.string } fn deref(&self) -> &str { self.string }
} }
impl fmt::Debug for LocalInternedString { impl fmt::Debug for SymbolStr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.string, f) fmt::Debug::fmt(self.string, f)
} }
} }
impl fmt::Display for LocalInternedString { impl fmt::Display for SymbolStr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self.string, f) fmt::Display::fmt(self.string, f)
} }