Move four fields from ParseSess to Session.

`ParseSess` is separate from, but sits within, `Session`. The separation
is because there are some places (e.g. `Parser` methods) where
`ParseSess` is available but `Session` is not.

However, `ParseSess` has four fields that are only accessed from places
where `Session` is also available. This commit moves those fields to
`Session`. This means that `ParseSess` only contains the fields it
genuinely needs, and various `sess.psess.foo` occurrences are reduced to
`sess.foo`.
This commit is contained in:
Nicholas Nethercote
2026-04-28 08:58:57 +10:00
parent b317977ee3
commit 01e933f888
11 changed files with 59 additions and 62 deletions
@@ -222,7 +222,7 @@ pub(crate) fn parse_name_value<S: Stage>(
}
};
match cx.sess.psess.check_config.expecteds.get(&name) {
match cx.sess.check_config.expecteds.get(&name) {
Some(ExpectedValues::Some(values)) if !values.contains(&value.map(|(v, _)| v)) => cx
.emit_lint_with_sess(
UNEXPECTED_CFGS,
@@ -232,7 +232,7 @@ pub(crate) fn parse_name_value<S: Stage>(
},
span,
),
None if cx.sess.psess.check_config.exhaustive_names => cx.emit_lint_with_sess(
None if cx.sess.check_config.exhaustive_names => cx.emit_lint_with_sess(
UNEXPECTED_CFGS,
move |dcx, level, sess| {
check_cfg::unexpected_cfg_name(sess, (name, name_span), value).into_diag(dcx, level)
@@ -280,7 +280,7 @@ pub fn eval_config_entry(sess: &Session, cfg_entry: &CfgEntry) -> EvalConfigResu
}
}
CfgEntry::NameValue { name, value, span } => {
if sess.psess.config.contains(&(*name, *value)) {
if sess.config.contains(&(*name, *value)) {
EvalConfigResult::True
} else {
EvalConfigResult::False { reason: cfg_entry.clone(), reason_span: *span }
@@ -25,9 +25,8 @@ fn sort_and_truncate_possibilities(
} else {
match filter_well_known_names {
FilterWellKnownNames::Yes => {
possibilities.retain(|cfg_name| {
!sess.psess.check_config.well_known_names.contains(cfg_name)
});
possibilities
.retain(|cfg_name| !sess.check_config.well_known_names.contains(cfg_name));
}
FilterWellKnownNames::No => {}
};
@@ -105,13 +104,12 @@ pub(crate) fn unexpected_cfg_name(
value: Option<(Symbol, Span)>,
) -> errors::UnexpectedCfgName {
#[allow(rustc::potential_query_instability)]
let possibilities: Vec<Symbol> = sess.psess.check_config.expecteds.keys().copied().collect();
let possibilities: Vec<Symbol> = sess.check_config.expecteds.keys().copied().collect();
let mut names_possibilities: Vec<_> = if value.is_none() {
// We later sort and display all the possibilities, so the order here does not matter.
#[allow(rustc::potential_query_instability)]
sess.psess
.check_config
sess.check_config
.expecteds
.iter()
.filter_map(|(k, v)| match v {
@@ -167,7 +165,7 @@ pub(crate) fn unexpected_cfg_name(
is_feature_cfg |= best_match == sym::feature;
if let Some(ExpectedValues::Some(best_match_values)) =
sess.psess.check_config.expecteds.get(&best_match)
sess.check_config.expecteds.get(&best_match)
{
// We will soon sort, so the initial order does not matter.
#[allow(rustc::potential_query_instability)]
@@ -285,7 +283,7 @@ pub(crate) fn unexpected_cfg_value(
(name, name_span): (Symbol, Span),
value: Option<(Symbol, Span)>,
) -> errors::UnexpectedCfgValue {
let Some(ExpectedValues::Some(values)) = &sess.psess.check_config.expecteds.get(&name) else {
let Some(ExpectedValues::Some(values)) = &sess.check_config.expecteds.get(&name) else {
panic!(
"it shouldn't be possible to have a diagnostic on a value whose name is not in values"
);
@@ -305,7 +303,7 @@ pub(crate) fn unexpected_cfg_value(
let is_from_external_macro = name_span.in_external_macro(sess.source_map());
let code_sugg = if let Some((value, _)) = value
&& sess.psess.check_config.well_known_names.contains(&name)
&& sess.check_config.well_known_names.contains(&name)
&& let valid_names = possible_well_known_names_for_cfg_value(sess, value)
&& !valid_names.is_empty()
{
@@ -378,12 +376,12 @@ pub(crate) fn unexpected_cfg_value(
// We don't want to encourage people to add values to a well-known names, as these are
// defined by rustc/Rust itself. Users can still do this if they wish, but should not be
// encouraged to do so.
let can_suggest_adding_value = !sess.psess.check_config.well_known_names.contains(&name)
let can_suggest_adding_value = !sess.check_config.well_known_names.contains(&name)
// Except when working on rustc or the standard library itself, in which case we want to
// suggest adding these cfgs to the "normal" place because of bootstrapping reasons. As a
// basic heuristic, we use the "cheat" unstable feature enable method and the
// non-ui-testing enabled option.
|| (matches!(sess.psess.unstable_features, rustc_feature::UnstableFeatures::Cheat)
|| (matches!(sess.unstable_features, rustc_feature::UnstableFeatures::Cheat)
&& !sess.opts.unstable_opts.ui_testing);
let inst = |escape_quotes| {
@@ -429,13 +427,11 @@ pub(crate) fn unexpected_cfg_value(
fn possible_well_known_names_for_cfg_value(sess: &Session, value: Symbol) -> Vec<Symbol> {
#[allow(rustc::potential_query_instability)]
let mut names = sess
.psess
.check_config
.well_known_names
.iter()
.filter(|name| {
sess.psess
.check_config
sess.check_config
.expecteds
.get(*name)
.map(|expected_values| expected_values.contains(&Some(value)))
@@ -171,7 +171,7 @@ impl<'tcx> AssertModuleSource<'tcx> {
/// Scan for a `cfg="foo"` attribute and check whether we have a
/// cfg flag called `foo`.
fn check_config(&self, value: Symbol) -> bool {
let config = &self.tcx.sess.psess.config;
let config = &self.tcx.sess.config;
debug!("check_config(config={:?}, value={:?})", config, value);
if config.iter().any(|&(name, _)| name == value) {
debug!("check_config: matched");
+2 -5
View File
@@ -734,7 +734,6 @@ fn print_crate_info(
}
Cfg => {
let mut cfgs = sess
.psess
.config
.iter()
.filter_map(|&(name, value)| {
@@ -763,7 +762,7 @@ fn print_crate_info(
// INSTABILITY: We are sorting the output below.
#[allow(rustc::potential_query_instability)]
for (name, expected_values) in &sess.psess.check_config.expecteds {
for (name, expected_values) in &sess.check_config.expecteds {
use crate::config::ExpectedValues;
match expected_values {
ExpectedValues::Any => {
@@ -791,9 +790,7 @@ fn print_crate_info(
}
check_cfgs.sort_unstable();
if !sess.psess.check_config.exhaustive_names
&& sess.psess.check_config.exhaustive_values
{
if !sess.check_config.exhaustive_names && sess.check_config.exhaustive_values {
println_info!("cfg(any())");
}
for check_cfg in check_cfgs {
@@ -15,6 +15,7 @@ use rustc_proc_macro::bridge::{
DelimSpan, Diagnostic, ExpnGlobals, Group, Ident, LitKind, Literal, Punct, TokenTree, server,
};
use rustc_proc_macro::{Delimiter, Level};
use rustc_session::Session;
use rustc_session::parse::ParseSess;
use rustc_span::def_id::CrateNum;
use rustc_span::{BytePos, FileName, Pos, Span, Symbol, sym};
@@ -440,6 +441,10 @@ impl<'a, 'b> Rustc<'a, 'b> {
}
}
fn sess(&self) -> &Session {
&self.ecx.sess
}
fn psess(&self) -> &ParseSess {
self.ecx.psess()
}
@@ -825,7 +830,7 @@ impl server::Server for Rustc<'_, '_> {
/// since we've loaded `my_proc_macro` from disk in order to execute it).
/// In this way, we have obtained a span pointing into `my_proc_macro`
fn span_save_span(&mut self, span: Self::Span) -> usize {
self.psess().save_proc_macro_span(span)
self.sess().save_proc_macro_span(span)
}
fn span_recover_proc_macro_span(&mut self, id: usize) -> Self::Span {
@@ -183,12 +183,7 @@ impl<'tcx> CleanVisitor<'tcx> {
item_id: LocalDefId,
attr: &RustcCleanAttribute,
) -> Option<Assertion> {
self.tcx
.sess
.psess
.config
.contains(&(attr.cfg, None))
.then(|| self.assertion_auto(item_id, attr))
self.tcx.sess.config.contains(&(attr.cfg, None)).then(|| self.assertion_auto(item_id, attr))
}
/// Gets the "auto" assertion on pre-validated attr, along with the `except` labels.
@@ -406,7 +401,7 @@ struct FindAllAttrs<'tcx> {
impl<'tcx> FindAllAttrs<'tcx> {
fn is_active_attr(&self, attr: &RustcCleanAttribute) -> bool {
self.tcx.sess.psess.config.contains(&(attr.cfg, None))
self.tcx.sess.config.contains(&(attr.cfg, None))
}
fn report_unchecked_attrs(&self, mut checked_attrs: FxHashSet<Span>) {
+2 -2
View File
@@ -452,11 +452,11 @@ pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Se
let cfg = parse_cfg(sess.dcx(), config.crate_cfg);
let mut cfg = config::build_configuration(&sess, cfg);
util::add_configuration(&mut cfg, &mut sess, &*codegen_backend);
sess.psess.config = cfg;
sess.config = cfg;
let mut check_cfg = parse_check_cfg(sess.dcx(), config.crate_check_cfg);
check_cfg.fill_well_known(&sess.target);
sess.psess.check_config = check_cfg;
sess.check_config = check_cfg;
if let Some(psess_created) = config.psess_created {
psess_created(&mut sess.psess);
@@ -309,7 +309,7 @@ fn add_library(
// This error is probably a little obscure, but I imagine that it
// can be refined over time.
if link2 != link || link == RequireStatic {
let linking_to_rustc_driver = tcx.sess.psess.unstable_features.is_nightly_build()
let linking_to_rustc_driver = tcx.sess.unstable_features.is_nightly_build()
&& tcx.crates(()).iter().any(|&cnum| tcx.crate_name(cnum) == sym::rustc_driver);
tcx.dcx().emit_err(CrateDepMultiple {
crate_name: tcx.crate_name(cnum),
+1 -1
View File
@@ -1984,7 +1984,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
let stability = tcx.lookup_stability(CRATE_DEF_ID);
let macros =
self.lazy_array(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index));
for (i, span) in self.tcx.sess.psess.proc_macro_quoted_spans() {
for (i, span) in self.tcx.sess.proc_macro_quoted_spans() {
let span = self.lazy(span);
self.tables.proc_macro_quoted_spans.set_some(i, span);
}
+3 -24
View File
@@ -14,14 +14,13 @@ use rustc_errors::{
BufferedEarlyLint, ColorConfig, DecorateDiagCompat, Diag, DiagCtxt, DiagCtxtHandle,
DiagMessage, EmissionGuarantee, Level, MultiSpan, StashKey,
};
use rustc_feature::{GateIssue, UnstableFeatures, find_feature_issue};
use rustc_feature::{GateIssue, find_feature_issue};
use rustc_span::edition::Edition;
use rustc_span::hygiene::ExpnId;
use rustc_span::source_map::{FilePathMapping, SourceMap};
use rustc_span::{Span, Symbol, sym};
use crate::Session;
use crate::config::{Cfg, CheckCfg};
use crate::errors::{
CliFeatureDiagnosticHelp, FeatureDiagnosticForIssue, FeatureDiagnosticHelp,
FeatureDiagnosticSuggestion, FeatureGateError, SuggestUpgradeCompiler,
@@ -182,7 +181,7 @@ pub fn add_feature_diagnostics_for_issue<G: EmissionGuarantee>(
}
// #23973: do not suggest `#![feature(...)]` if we are in beta/stable
if sess.psess.unstable_features.is_nightly_build() {
if sess.unstable_features.is_nightly_build() {
if feature_from_cli {
err.subdiagnostic(CliFeatureDiagnosticHelp { feature });
} else if let Some(span) = inject_span {
@@ -226,7 +225,7 @@ pub fn feature_err_unstable_feature_bound(
let mut err = sess.dcx().create_err(FeatureGateError { span, explain: explain.into() });
// #23973: do not suggest `#![feature(...)]` if we are in beta/stable
if sess.psess.unstable_features.is_nightly_build() {
if sess.unstable_features.is_nightly_build() {
err.subdiagnostic(FeatureDiagnosticHelp { feature });
if feature == sym::rustc_attrs {
@@ -245,9 +244,6 @@ pub fn feature_err_unstable_feature_bound(
/// Info about a parsing session.
pub struct ParseSess {
dcx: DiagCtxt,
pub unstable_features: UnstableFeatures,
pub config: Cfg,
pub check_config: CheckCfg,
pub edition: Edition,
/// Places where raw identifiers were used. This is used to avoid complaining about idents
/// clashing with keywords in new editions.
@@ -264,9 +260,6 @@ pub struct ParseSess {
pub ambiguous_block_expr_parse: Lock<FxIndexMap<Span, Span>>,
pub gated_spans: GatedSpans,
pub symbol_gallery: SymbolGallery,
/// Spans passed to `proc_macro::quote_span`. Each span has a numerical
/// identifier represented by its position in the vector.
proc_macro_quoted_spans: AppendOnlyVec<Span>,
/// Used to generate new `AttrId`s. Every `AttrId` is unique.
pub attr_id_generator: AttrIdGenerator,
}
@@ -286,9 +279,6 @@ impl ParseSess {
pub fn with_dcx(dcx: DiagCtxt, source_map: Arc<SourceMap>) -> Self {
Self {
dcx,
unstable_features: UnstableFeatures::from_environment(None),
config: Cfg::default(),
check_config: CheckCfg::default(),
edition: ExpnId::root().expn_data().edition,
raw_identifier_spans: Default::default(),
bad_unicode_identifiers: Lock::new(Default::default()),
@@ -297,7 +287,6 @@ impl ParseSess {
ambiguous_block_expr_parse: Lock::new(Default::default()),
gated_spans: GatedSpans::default(),
symbol_gallery: SymbolGallery::default(),
proc_macro_quoted_spans: Default::default(),
attr_id_generator: AttrIdGenerator::new(),
}
}
@@ -385,16 +374,6 @@ impl ParseSess {
});
}
pub fn save_proc_macro_span(&self, span: Span) -> usize {
self.proc_macro_quoted_spans.push(span)
}
pub fn proc_macro_quoted_spans(&self) -> impl Iterator<Item = (usize, Span)> {
// This is equivalent to `.iter().copied().enumerate()`, but that isn't possible for
// AppendOnlyVec, so we resort to this scheme.
self.proc_macro_quoted_spans.iter_enumerated()
}
pub fn dcx(&self) -> DiagCtxtHandle<'_> {
self.dcx.handle()
}
+28 -3
View File
@@ -10,7 +10,9 @@ use rustc_data_structures::base_n::{CASE_INSENSITIVE, ToBaseN};
use rustc_data_structures::flock;
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
use rustc_data_structures::profiling::{SelfProfiler, SelfProfilerRef};
use rustc_data_structures::sync::{DynSend, DynSync, Lock, MappedReadGuard, ReadGuard, RwLock};
use rustc_data_structures::sync::{
AppendOnlyVec, DynSend, DynSync, Lock, MappedReadGuard, ReadGuard, RwLock,
};
use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter;
use rustc_errors::codes::*;
use rustc_errors::emitter::{DynEmitter, HumanReadableErrorType, OutputTheme, stderr_destination};
@@ -20,6 +22,7 @@ use rustc_errors::{
Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, FatalAbort,
TerminalUrl,
};
use rustc_feature::UnstableFeatures;
use rustc_hir::limit::Limit;
use rustc_macros::HashStable_Generic;
pub use rustc_span::def_id::StableCrateId;
@@ -36,8 +39,9 @@ use rustc_target::spec::{
use crate::code_stats::CodeStats;
pub use crate::code_stats::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo};
use crate::config::{
self, CoverageLevel, CoverageOptions, CrateType, DebugInfo, ErrorOutputType, FunctionReturn,
Input, InstrumentCoverage, OptLevel, OutFileName, OutputType, SwitchWithOptPath,
self, Cfg, CheckCfg, CoverageLevel, CoverageOptions, CrateType, DebugInfo, ErrorOutputType,
FunctionReturn, Input, InstrumentCoverage, OptLevel, OutFileName, OutputType,
SwitchWithOptPath,
};
use crate::filesearch::FileSearch;
use crate::lint::LintId;
@@ -91,6 +95,13 @@ pub struct Session {
pub opts: config::Options,
pub target_tlib_path: Arc<SearchPath>,
pub psess: ParseSess,
pub unstable_features: UnstableFeatures,
pub config: Cfg,
pub check_config: CheckCfg,
/// Spans passed to `proc_macro::quote_span`. Each span has a numerical
/// identifier represented by its position in the vector.
proc_macro_quoted_spans: AppendOnlyVec<Span>,
/// Input, input file path and output file path to this compilation process.
pub io: CompilerIO,
@@ -302,6 +313,16 @@ impl Session {
self.psess.source_map()
}
pub fn proc_macro_quoted_spans(&self) -> impl Iterator<Item = (usize, Span)> {
// This is equivalent to `.iter().copied().enumerate()`, but that isn't possible for
// AppendOnlyVec, so we resort to this scheme.
self.proc_macro_quoted_spans.iter_enumerated()
}
pub fn save_proc_macro_span(&self, span: Span) -> usize {
self.proc_macro_quoted_spans.push(span)
}
/// Returns `true` if internal lints should be added to the lint store - i.e. if
/// `-Zunstable-options` is provided and this isn't rustdoc (internal lints can trigger errors
/// to be emitted under rustdoc).
@@ -1089,6 +1110,10 @@ pub fn build_session(
opts: sopts,
target_tlib_path,
psess,
unstable_features: UnstableFeatures::from_environment(None),
config: Cfg::default(),
check_config: CheckCfg::default(),
proc_macro_quoted_spans: Default::default(),
io,
incr_comp_session: RwLock::new(IncrCompSession::NotInitialized),
prof,