1
Fork 0

Rollup merge of #117268 - nnethercote:rustc_interface, r=oli-obk

`rustc_interface` cleanups

Particularly in and around `--cfg` and `--check-cfg` handling.

r? `@oli-obk`
This commit is contained in:
Jubilee 2023-10-28 01:07:38 -07:00 committed by GitHub
commit 48a3865218
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 76 additions and 87 deletions

View file

@ -26,7 +26,7 @@ fn track_span_parent(def_id: rustc_span::def_id::LocalDefId) {
})
}
/// This is a callback from `rustc_ast` as it cannot access the implicit state
/// This is a callback from `rustc_errors` as it cannot access the implicit state
/// in `rustc_middle` otherwise. It is used when diagnostic messages are
/// emitted and stores them in the current query, if there is one.
fn track_diagnostic(diagnostic: &mut Diagnostic, f: &mut dyn FnMut(&mut Diagnostic)) {

View file

@ -15,8 +15,10 @@ use rustc_middle::{bug, ty};
use rustc_parse::maybe_new_parser_from_source_str;
use rustc_query_impl::QueryCtxt;
use rustc_query_system::query::print_query_stack;
use rustc_session::config::{self, CheckCfg, ExpectedValues, Input, OutFileName, OutputFilenames};
use rustc_session::parse::{CrateConfig, ParseSess};
use rustc_session::config::{
self, Cfg, CheckCfg, ExpectedValues, Input, OutFileName, OutputFilenames,
};
use rustc_session::parse::ParseSess;
use rustc_session::CompilerIO;
use rustc_session::Session;
use rustc_session::{lint, EarlyErrorHandler};
@ -61,14 +63,13 @@ impl Compiler {
}
}
/// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
pub fn parse_cfgspecs(
handler: &EarlyErrorHandler,
cfgspecs: Vec<String>,
) -> FxHashSet<(String, Option<String>)> {
/// Converts strings provided as `--cfg [cfgspec]` into a `Cfg`.
pub fn parse_cfg(handler: &EarlyErrorHandler, cfgs: Vec<String>) -> Cfg<String> {
// This creates a short-lived `SessionGlobals`, containing an interner. The
// parsed values are converted from symbols to strings before exiting
// because the symbols are meaningless once the interner is gone.
rustc_span::create_default_session_if_not_set_then(move |_| {
let cfg = cfgspecs
.into_iter()
cfgs.into_iter()
.map(|s| {
let sess = ParseSess::with_silent_emitter(Some(format!(
"this error occurred on the command line: `--cfg={s}`"
@ -97,7 +98,10 @@ pub fn parse_cfgspecs(
}
MetaItemKind::NameValue(..) | MetaItemKind::Word => {
let ident = meta_item.ident().expect("multi-segment cfg key");
return (ident.name, meta_item.value_str());
return (
ident.name.to_string(),
meta_item.value_str().map(|sym| sym.to_string()),
);
}
}
}
@ -118,13 +122,14 @@ pub fn parse_cfgspecs(
error!(r#"expected `key` or `key="value"`"#);
}
})
.collect::<CrateConfig>();
cfg.into_iter().map(|(a, b)| (a.to_string(), b.map(|b| b.to_string()))).collect()
.collect::<Cfg<String>>()
})
}
/// Converts strings provided as `--check-cfg [specs]` into a `CheckCfg`.
pub fn parse_check_cfg(handler: &EarlyErrorHandler, specs: Vec<String>) -> CheckCfg {
pub fn parse_check_cfg(handler: &EarlyErrorHandler, specs: Vec<String>) -> CheckCfg<String> {
// The comment about `SessionGlobals` and symbols in `parse_cfg` above
// applies here too.
rustc_span::create_default_session_if_not_set_then(move |_| {
// If any --check-cfg is passed then exhaustive_values and exhaustive_names
// are enabled by default.
@ -357,8 +362,8 @@ pub struct Config {
pub opts: config::Options,
/// cfg! configuration in addition to the default ones
pub crate_cfg: FxHashSet<(String, Option<String>)>,
pub crate_check_cfg: CheckCfg,
pub crate_cfg: Cfg<String>,
pub crate_check_cfg: CheckCfg<String>,
pub input: Input,
pub output_dir: Option<PathBuf>,

View file

@ -1,17 +1,16 @@
#![allow(rustc::bad_opt_access)]
use crate::interface::parse_cfgspecs;
use rustc_data_structures::fx::FxHashSet;
use crate::interface::parse_cfg;
use rustc_data_structures::profiling::TimePassesFormat;
use rustc_errors::{emitter::HumanReadableErrorType, registry, ColorConfig};
use rustc_session::config::rustc_optgroups;
use rustc_session::config::Cfg;
use rustc_session::config::DebugInfo;
use rustc_session::config::Input;
use rustc_session::config::InstrumentXRay;
use rustc_session::config::LinkSelfContained;
use rustc_session::config::Polonius;
use rustc_session::config::TraitSolver;
use rustc_session::config::{build_configuration, build_session_options, to_crate_config};
use rustc_session::config::{build_configuration, build_session_options};
use rustc_session::config::{
BranchProtection, Externs, OomStrategy, OutFileName, OutputType, OutputTypes, PAuthKey, PacRet,
ProcMacroExecutionStrategy, SymbolManglingVersion, WasiExecModel,
@ -31,26 +30,18 @@ use rustc_span::FileName;
use rustc_span::SourceFileHashAlgorithm;
use rustc_target::spec::{CodeModel, LinkerFlavorCli, MergeFunctions, PanicStrategy, RelocModel};
use rustc_target::spec::{RelroLevel, SanitizerSet, SplitDebuginfo, StackProtector, TlsModel};
use std::collections::{BTreeMap, BTreeSet};
use std::num::NonZeroUsize;
use std::path::{Path, PathBuf};
use std::sync::Arc;
type CfgSpecs = FxHashSet<(String, Option<String>)>;
fn build_session_options_and_crate_config(
fn mk_session(
handler: &mut EarlyErrorHandler,
matches: getopts::Matches,
) -> (Options, CfgSpecs) {
let sessopts = build_session_options(handler, &matches);
let cfg = parse_cfgspecs(handler, matches.opt_strs("cfg"));
(sessopts, cfg)
}
fn mk_session(handler: &mut EarlyErrorHandler, matches: getopts::Matches) -> (Session, CfgSpecs) {
) -> (Session, Cfg<String>) {
let registry = registry::Registry::new(&[]);
let (sessopts, cfg) = build_session_options_and_crate_config(handler, matches);
let sessopts = build_session_options(handler, &matches);
let cfg = parse_cfg(handler, matches.opt_strs("cfg"));
let temps_dir = sessopts.unstable_opts.temps_dir.as_deref().map(PathBuf::from);
let io = CompilerIO {
input: Input::Str { name: FileName::Custom(String::new()), input: String::new() },
@ -141,7 +132,7 @@ fn test_switch_implies_cfg_test() {
let matches = optgroups().parse(&["--test".to_string()]).unwrap();
let mut handler = EarlyErrorHandler::new(ErrorOutputType::default());
let (sess, cfg) = mk_session(&mut handler, matches);
let cfg = build_configuration(&sess, to_crate_config(cfg));
let cfg = build_configuration(&sess, cfg);
assert!(cfg.contains(&(sym::test, None)));
});
}
@ -153,7 +144,7 @@ fn test_switch_implies_cfg_test_unless_cfg_test() {
let matches = optgroups().parse(&["--test".to_string(), "--cfg=test".to_string()]).unwrap();
let mut handler = EarlyErrorHandler::new(ErrorOutputType::default());
let (sess, cfg) = mk_session(&mut handler, matches);
let cfg = build_configuration(&sess, to_crate_config(cfg));
let cfg = build_configuration(&sess, cfg);
let mut test_items = cfg.iter().filter(|&&(name, _)| name == sym::test);
assert!(test_items.next().is_some());
assert!(test_items.next().is_none());
@ -879,6 +870,6 @@ fn test_edition_parsing() {
let mut handler = EarlyErrorHandler::new(ErrorOutputType::default());
let matches = optgroups().parse(&["--edition=2018".to_string()]).unwrap();
let (sessopts, _) = build_session_options_and_crate_config(&mut handler, matches);
let sessopts = build_session_options(&mut handler, &matches);
assert!(sessopts.edition == Edition::Edition2018)
}

View file

@ -3,18 +3,17 @@ use info;
use libloading::Library;
use rustc_ast as ast;
use rustc_codegen_ssa::traits::CodegenBackend;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::fx::FxHashMap;
#[cfg(parallel_compiler)]
use rustc_data_structures::sync;
use rustc_errors::registry::Registry;
use rustc_parse::validate_attr;
use rustc_session as session;
use rustc_session::config::CheckCfg;
use rustc_session::config::{self, CrateType};
use rustc_session::config::{OutFileName, OutputFilenames, OutputTypes};
use rustc_session::config::{
self, Cfg, CheckCfg, CrateType, OutFileName, OutputFilenames, OutputTypes,
};
use rustc_session::filesearch::sysroot_candidates;
use rustc_session::lint::{self, BuiltinLintDiagnostics, LintBuffer};
use rustc_session::parse::CrateConfig;
use rustc_session::{filesearch, output, Session};
use rustc_span::edit_distance::find_best_match_for_name;
use rustc_span::edition::Edition;
@ -38,7 +37,7 @@ pub type MakeBackendFn = fn() -> Box<dyn CodegenBackend>;
/// This is performed by checking whether a set of permitted features
/// is available on the target machine, by querying the codegen backend.
pub fn add_configuration(
cfg: &mut CrateConfig,
cfg: &mut Cfg<Symbol>,
sess: &mut Session,
codegen_backend: &dyn CodegenBackend,
) {
@ -60,8 +59,8 @@ pub fn add_configuration(
pub fn create_session(
handler: &EarlyErrorHandler,
sopts: config::Options,
cfg: FxHashSet<(String, Option<String>)>,
check_cfg: CheckCfg,
cfg: Cfg<String>,
check_cfg: CheckCfg<String>,
locale_resources: &'static [&'static str],
file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>,
io: CompilerIO,
@ -121,12 +120,13 @@ pub fn create_session(
codegen_backend.init(&sess);
let mut cfg = config::build_configuration(&sess, config::to_crate_config(cfg));
let mut cfg = config::build_configuration(&sess, cfg);
add_configuration(&mut cfg, &mut sess, &*codegen_backend);
let mut check_cfg = config::to_crate_check_config(check_cfg);
let mut check_cfg = check_cfg.intern();
check_cfg.fill_well_known(&sess.target);
// These configs use symbols, rather than strings.
sess.parse_sess.config = cfg;
sess.parse_sess.check_config = check_cfg;