Skip to content

[DRAFT] Change Symbol::as_str() to &self -> &str. #76460

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion compiler/rustc_ast_passes/src/feature_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ impl<'a> PostExpansionVisitor<'a> {
fn check_abi(&self, abi: ast::StrLit) {
let ast::StrLit { symbol_unescaped, span, .. } = abi;

match &*symbol_unescaped.as_str() {
match symbol_unescaped.as_str() {
// Stable
"Rust" | "C" | "cdecl" | "stdcall" | "fastcall" | "aapcs" | "win64" | "sysv64"
| "system" => {}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_attr/src/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ where

// These unwraps are safe because `get` ensures the meta item
// is a name/value pair string literal.
issue_num = match &*issue.unwrap().as_str() {
issue_num = match issue.unwrap().as_str() {
"none" => None,
issue => {
let emit_diag = |msg: &str| {
Expand Down
7 changes: 4 additions & 3 deletions compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2014,8 +2014,8 @@ fn prepare_enum_metadata(
let item_name;
let discriminant_name = match enum_type.kind() {
ty::Adt(..) => {
item_name = tcx.item_name(enum_def_id).as_str();
&*item_name
item_name = tcx.item_name(enum_def_id);
item_name.as_str()
}
ty::Generator(..) => enum_name.as_str(),
_ => bug!(),
Expand Down Expand Up @@ -2483,7 +2483,8 @@ pub fn create_global_var_metadata(cx: &CodegenCx<'ll, '_>, def_id: DefId, global
let is_local_to_unit = is_node_local_to_unit(cx, def_id);
let variable_type = Instance::mono(cx.tcx, def_id).ty(cx.tcx, ty::ParamEnv::reveal_all());
let type_metadata = type_metadata(cx, variable_type, span);
let var_name = tcx.item_name(def_id).as_str();
let var_name = tcx.item_name(def_id);
let var_name = var_name.as_str();
let linkage_name = mangled_name_of_instance(cx, Instance::mono(tcx, def_id)).name;
// When empty, linkage_name field is omitted,
// which is what we want for no_mangle statics
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_hir/src/definitions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,10 +214,10 @@ impl DefPath {
where
F: FnOnce(CrateNum) -> Symbol,
{
let crate_name_str = crate_imported_name(self.krate).as_str();
let mut s = String::with_capacity(crate_name_str.len() + self.data.len() * 16);
let crate_name = crate_imported_name(self.krate);
let mut s = String::with_capacity(crate_name.as_str().len() + self.data.len() * 16);

write!(s, "::{}", crate_name_str).unwrap();
write!(s, "::{}", crate_name).unwrap();

for component in &self.data {
if component.disambiguator == 0 {
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_interface/src/passes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -948,8 +948,8 @@ fn encode_and_write_metadata(

let need_metadata_file = tcx.sess.opts.output_types.contains_key(&OutputType::Metadata);
if need_metadata_file {
let crate_name = &tcx.crate_name(LOCAL_CRATE).as_str();
let out_filename = filename_for_metadata(tcx.sess, crate_name, outputs);
let crate_name = &tcx.crate_name(LOCAL_CRATE);
let out_filename = filename_for_metadata(tcx.sess, crate_name.as_str(), outputs);
// To avoid races with another rustc process scanning the output directory,
// we need to write the file somewhere else and atomically move it to its
// final destination, with an `fs::rename` call. In order for the rename to
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_metadata/src/locator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -932,7 +932,8 @@ impl CrateError {
let candidates = libraries
.iter()
.filter_map(|(_, lib)| {
let crate_name = &lib.metadata.get_root().name().as_str();
let crate_name = lib.metadata.get_root().name();
let crate_name = crate_name.as_str();
match (&lib.source.dylib, &lib.source.rlib) {
(Some((pd, _)), Some((pr, _))) => Some(format!(
"\ncrate `{}`: {}\n{:>padding$}",
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_metadata/src/native_libs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ impl ItemLikeVisitor<'tcx> for Collector<'tcx> {
Some(name) => name,
None => continue, // skip like historical compilers
};
lib.kind = match &*kind.as_str() {
lib.kind = match kind.as_str() {
"static" => NativeLibKind::StaticBundle,
"static-nobundle" => NativeLibKind::StaticNoBundle,
"dylib" => NativeLibKind::Dylib,
Expand Down
4 changes: 3 additions & 1 deletion compiler/rustc_middle/src/hir/map/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,9 @@ fn upstream_crates(cstore: &dyn CrateStore) -> Vec<(Symbol, Fingerprint, Svh)> {
(name, disambiguator, hash)
})
.collect();
upstream_crates.sort_unstable_by_key(|&(name, dis, _)| (name.as_str(), dis));
upstream_crates.sort_unstable_by(|&(name1, dis1, _), &(name2, dis2, _)| {
(name1.as_str(), dis1).partial_cmp(&(name2.as_str(), dis2)).unwrap()
});
upstream_crates
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/middle/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub mod lib_features {
.map(|(f, s)| (*f, Some(*s)))
.chain(self.unstable.iter().map(|f| (*f, None)))
.collect();
all_features.sort_unstable_by_key(|f| f.0.as_str());
all_features.sort_unstable_by(|a, b| a.0.as_str().partial_cmp(b.0.as_str()).unwrap());
all_features
}
}
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_middle/src/middle/stability.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,8 @@ pub fn deprecation_suggestion(
pub fn deprecation_message(depr: &Deprecation, kind: &str, path: &str) -> (String, &'static Lint) {
let (message, lint) = if deprecation_in_effect(
depr.is_since_rustc_version,
depr.since.map(Symbol::as_str).as_deref(),
// njn: surely can use as_str() somehow here
depr.since.map(Symbol::as_str2).as_deref(),
) {
(format!("use of deprecated {} `{}`", kind, path), DEPRECATED)
} else {
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_middle/src/mir/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2222,7 +2222,7 @@ impl<'tcx> Debug for Rvalue<'tcx> {
if let Some(upvars) = tcx.upvars_mentioned(def_id) {
for (&var_id, place) in upvars.keys().zip(places) {
let var_name = tcx.hir().name(var_id);
struct_fmt.field(&var_name.as_str(), place);
struct_fmt.field(var_name.as_str(), place);
}
}

Expand All @@ -2241,7 +2241,7 @@ impl<'tcx> Debug for Rvalue<'tcx> {
if let Some(upvars) = tcx.upvars_mentioned(def_id) {
for (&var_id, place) in upvars.keys().zip(places) {
let var_name = tcx.hir().name(var_id);
struct_fmt.field(&var_name.as_str(), place);
struct_fmt.field(var_name.as_str(), place);
}
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/mir/mono.rs
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@ impl CodegenUnitNameBuilder<'tcx> {
if self.tcx.sess.opts.debugging_opts.human_readable_cgu_names {
cgu_name
} else {
Symbol::intern(&CodegenUnit::mangle_name(&cgu_name.as_str()))
Symbol::intern(&CodegenUnit::mangle_name(cgu_name.as_str()))
}
}

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_middle/src/ty/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1183,8 +1183,8 @@ impl<'tcx> TyCtxt<'tcx> {
}

pub fn consider_optimizing<T: Fn() -> String>(&self, msg: T) -> bool {
let cname = self.crate_name(LOCAL_CRATE).as_str();
self.sess.consider_optimizing(&cname, msg)
let cname = self.crate_name(LOCAL_CRATE);
self.sess.consider_optimizing(cname.as_str(), msg)
}

pub fn lib_features(self) -> &'tcx middle::lib_features::LibFeatures {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/query/profiling_support.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ impl<'p, 'c, 'tcx> QueryKeyStringBuilder<'p, 'c, 'tcx> {
}
}

let name = &*name.as_str();
let name = name.as_str();
let components = [
StringComponent::Ref(parent_string_id),
StringComponent::Value("::"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
tcx,
generics,
&mut err,
&param.name.as_str(),
param.name.as_str(),
"Copy",
None,
);
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir/src/borrow_check/diagnostics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
let decl = &self.body.local_decls[local];
match self.local_names[local] {
Some(name) if !decl.from_compiler_desugaring() => {
buf.push_str(&name.as_str());
buf.push_str(name.as_str());
Ok(())
}
_ => Err(()),
Expand Down
10 changes: 6 additions & 4 deletions compiler/rustc_mir/src/monomorphize/partitioning/merging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use rustc_data_structures::fx::FxHashMap;
use rustc_hir::def_id::LOCAL_CRATE;
use rustc_middle::mir::mono::{CodegenUnit, CodegenUnitNameBuilder};
use rustc_middle::ty::TyCtxt;
use rustc_span::symbol::{Symbol, SymbolStr};
use rustc_span::symbol::Symbol;

use crate::monomorphize::partitioning::PreInliningPartitioning;

Expand All @@ -25,11 +25,13 @@ pub fn merge_codegen_units<'tcx>(
// smallest into each other) we're sure to start off with a deterministic
// order (sorted by name). This'll mean that if two cgus have the same size
// the stable sort below will keep everything nice and deterministic.
codegen_units.sort_by_cached_key(|cgu| cgu.name().as_str());
codegen_units.sort_by(|a, b| a.name().as_str().partial_cmp(b.name().as_str()).unwrap());

// This map keeps track of what got merged into what.
let mut cgu_contents: FxHashMap<Symbol, Vec<SymbolStr>> =
codegen_units.iter().map(|cgu| (cgu.name(), vec![cgu.name().as_str()])).collect();
let mut cgu_contents: FxHashMap<Symbol, Vec<String>> = codegen_units
.iter()
.map(|cgu| (cgu.name(), vec![cgu.name().as_str().to_owned()]))
.collect();

// Merge the two smallest codegen units until the target size is reached.
while codegen_units.len() > target_cgu_count {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir/src/monomorphize/partitioning/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ pub fn partition<'tcx>(
internalization_candidates: _,
} = post_inlining;

result.sort_by_cached_key(|cgu| cgu.name().as_str());
result.sort_by(|a, b| a.name().as_str().partial_cmp(b.name().as_str()).unwrap());

result
}
Expand Down
6 changes: 4 additions & 2 deletions compiler/rustc_parse/src/parser/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1398,7 +1398,8 @@ impl<'a> Parser<'a> {
);
}
LitError::InvalidIntSuffix => {
let suf = suffix.expect("suffix error with no suffix").as_str();
let suf = suffix.expect("suffix error with no suffix");
let suf = suf.as_str();
if looks_like_width_suffix(&['i', 'u'], &suf) {
// If it looks like a width, try to be helpful.
let msg = format!("invalid width `{}` for integer literal", &suf[1..]);
Expand All @@ -1414,7 +1415,8 @@ impl<'a> Parser<'a> {
}
}
LitError::InvalidFloatSuffix => {
let suf = suffix.expect("suffix error with no suffix").as_str();
let suf = suffix.expect("suffix error with no suffix");
let suf = suf.as_str();
if looks_like_width_suffix(&['f'], &suf) {
// If it looks like a width, try to be helpful.
let msg = format!("invalid width `{}` for float literal", &suf[1..]);
Expand Down
7 changes: 3 additions & 4 deletions compiler/rustc_resolve/src/diagnostics.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use std::cmp::Reverse;
use std::ptr;

use rustc_ast::util::lev_distance::find_best_match_for_name;
Expand Down Expand Up @@ -711,7 +710,7 @@ impl<'a> Resolver<'a> {
});

// Make sure error reporting is deterministic.
suggestions.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
suggestions.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());

match find_best_match_for_name(
suggestions.iter().map(|suggestion| &suggestion.candidate),
Expand Down Expand Up @@ -1306,12 +1305,12 @@ impl<'a, 'b> ImportResolver<'a, 'b> {
return None;
}

// Sort extern crate names in reverse order to get
// Sort extern crate names in *reverse* order to get
// 1) some consistent ordering for emitted diagnostics, and
// 2) `std` suggestions before `core` suggestions.
let mut extern_crate_names =
self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
extern_crate_names.sort_by_key(|name| Reverse(name.as_str()));
extern_crate_names.sort_by(|a, b| b.as_str().partial_cmp(a.as_str()).unwrap());

for name in extern_crate_names.into_iter() {
// Replace first ident with a crate name and check if that is valid.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_resolve/src/late/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -946,7 +946,7 @@ impl<'a> LateResolutionVisitor<'a, '_, '_> {

let name = path[path.len() - 1].ident.name;
// Make sure error reporting is deterministic.
names.sort_by_cached_key(|suggestion| suggestion.candidate.as_str());
names.sort_by(|a, b| a.candidate.as_str().partial_cmp(b.candidate.as_str()).unwrap());

match find_best_match_for_name(
names.iter().map(|suggestion| &suggestion.candidate),
Expand Down
25 changes: 22 additions & 3 deletions compiler/rustc_span/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1256,7 +1256,15 @@ impl Ident {

/// Convert the name to a `SymbolStr`. This is a slowish operation because
/// it requires locking the symbol interner.
pub fn as_str(self) -> SymbolStr {
// njn: want to remove this
pub fn as_str2(self) -> SymbolStr {
self.name.as_str2()
}

/// Access the underlying string. This is a slowish operation because it
/// requires locking the symbol interner.
// njn: comment about the lifetime of the return value being a lie?
pub fn as_str(&self) -> &str {
self.name.as_str()
}
}
Expand Down Expand Up @@ -1402,12 +1410,20 @@ impl Symbol {

/// Convert to a `SymbolStr`. This is a slowish operation because it
/// requires locking the symbol interner.
pub fn as_str(self) -> SymbolStr {
// njn: want to remove this
pub fn as_str2(self) -> SymbolStr {
with_interner(|interner| unsafe {
SymbolStr { string: std::mem::transmute::<&str, &str>(interner.get(self)) }
})
}

/// Access the underlying string. This is a slowish operation because it
/// requires locking the symbol interner.
// njn: comment about the lifetime of the return value being a lie?
pub fn as_str(&self) -> &str {
with_interner(|interner| unsafe { std::mem::transmute::<&str, &str>(interner.get(*self)) })
}

pub fn as_u32(self) -> u32 {
self.0.as_u32()
}
Expand Down Expand Up @@ -1458,7 +1474,8 @@ impl<CTX> ToStableHashKey<CTX> for Symbol {

#[inline]
fn to_stable_hash_key(&self, _: &CTX) -> SymbolStr {
self.as_str()
// njn: hmm
self.as_str2()
}
}

Expand Down Expand Up @@ -1635,6 +1652,8 @@ fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
//
// FIXME: ensure that the interner outlives any thread which uses `SymbolStr`,
// by creating a new thread right after constructing the interner.
//
// njn: want to remove this
#[derive(Clone, Eq, PartialOrd, Ord)]
pub struct SymbolStr {
string: &'static str,
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_symbol_mangling/src/v0.rs
Original file line number Diff line number Diff line change
Expand Up @@ -536,8 +536,8 @@ impl Printer<'tcx> for SymbolMangler<'tcx> {
self.push("C");
let fingerprint = self.tcx.crate_disambiguator(cnum).to_fingerprint();
self.push_disambiguator(fingerprint.to_smaller_hash());
let name = self.tcx.original_crate_name(cnum).as_str();
self.push_ident(&name);
let name = self.tcx.original_crate_name(cnum);
self.push_ident(name.as_str());
Ok(self)
}
fn path_qualified(
Expand Down Expand Up @@ -596,13 +596,13 @@ impl Printer<'tcx> for SymbolMangler<'tcx> {
}
};

let name = disambiguated_data.data.get_opt_name().map(|s| s.as_str());
let name = disambiguated_data.data.get_opt_name();

self.path_append_ns(
print_prefix,
ns,
disambiguated_data.disambiguator as u64,
name.as_ref().map_or("", |s| &s[..]),
name.as_ref().map_or("", |name| name.as_str()),
)
}
fn path_generic_args(
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_typeck/src/check/method/probe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1008,7 +1008,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
.collect();

// Sort them by the name so we have a stable result.
names.sort_by_cached_key(|n| n.as_str());
names.sort_by(|a, b| a.as_str().partial_cmp(b.as_str()).unwrap());
names
}

Expand Down
Loading