Use Symbol for the crate name instead of String/str

This commit is contained in:
Oli Scherer 2022-12-06 12:46:10 +00:00
parent e60fbaf4ce
commit d30848b30a
18 changed files with 103 additions and 92 deletions

View File

@ -102,7 +102,7 @@ pub fn link_binary<'a>(
sess,
crate_type,
outputs,
codegen_results.crate_info.local_crate_name.as_str(),
codegen_results.crate_info.local_crate_name,
);
match crate_type {
CrateType::Rlib => {

View File

@ -25,6 +25,7 @@
use rustc_errors::registry::{InvalidErrorCode, Registry};
use rustc_errors::{ErrorGuaranteed, PResult};
use rustc_feature::find_gated_cfg;
use rustc_hir::def_id::LOCAL_CRATE;
use rustc_interface::util::{self, collect_crate_types, get_codegen_backend};
use rustc_interface::{interface, Queries};
use rustc_lint::LintStore;
@ -374,14 +375,14 @@ fn run_compiler(
queries.global_ctxt()?.peek_mut().enter(|tcx| {
let result = tcx.analysis(());
if sess.opts.unstable_opts.save_analysis {
let crate_name = queries.crate_name()?.peek().clone();
let crate_name = tcx.crate_name(LOCAL_CRATE);
sess.time("save_analysis", || {
save::process_crate(
tcx,
&crate_name,
crate_name,
compiler.input(),
None,
DumpHandler::new(compiler.output_dir().as_deref(), &crate_name),
DumpHandler::new(compiler.output_dir().as_deref(), crate_name),
)
});
}
@ -678,7 +679,7 @@ fn print_crate_info(
let crate_types = collect_crate_types(sess, attrs);
for &style in &crate_types {
let fname =
rustc_session::output::filename_for_input(sess, style, &id, &t_outputs);
rustc_session::output::filename_for_input(sess, style, id, &t_outputs);
println!("{}", fname.file_name().unwrap().to_string_lossy());
}
}

View File

@ -960,7 +960,7 @@ fn pre_expansion_lint(
node_id: NodeId,
attrs: &[Attribute],
items: &[P<Item>],
name: &str,
name: Symbol,
);
}

View File

@ -1122,7 +1122,7 @@ fn wrap_flat_map_node_noop_flat_map(
ecx.current_expansion.lint_node_id,
&attrs,
&items,
ident.name.as_str(),
ident.name,
);
}

View File

@ -1,5 +1,7 @@
use crate::definitions::{DefKey, DefPathData, DisambiguatedDefPathData};
use rustc_span::def_id::{DefPathHash, StableCrateId};
use rustc_span::edition::Edition;
use rustc_span::{create_session_if_not_set_then, Symbol};
#[test]
fn def_path_hash_depends_on_crate_id() {
@ -11,26 +13,28 @@ fn def_path_hash_depends_on_crate_id() {
// the crate by changing the crate disambiguator (e.g. via bumping the
// crate's version number).
let id0 = StableCrateId::new("foo", false, vec!["1".to_string()]);
let id1 = StableCrateId::new("foo", false, vec!["2".to_string()]);
create_session_if_not_set_then(Edition::Edition2024, |_| {
let id0 = StableCrateId::new(Symbol::intern("foo"), false, vec!["1".to_string()]);
let id1 = StableCrateId::new(Symbol::intern("foo"), false, vec!["2".to_string()]);
let h0 = mk_test_hash(id0);
let h1 = mk_test_hash(id1);
let h0 = mk_test_hash(id0);
let h1 = mk_test_hash(id1);
assert_ne!(h0.stable_crate_id(), h1.stable_crate_id());
assert_ne!(h0.local_hash(), h1.local_hash());
assert_ne!(h0.stable_crate_id(), h1.stable_crate_id());
assert_ne!(h0.local_hash(), h1.local_hash());
fn mk_test_hash(stable_crate_id: StableCrateId) -> DefPathHash {
let parent_hash = DefPathHash::new(stable_crate_id, 0);
fn mk_test_hash(stable_crate_id: StableCrateId) -> DefPathHash {
let parent_hash = DefPathHash::new(stable_crate_id, 0);
let key = DefKey {
parent: None,
disambiguated_data: DisambiguatedDefPathData {
data: DefPathData::CrateRoot,
disambiguator: 0,
},
};
let key = DefKey {
parent: None,
disambiguated_data: DisambiguatedDefPathData {
data: DefPathData::CrateRoot,
disambiguator: 0,
},
};
key.compute_stable_hash(parent_hash)
}
key.compute_stable_hash(parent_hash)
}
})
}

View File

@ -109,6 +109,7 @@
use rustc_errors::ErrorGuaranteed;
use rustc_fs_util::{link_or_copy, LinkOrCopy};
use rustc_session::{Session, StableCrateId};
use rustc_span::Symbol;
use std::fs as std_fs;
use std::io::{self, ErrorKind};
@ -202,7 +203,7 @@ pub fn in_incr_comp_dir(incr_comp_session_dir: &Path, file_name: &str) -> PathBu
/// [`rustc_interface::queries::dep_graph`]: ../../rustc_interface/struct.Queries.html#structfield.dep_graph
pub fn prepare_session_directory(
sess: &Session,
crate_name: &str,
crate_name: Symbol,
stable_crate_id: StableCrateId,
) -> Result<(), ErrorGuaranteed> {
if sess.opts.incremental.is_none() {
@ -657,7 +658,7 @@ fn string_to_timestamp(s: &str) -> Result<SystemTime, ()> {
Ok(UNIX_EPOCH + duration)
}
fn crate_path(sess: &Session, crate_name: &str, stable_crate_id: StableCrateId) -> PathBuf {
fn crate_path(sess: &Session, crate_name: Symbol, stable_crate_id: StableCrateId) -> PathBuf {
let incr_dir = sess.opts.incremental.as_ref().unwrap().clone();
let stable_crate_id = base_n::encode(stable_crate_id.to_u64() as u128, INT_ENCODE_BASE);

View File

@ -158,7 +158,7 @@ pub fn create_resolver(
sess: Lrc<Session>,
metadata_loader: Box<MetadataLoaderDyn>,
krate: &ast::Crate,
crate_name: &str,
crate_name: Symbol,
) -> BoxedResolver {
trace!("create_resolver");
BoxedResolver::new(sess, move |sess, resolver_arenas| {
@ -171,7 +171,7 @@ pub fn register_plugins<'a>(
metadata_loader: &'a dyn MetadataLoader,
register_lints: impl Fn(&Session, &mut LintStore),
mut krate: ast::Crate,
crate_name: &str,
crate_name: Symbol,
) -> Result<(ast::Crate, LintStore)> {
krate = sess.time("attributes_injection", || {
rustc_builtin_macros::cmdline_attrs::inject(
@ -228,19 +228,21 @@ fn pre_expansion_lint<'a>(
lint_store: &LintStore,
registered_tools: &RegisteredTools,
check_node: impl EarlyCheckNode<'a>,
node_name: &str,
node_name: Symbol,
) {
sess.prof.generic_activity_with_arg("pre_AST_expansion_lint_checks", node_name).run(|| {
rustc_lint::check_ast_node(
sess,
true,
lint_store,
registered_tools,
None,
rustc_lint::BuiltinCombinedPreExpansionLintPass::new(),
check_node,
);
});
sess.prof.generic_activity_with_arg("pre_AST_expansion_lint_checks", node_name.as_str()).run(
|| {
rustc_lint::check_ast_node(
sess,
true,
lint_store,
registered_tools,
None,
rustc_lint::BuiltinCombinedPreExpansionLintPass::new(),
check_node,
);
},
);
}
// Cannot implement directly for `LintStore` due to trait coherence.
@ -254,7 +256,7 @@ fn pre_expansion_lint(
node_id: ast::NodeId,
attrs: &[ast::Attribute],
items: &[rustc_ast::ptr::P<ast::Item>],
name: &str,
name: Symbol,
) {
pre_expansion_lint(sess, self.0, registered_tools, (node_id, attrs, items), name);
}
@ -268,7 +270,7 @@ pub fn configure_and_expand(
sess: &Session,
lint_store: &LintStore,
mut krate: ast::Crate,
crate_name: &str,
crate_name: Symbol,
resolver: &mut Resolver<'_>,
) -> Result<ast::Crate> {
trace!("configure_and_expand");
@ -462,7 +464,7 @@ fn generated_output_paths(
sess: &Session,
outputs: &OutputFilenames,
exact_name: bool,
crate_name: &str,
crate_name: Symbol,
) -> Vec<PathBuf> {
let mut out_filenames = Vec::new();
for output_type in sess.opts.output_types.keys() {
@ -661,7 +663,7 @@ pub fn prepare_outputs(
compiler: &Compiler,
krate: &ast::Crate,
boxed_resolver: &RefCell<BoxedResolver>,
crate_name: &str,
crate_name: Symbol,
) -> Result<OutputFilenames> {
let _timer = sess.timer("prepare_outputs");
@ -771,7 +773,7 @@ pub fn create_global_ctxt<'tcx>(
dep_graph: DepGraph,
resolver: Rc<RefCell<BoxedResolver>>,
outputs: OutputFilenames,
crate_name: &str,
crate_name: Symbol,
queries: &'tcx OnceCell<TcxQueries<'tcx>>,
global_ctxt: &'tcx OnceCell<GlobalCtxt<'tcx>>,
arena: &'tcx WorkerLocal<Arena<'tcx>>,

View File

@ -17,6 +17,7 @@
use rustc_session::config::{self, OutputFilenames, OutputType};
use rustc_session::{output::find_crate_name, Session};
use rustc_span::symbol::sym;
use rustc_span::Symbol;
use std::any::Any;
use std::cell::{Ref, RefCell, RefMut};
use std::rc::Rc;
@ -74,7 +75,7 @@ pub struct Queries<'tcx> {
dep_graph_future: Query<Option<DepGraphFuture>>,
parse: Query<ast::Crate>,
crate_name: Query<String>,
crate_name: Query<Symbol>,
register_plugins: Query<(ast::Crate, Lrc<LintStore>)>,
expansion: Query<(Lrc<ast::Crate>, Rc<RefCell<BoxedResolver>>, Lrc<LintStore>)>,
dep_graph: Query<DepGraph>,
@ -135,7 +136,7 @@ pub fn register_plugins(&self) -> Result<&Query<(ast::Crate, Lrc<LintStore>)>> {
&*self.codegen_backend().metadata_loader(),
self.compiler.register_lints.as_deref().unwrap_or_else(|| empty),
krate,
&crate_name,
crate_name,
)?;
// Compute the dependency graph (in the background). We want to do
@ -149,7 +150,7 @@ pub fn register_plugins(&self) -> Result<&Query<(ast::Crate, Lrc<LintStore>)>> {
})
}
pub fn crate_name(&self) -> Result<&Query<String>> {
pub fn crate_name(&self) -> Result<&Query<Symbol>> {
self.crate_name.compute(|| {
Ok({
let parse_result = self.parse()?;
@ -165,7 +166,7 @@ pub fn expansion(
) -> Result<&Query<(Lrc<ast::Crate>, Rc<RefCell<BoxedResolver>>, Lrc<LintStore>)>> {
trace!("expansion");
self.expansion.compute(|| {
let crate_name = self.crate_name()?.peek().clone();
let crate_name = *self.crate_name()?.peek();
let (krate, lint_store) = self.register_plugins()?.take();
let _timer = self.session().timer("configure_and_expand");
let sess = self.session();
@ -173,10 +174,10 @@ pub fn expansion(
sess.clone(),
self.codegen_backend().metadata_loader(),
&krate,
&crate_name,
crate_name,
);
let krate = resolver.access(|resolver| {
passes::configure_and_expand(sess, &lint_store, krate, &crate_name, resolver)
passes::configure_and_expand(sess, &lint_store, krate, crate_name, resolver)
})?;
Ok((Lrc::new(krate), Rc::new(RefCell::new(resolver)), lint_store))
})
@ -201,20 +202,20 @@ fn dep_graph(&self) -> Result<&Query<DepGraph>> {
pub fn prepare_outputs(&self) -> Result<&Query<OutputFilenames>> {
self.prepare_outputs.compute(|| {
let (krate, boxed_resolver, _) = &*self.expansion()?.peek();
let crate_name = self.crate_name()?.peek();
let crate_name = *self.crate_name()?.peek();
passes::prepare_outputs(
self.session(),
self.compiler,
krate,
&*boxed_resolver,
&crate_name,
crate_name,
)
})
}
pub fn global_ctxt(&'tcx self) -> Result<&Query<QueryContext<'tcx>>> {
self.global_ctxt.compute(|| {
let crate_name = self.crate_name()?.peek().clone();
let crate_name = *self.crate_name()?.peek();
let outputs = self.prepare_outputs()?.take();
let dep_graph = self.dep_graph()?.peek().clone();
let (krate, resolver, lint_store) = self.expansion()?.take();
@ -225,7 +226,7 @@ pub fn global_ctxt(&'tcx self) -> Result<&Query<QueryContext<'tcx>>> {
dep_graph,
resolver,
outputs,
&crate_name,
crate_name,
&self.queries,
&self.gcx,
&self.arena,

View File

@ -245,7 +245,7 @@ impl<'a> CrateLoader<'a> {
pub fn new(
sess: &'a Session,
metadata_loader: Box<MetadataLoaderDyn>,
local_crate_name: &str,
local_crate_name: Symbol,
) -> Self {
let mut stable_crate_ids = FxHashMap::default();
stable_crate_ids.insert(sess.local_stable_crate_id(), LOCAL_CRATE);
@ -253,7 +253,7 @@ pub fn new(
CrateLoader {
sess,
metadata_loader,
local_crate_name: Symbol::intern(local_crate_name),
local_crate_name,
cstore: CStore {
// We add an empty entry for LOCAL_CRATE (which maps to zero) in
// order to make array indices in `metas` match with the
@ -1000,7 +1000,7 @@ pub fn process_extern_crate(
);
let name = match orig_name {
Some(orig_name) => {
validate_crate_name(self.sess, orig_name.as_str(), Some(item.span));
validate_crate_name(self.sess, orig_name, Some(item.span));
orig_name
}
None => item.ident.name,

View File

@ -61,8 +61,7 @@ enum MetadataKind {
.unwrap_or(MetadataKind::None);
let crate_name = tcx.crate_name(LOCAL_CRATE);
let out_filename =
filename_for_metadata(tcx.sess, crate_name.as_str(), tcx.output_filenames(()));
let out_filename = filename_for_metadata(tcx.sess, crate_name, tcx.output_filenames(()));
// 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

View File

@ -1281,7 +1281,7 @@ pub fn create_global_ctxt(
on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>,
queries: &'tcx dyn query::QueryEngine<'tcx>,
query_kinds: &'tcx [DepKindStruct<'tcx>],
crate_name: &str,
crate_name: Symbol,
output_filenames: OutputFilenames,
) -> GlobalCtxt<'tcx> {
let data_layout = s.target.parse_data_layout().unwrap_or_else(|err| {
@ -1321,7 +1321,7 @@ pub fn create_global_ctxt(
pred_rcache: Default::default(),
selection_cache: Default::default(),
evaluation_cache: Default::default(),
crate_name: Symbol::intern(crate_name),
crate_name,
data_layout,
alloc_map: Lock::new(interpret::AllocMap::new()),
output_filenames: Arc::new(output_filenames),

View File

@ -1196,7 +1196,7 @@ impl<'a> Resolver<'a> {
pub fn new(
session: &'a Session,
krate: &Crate,
crate_name: &str,
crate_name: Symbol,
metadata_loader: Box<MetadataLoaderDyn>,
arenas: &'a ResolverArenas<'a>,
) -> Resolver<'a> {

View File

@ -111,7 +111,7 @@ fn lookup_def_id(&self, ref_id: hir::HirId) -> Option<DefId> {
self.save_ctxt.lookup_def_id(ref_id)
}
pub fn dump_crate_info(&mut self, name: &str) {
pub fn dump_crate_info(&mut self, name: Symbol) {
let source_file = self.tcx.sess.local_crate_source_file.as_ref();
let crate_root = source_file.map(|source_file| {
let source_file = Path::new(source_file);
@ -124,7 +124,7 @@ pub fn dump_crate_info(&mut self, name: &str) {
let data = CratePreludeData {
crate_id: GlobalCrateId {
name: name.into(),
name: name.to_string(),
disambiguator: (self.tcx.sess.local_stable_crate_id().to_u64(), 0),
},
crate_root: crate_root.unwrap_or_else(|| "<no source>".to_owned()),
@ -135,7 +135,7 @@ pub fn dump_crate_info(&mut self, name: &str) {
self.dumper.crate_prelude(data);
}
pub fn dump_compilation_options(&mut self, input: &Input, crate_name: &str) {
pub fn dump_compilation_options(&mut self, input: &Input, crate_name: Symbol) {
// Apply possible `remap-path-prefix` remapping to the input source file
// (and don't include remapping args anymore)
let (program, arguments) = {

View File

@ -95,7 +95,7 @@ fn span_from_span(&self, span: Span) -> SpanData {
}
/// Returns path to the compilation output (e.g., libfoo-12345678.rmeta)
pub fn compilation_output(&self, crate_name: &str) -> PathBuf {
pub fn compilation_output(&self, crate_name: Symbol) -> PathBuf {
let sess = &self.tcx.sess;
// Save-analysis is emitted per whole session, not per each crate type
let crate_type = sess.crate_types()[0];
@ -894,8 +894,8 @@ pub struct DumpHandler<'a> {
}
impl<'a> DumpHandler<'a> {
pub fn new(odir: Option<&'a Path>, cratename: &str) -> DumpHandler<'a> {
DumpHandler { odir, cratename: cratename.to_owned() }
pub fn new(odir: Option<&'a Path>, cratename: Symbol) -> DumpHandler<'a> {
DumpHandler { odir, cratename: cratename.to_string() }
}
fn output_file(&self, ctx: &SaveContext<'_>) -> (BufWriter<File>, PathBuf) {
@ -960,7 +960,7 @@ fn save(&mut self, _: &SaveContext<'_>, analysis: &Analysis) {
pub fn process_crate<'l, 'tcx, H: SaveHandler>(
tcx: TyCtxt<'tcx>,
cratename: &str,
cratename: Symbol,
input: &'l Input,
config: Option<Config>,
mut handler: H,

View File

@ -129,10 +129,10 @@ pub struct FileIsNotWriteable<'a> {
#[derive(Diagnostic)]
#[diag(session_crate_name_does_not_match)]
pub struct CrateNameDoesNotMatch<'a> {
pub struct CrateNameDoesNotMatch {
#[primary_span]
pub span: Span,
pub s: &'a str,
pub s: Symbol,
pub name: Symbol,
}
@ -151,11 +151,11 @@ pub struct CrateNameEmpty {
#[derive(Diagnostic)]
#[diag(session_invalid_character_in_create_name)]
pub struct InvalidCharacterInCrateName<'a> {
pub struct InvalidCharacterInCrateName {
#[primary_span]
pub span: Option<Span>,
pub character: char,
pub crate_name: &'a str,
pub crate_name: Symbol,
}
#[derive(Subdiagnostic)]

View File

@ -7,14 +7,14 @@
use crate::Session;
use rustc_ast as ast;
use rustc_span::symbol::sym;
use rustc_span::Span;
use rustc_span::{Span, Symbol};
use std::path::{Path, PathBuf};
pub fn out_filename(
sess: &Session,
crate_type: CrateType,
outputs: &OutputFilenames,
crate_name: &str,
crate_name: Symbol,
) -> PathBuf {
let default_filename = filename_for_input(sess, crate_type, crate_name, outputs);
let out_filename = outputs
@ -45,9 +45,9 @@ fn is_writeable(p: &Path) -> bool {
}
}
pub fn find_crate_name(sess: &Session, attrs: &[ast::Attribute], input: &Input) -> String {
let validate = |s: String, span: Option<Span>| {
validate_crate_name(sess, &s, span);
pub fn find_crate_name(sess: &Session, attrs: &[ast::Attribute], input: &Input) -> Symbol {
let validate = |s: Symbol, span: Option<Span>| {
validate_crate_name(sess, s, span);
s
};
@ -59,38 +59,39 @@ pub fn find_crate_name(sess: &Session, attrs: &[ast::Attribute], input: &Input)
sess.find_by_name(attrs, sym::crate_name).and_then(|at| at.value_str().map(|s| (at, s)));
if let Some(ref s) = sess.opts.crate_name {
let s = Symbol::intern(s);
if let Some((attr, name)) = attr_crate_name {
if name.as_str() != s {
if name != s {
sess.emit_err(CrateNameDoesNotMatch { span: attr.span, s, name });
}
}
return validate(s.clone(), None);
return validate(s, None);
}
if let Some((attr, s)) = attr_crate_name {
return validate(s.to_string(), Some(attr.span));
return validate(s, Some(attr.span));
}
if let Input::File(ref path) = *input {
if let Some(s) = path.file_stem().and_then(|s| s.to_str()) {
if s.starts_with('-') {
sess.emit_err(CrateNameInvalid { s });
} else {
return validate(s.replace('-', "_"), None);
return validate(Symbol::intern(&s.replace('-', "_")), None);
}
}
}
"rust_out".to_string()
Symbol::intern("rust_out")
}
pub fn validate_crate_name(sess: &Session, s: &str, sp: Option<Span>) {
pub fn validate_crate_name(sess: &Session, s: Symbol, sp: Option<Span>) {
let mut err_count = 0;
{
if s.is_empty() {
err_count += 1;
sess.emit_err(CrateNameEmpty { span: sp });
}
for c in s.chars() {
for c in s.as_str().chars() {
if c.is_alphanumeric() {
continue;
}
@ -109,7 +110,7 @@ pub fn validate_crate_name(sess: &Session, s: &str, sp: Option<Span>) {
pub fn filename_for_metadata(
sess: &Session,
crate_name: &str,
crate_name: Symbol,
outputs: &OutputFilenames,
) -> PathBuf {
// If the command-line specified the path, use that directly.
@ -132,7 +133,7 @@ pub fn filename_for_metadata(
pub fn filename_for_input(
sess: &Session,
crate_type: CrateType,
crate_name: &str,
crate_name: Symbol,
outputs: &OutputFilenames,
) -> PathBuf {
let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename);

View File

@ -1,4 +1,4 @@
use crate::HashStableContext;
use crate::{HashStableContext, Symbol};
use rustc_data_structures::fingerprint::Fingerprint;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
use rustc_data_structures::AtomicRef;
@ -149,9 +149,11 @@ pub fn to_u64(self) -> u64 {
/// Computes the stable ID for a crate with the given name and
/// `-Cmetadata` arguments.
pub fn new(crate_name: &str, is_exe: bool, mut metadata: Vec<String>) -> StableCrateId {
pub fn new(crate_name: Symbol, is_exe: bool, mut metadata: Vec<String>) -> StableCrateId {
let mut hasher = StableHasher::new();
crate_name.hash(&mut hasher);
// We must hash the string text of the crate name, not the id, as the id is not stable
// across builds.
crate_name.as_str().hash(&mut hasher);
// We don't want the stable crate ID to depend on the order of
// -C metadata arguments, so sort them:

View File

@ -67,7 +67,7 @@ fn link(
if crate_type != CrateType::Rlib {
sess.fatal(&format!("Crate type is {:?}", crate_type));
}
let output_name = out_filename(sess, crate_type, &outputs, &*crate_name.as_str());
let output_name = out_filename(sess, crate_type, &outputs, crate_name);
let mut out_file = ::std::fs::File::create(output_name).unwrap();
write!(out_file, "This has been \"compiled\" successfully.").unwrap();
}