Skip to content

Commit dff7d51

Browse files
authored
Rollup merge of #93936 - bjorn3:simplifications2, r=cjgillot
Couple of driver cleanups * Remove the `RustcDefaultCalls` struct, which hasn't been necessary since the introduction of `rustc_interface`. * Move the `setup_callbacks` call around for a tiny code deduplication. * Remove the `SPAN_DEBUG` global as it isn't actually necessary.
2 parents 2b7f3ee + f45ba82 commit dff7d51

File tree

7 files changed

+158
-199
lines changed

7 files changed

+158
-199
lines changed

compiler/rustc_driver/src/lib.rs

+138-151
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,7 @@ fn run_compiler(
263263
describe_lints(compiler.session(), &lint_store, registered_lints);
264264
return;
265265
}
266-
let should_stop = RustcDefaultCalls::print_crate_info(
266+
let should_stop = print_crate_info(
267267
&***compiler.codegen_backend(),
268268
compiler.session(),
269269
None,
@@ -292,7 +292,7 @@ fn run_compiler(
292292

293293
interface::run_compiler(config, |compiler| {
294294
let sess = compiler.session();
295-
let should_stop = RustcDefaultCalls::print_crate_info(
295+
let should_stop = print_crate_info(
296296
&***compiler.codegen_backend(),
297297
sess,
298298
Some(compiler.input()),
@@ -301,13 +301,9 @@ fn run_compiler(
301301
compiler.temps_dir(),
302302
)
303303
.and_then(|| {
304-
RustcDefaultCalls::list_metadata(
305-
sess,
306-
&*compiler.codegen_backend().metadata_loader(),
307-
compiler.input(),
308-
)
304+
list_metadata(sess, &*compiler.codegen_backend().metadata_loader(), compiler.input())
309305
})
310-
.and_then(|| RustcDefaultCalls::try_process_rlink(sess, compiler));
306+
.and_then(|| try_process_rlink(sess, compiler));
311307

312308
if should_stop == Compilation::Stop {
313309
return sess.compile_status();
@@ -512,10 +508,6 @@ impl Compilation {
512508
}
513509
}
514510

515-
/// CompilerCalls instance for a regular rustc build.
516-
#[derive(Copy, Clone)]
517-
pub struct RustcDefaultCalls;
518-
519511
fn handle_explain(registry: Registry, code: &str, output: ErrorOutputType) {
520512
let upper_cased_code = code.to_ascii_uppercase();
521513
let normalised = if upper_cased_code.starts_with('E') {
@@ -588,162 +580,157 @@ fn show_content_with_pager(content: &str) {
588580
}
589581
}
590582

591-
impl RustcDefaultCalls {
592-
pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Compilation {
593-
if sess.opts.debugging_opts.link_only {
594-
if let Input::File(file) = compiler.input() {
595-
// FIXME: #![crate_type] and #![crate_name] support not implemented yet
596-
sess.init_crate_types(collect_crate_types(sess, &[]));
597-
let outputs = compiler.build_output_filenames(sess, &[]);
598-
let rlink_data = fs::read(file).unwrap_or_else(|err| {
599-
sess.fatal(&format!("failed to read rlink file: {}", err));
600-
});
601-
let mut decoder = rustc_serialize::opaque::Decoder::new(&rlink_data, 0);
602-
let codegen_results: CodegenResults =
603-
rustc_serialize::Decodable::decode(&mut decoder);
604-
let result = compiler.codegen_backend().link(sess, codegen_results, &outputs);
605-
abort_on_err(result, sess);
606-
} else {
607-
sess.fatal("rlink must be a file")
608-
}
609-
Compilation::Stop
583+
pub fn try_process_rlink(sess: &Session, compiler: &interface::Compiler) -> Compilation {
584+
if sess.opts.debugging_opts.link_only {
585+
if let Input::File(file) = compiler.input() {
586+
// FIXME: #![crate_type] and #![crate_name] support not implemented yet
587+
sess.init_crate_types(collect_crate_types(sess, &[]));
588+
let outputs = compiler.build_output_filenames(sess, &[]);
589+
let rlink_data = fs::read(file).unwrap_or_else(|err| {
590+
sess.fatal(&format!("failed to read rlink file: {}", err));
591+
});
592+
let mut decoder = rustc_serialize::opaque::Decoder::new(&rlink_data, 0);
593+
let codegen_results: CodegenResults = rustc_serialize::Decodable::decode(&mut decoder);
594+
let result = compiler.codegen_backend().link(sess, codegen_results, &outputs);
595+
abort_on_err(result, sess);
610596
} else {
611-
Compilation::Continue
597+
sess.fatal("rlink must be a file")
612598
}
599+
Compilation::Stop
600+
} else {
601+
Compilation::Continue
613602
}
603+
}
614604

615-
pub fn list_metadata(
616-
sess: &Session,
617-
metadata_loader: &dyn MetadataLoader,
618-
input: &Input,
619-
) -> Compilation {
620-
if sess.opts.debugging_opts.ls {
621-
match *input {
622-
Input::File(ref ifile) => {
623-
let path = &(*ifile);
624-
let mut v = Vec::new();
625-
locator::list_file_metadata(&sess.target, path, metadata_loader, &mut v)
626-
.unwrap();
627-
println!("{}", String::from_utf8(v).unwrap());
628-
}
629-
Input::Str { .. } => {
630-
early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
631-
}
605+
pub fn list_metadata(
606+
sess: &Session,
607+
metadata_loader: &dyn MetadataLoader,
608+
input: &Input,
609+
) -> Compilation {
610+
if sess.opts.debugging_opts.ls {
611+
match *input {
612+
Input::File(ref ifile) => {
613+
let path = &(*ifile);
614+
let mut v = Vec::new();
615+
locator::list_file_metadata(&sess.target, path, metadata_loader, &mut v).unwrap();
616+
println!("{}", String::from_utf8(v).unwrap());
617+
}
618+
Input::Str { .. } => {
619+
early_error(ErrorOutputType::default(), "cannot list metadata for stdin");
632620
}
633-
return Compilation::Stop;
634621
}
635-
636-
Compilation::Continue
622+
return Compilation::Stop;
637623
}
638624

639-
fn print_crate_info(
640-
codegen_backend: &dyn CodegenBackend,
641-
sess: &Session,
642-
input: Option<&Input>,
643-
odir: &Option<PathBuf>,
644-
ofile: &Option<PathBuf>,
645-
temps_dir: &Option<PathBuf>,
646-
) -> Compilation {
647-
use rustc_session::config::PrintRequest::*;
648-
// NativeStaticLibs and LinkArgs are special - printed during linking
649-
// (empty iterator returns true)
650-
if sess.opts.prints.iter().all(|&p| p == NativeStaticLibs || p == LinkArgs) {
651-
return Compilation::Continue;
652-
}
625+
Compilation::Continue
626+
}
653627

654-
let attrs = match input {
655-
None => None,
656-
Some(input) => {
657-
let result = parse_crate_attrs(sess, input);
658-
match result {
659-
Ok(attrs) => Some(attrs),
660-
Err(mut parse_error) => {
661-
parse_error.emit();
662-
return Compilation::Stop;
663-
}
628+
fn print_crate_info(
629+
codegen_backend: &dyn CodegenBackend,
630+
sess: &Session,
631+
input: Option<&Input>,
632+
odir: &Option<PathBuf>,
633+
ofile: &Option<PathBuf>,
634+
temps_dir: &Option<PathBuf>,
635+
) -> Compilation {
636+
use rustc_session::config::PrintRequest::*;
637+
// NativeStaticLibs and LinkArgs are special - printed during linking
638+
// (empty iterator returns true)
639+
if sess.opts.prints.iter().all(|&p| p == NativeStaticLibs || p == LinkArgs) {
640+
return Compilation::Continue;
641+
}
642+
643+
let attrs = match input {
644+
None => None,
645+
Some(input) => {
646+
let result = parse_crate_attrs(sess, input);
647+
match result {
648+
Ok(attrs) => Some(attrs),
649+
Err(mut parse_error) => {
650+
parse_error.emit();
651+
return Compilation::Stop;
664652
}
665653
}
666-
};
667-
for req in &sess.opts.prints {
668-
match *req {
669-
TargetList => {
670-
let mut targets =
671-
rustc_target::spec::TARGETS.iter().copied().collect::<Vec<_>>();
672-
targets.sort_unstable();
673-
println!("{}", targets.join("\n"));
674-
}
675-
Sysroot => println!("{}", sess.sysroot.display()),
676-
TargetLibdir => println!("{}", sess.target_tlib_path.dir.display()),
677-
TargetSpec => println!("{}", sess.target.to_json().pretty()),
678-
FileNames | CrateName => {
679-
let input = input.unwrap_or_else(|| {
680-
early_error(ErrorOutputType::default(), "no input file provided")
681-
});
682-
let attrs = attrs.as_ref().unwrap();
683-
let t_outputs = rustc_interface::util::build_output_filenames(
684-
input, odir, ofile, temps_dir, attrs, sess,
685-
);
686-
let id = rustc_session::output::find_crate_name(sess, attrs, input);
687-
if *req == PrintRequest::CrateName {
688-
println!("{}", id);
689-
continue;
690-
}
691-
let crate_types = collect_crate_types(sess, attrs);
692-
for &style in &crate_types {
693-
let fname =
694-
rustc_session::output::filename_for_input(sess, style, &id, &t_outputs);
695-
println!("{}", fname.file_name().unwrap().to_string_lossy());
696-
}
654+
}
655+
};
656+
for req in &sess.opts.prints {
657+
match *req {
658+
TargetList => {
659+
let mut targets = rustc_target::spec::TARGETS.iter().copied().collect::<Vec<_>>();
660+
targets.sort_unstable();
661+
println!("{}", targets.join("\n"));
662+
}
663+
Sysroot => println!("{}", sess.sysroot.display()),
664+
TargetLibdir => println!("{}", sess.target_tlib_path.dir.display()),
665+
TargetSpec => println!("{}", sess.target.to_json().pretty()),
666+
FileNames | CrateName => {
667+
let input = input.unwrap_or_else(|| {
668+
early_error(ErrorOutputType::default(), "no input file provided")
669+
});
670+
let attrs = attrs.as_ref().unwrap();
671+
let t_outputs = rustc_interface::util::build_output_filenames(
672+
input, odir, ofile, temps_dir, attrs, sess,
673+
);
674+
let id = rustc_session::output::find_crate_name(sess, attrs, input);
675+
if *req == PrintRequest::CrateName {
676+
println!("{}", id);
677+
continue;
697678
}
698-
Cfg => {
699-
let mut cfgs = sess
700-
.parse_sess
701-
.config
702-
.iter()
703-
.filter_map(|&(name, value)| {
704-
// Note that crt-static is a specially recognized cfg
705-
// directive that's printed out here as part of
706-
// rust-lang/rust#37406, but in general the
707-
// `target_feature` cfg is gated under
708-
// rust-lang/rust#29717. For now this is just
709-
// specifically allowing the crt-static cfg and that's
710-
// it, this is intended to get into Cargo and then go
711-
// through to build scripts.
712-
if (name != sym::target_feature || value != Some(sym::crt_dash_static))
713-
&& !sess.is_nightly_build()
714-
&& find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
715-
{
716-
return None;
717-
}
718-
719-
if let Some(value) = value {
720-
Some(format!("{}=\"{}\"", name, value))
721-
} else {
722-
Some(name.to_string())
723-
}
724-
})
725-
.collect::<Vec<String>>();
726-
727-
cfgs.sort();
728-
for cfg in cfgs {
729-
println!("{}", cfg);
730-
}
679+
let crate_types = collect_crate_types(sess, attrs);
680+
for &style in &crate_types {
681+
let fname =
682+
rustc_session::output::filename_for_input(sess, style, &id, &t_outputs);
683+
println!("{}", fname.file_name().unwrap().to_string_lossy());
731684
}
732-
RelocationModels
733-
| CodeModels
734-
| TlsModels
735-
| TargetCPUs
736-
| StackProtectorStrategies
737-
| TargetFeatures => {
738-
codegen_backend.print(*req, sess);
685+
}
686+
Cfg => {
687+
let mut cfgs = sess
688+
.parse_sess
689+
.config
690+
.iter()
691+
.filter_map(|&(name, value)| {
692+
// Note that crt-static is a specially recognized cfg
693+
// directive that's printed out here as part of
694+
// rust-lang/rust#37406, but in general the
695+
// `target_feature` cfg is gated under
696+
// rust-lang/rust#29717. For now this is just
697+
// specifically allowing the crt-static cfg and that's
698+
// it, this is intended to get into Cargo and then go
699+
// through to build scripts.
700+
if (name != sym::target_feature || value != Some(sym::crt_dash_static))
701+
&& !sess.is_nightly_build()
702+
&& find_gated_cfg(|cfg_sym| cfg_sym == name).is_some()
703+
{
704+
return None;
705+
}
706+
707+
if let Some(value) = value {
708+
Some(format!("{}=\"{}\"", name, value))
709+
} else {
710+
Some(name.to_string())
711+
}
712+
})
713+
.collect::<Vec<String>>();
714+
715+
cfgs.sort();
716+
for cfg in cfgs {
717+
println!("{}", cfg);
739718
}
740-
// Any output here interferes with Cargo's parsing of other printed output
741-
NativeStaticLibs => {}
742-
LinkArgs => {}
743719
}
720+
RelocationModels
721+
| CodeModels
722+
| TlsModels
723+
| TargetCPUs
724+
| StackProtectorStrategies
725+
| TargetFeatures => {
726+
codegen_backend.print(*req, sess);
727+
}
728+
// Any output here interferes with Cargo's parsing of other printed output
729+
NativeStaticLibs => {}
730+
LinkArgs => {}
744731
}
745-
Compilation::Stop
746732
}
733+
Compilation::Stop
747734
}
748735

749736
/// Prints version information

compiler/rustc_interface/src/callbacks.rs

+1-14
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
//! `rustc_data_structures::AtomicRef` type, which allows us to setup a global
55
//! static which can then be set in this file at program startup.
66
//!
7-
//! See `SPAN_DEBUG` for an example of how to set things up.
7+
//! See `SPAN_TRACK` for an example of how to set things up.
88
//!
99
//! The functions in this file should fall back to the default set in their
1010
//! origin crate when the `TyCtxt` is not present in TLS.
@@ -13,18 +13,6 @@ use rustc_errors::{Diagnostic, TRACK_DIAGNOSTICS};
1313
use rustc_middle::ty::tls;
1414
use std::fmt;
1515

16-
/// This is a callback from `rustc_ast` as it cannot access the implicit state
17-
/// in `rustc_middle` otherwise.
18-
fn span_debug(span: rustc_span::Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19-
tls::with_opt(|tcx| {
20-
if let Some(tcx) = tcx {
21-
rustc_span::debug_with_source_map(span, f, tcx.sess.source_map())
22-
} else {
23-
rustc_span::default_span_debug(span, f)
24-
}
25-
})
26-
}
27-
2816
fn track_span_parent(def_id: rustc_span::def_id::LocalDefId) {
2917
tls::with_opt(|tcx| {
3018
if let Some(tcx) = tcx {
@@ -65,7 +53,6 @@ fn def_id_debug(def_id: rustc_hir::def_id::DefId, f: &mut fmt::Formatter<'_>) ->
6553
/// Sets up the callbacks in prior crates which we want to refer to the
6654
/// TyCtxt in.
6755
pub fn setup_callbacks() {
68-
rustc_span::SPAN_DEBUG.swap(&(span_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
6956
rustc_span::SPAN_TRACK.swap(&(track_span_parent as fn(_)));
7057
rustc_hir::def_id::DEF_ID_DEBUG.swap(&(def_id_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
7158
TRACK_DIAGNOSTICS.swap(&(track_diagnostic as fn(&_)));

compiler/rustc_interface/src/interface.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,8 @@ pub struct Config {
186186
}
187187

188188
pub fn create_compiler_and_run<R>(config: Config, f: impl FnOnce(&Compiler) -> R) -> R {
189+
crate::callbacks::setup_callbacks();
190+
189191
let registry = &config.registry;
190192
let (mut sess, codegen_backend) = util::create_session(
191193
config.opts,
@@ -238,7 +240,7 @@ pub fn create_compiler_and_run<R>(config: Config, f: impl FnOnce(&Compiler) -> R
238240
pub fn run_compiler<R: Send>(mut config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R {
239241
tracing::trace!("run_compiler");
240242
let stderr = config.stderr.take();
241-
util::setup_callbacks_and_run_in_thread_pool_with_globals(
243+
util::run_in_thread_pool_with_globals(
242244
config.opts.edition,
243245
config.opts.debugging_opts.threads,
244246
&stderr,

0 commit comments

Comments
 (0)