Prefer `dcx` methods over fields or fields' methods

This commit is contained in:
Oli Scherer 2024-06-18 09:43:28 +00:00
parent 7e5893019c
commit c91edc3888
24 changed files with 62 additions and 58 deletions

View File

@ -596,7 +596,7 @@ pub fn eval_condition(
features: Option<&Features>,
eval: &mut impl FnMut(Condition) -> bool,
) -> bool {
let dcx = &sess.psess.dcx;
let dcx = sess.dcx();
match &cfg.kind {
ast::MetaItemKind::List(mis) if cfg.name_or_empty() == sym::version => {
try_gate_cfg(sym::version, cfg.span, sess, features);

View File

@ -46,7 +46,7 @@ pub fn parse_asm_args<'a>(
sp: Span,
is_global_asm: bool,
) -> PResult<'a, AsmArgs> {
let dcx = &p.psess.dcx;
let dcx = p.dcx();
if p.token == token::Eof {
return Err(dcx.create_err(errors::AsmRequiresTemplate { span: sp }));
@ -307,7 +307,7 @@ pub fn parse_asm_args<'a>(
fn err_duplicate_option(p: &Parser<'_>, symbol: Symbol, span: Span) {
// Tool-only output
let full_span = if p.token.kind == token::Comma { span.to(p.token.span) } else { span };
p.psess.dcx.emit_err(errors::AsmOptAlreadyprovided { span, symbol, full_span });
p.dcx().emit_err(errors::AsmOptAlreadyprovided { span, symbol, full_span });
}
/// Try to set the provided option in the provided `AsmArgs`.
@ -379,7 +379,7 @@ fn parse_clobber_abi<'a>(p: &mut Parser<'a>, args: &mut AsmArgs) -> PResult<'a,
p.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
if p.eat(&token::CloseDelim(Delimiter::Parenthesis)) {
return Err(p.psess.dcx.create_err(errors::NonABI { span: p.token.span }));
return Err(p.dcx().create_err(errors::NonABI { span: p.token.span }));
}
let mut new_abis = Vec::new();
@ -390,7 +390,7 @@ fn parse_clobber_abi<'a>(p: &mut Parser<'a>, args: &mut AsmArgs) -> PResult<'a,
}
Err(opt_lit) => {
let span = opt_lit.map_or(p.token.span, |lit| lit.span);
let mut err = p.psess.dcx.struct_span_err(span, "expected string literal");
let mut err = p.dcx().struct_span_err(span, "expected string literal");
err.span_label(span, "not a string literal");
return Err(err);
}

View File

@ -26,7 +26,7 @@ pub fn inject(krate: &mut ast::Crate, psess: &ParseSess, attrs: &[String]) {
};
let end_span = parser.token.span;
if parser.token != token::Eof {
psess.dcx.emit_err(errors::InvalidCrateAttr { span: start_span.to(end_span) });
psess.dcx().emit_err(errors::InvalidCrateAttr { span: start_span.to(end_span) });
continue;
}

View File

@ -1358,7 +1358,7 @@ fn pretty_printing_compatibility_hack(item: &Item, sess: &Session) {
if crate_matches {
// FIXME: make this translatable
#[allow(rustc::untranslatable_diagnostic)]
sess.psess.dcx.emit_fatal(errors::ProcMacroBackCompat {
sess.dcx().emit_fatal(errors::ProcMacroBackCompat {
crate_name: "rental".to_string(),
fixed_version: "0.5.6".to_string(),
});

View File

@ -206,7 +206,7 @@ pub(super) fn check_meta_variables(
rhses: &[TokenTree],
) -> Result<(), ErrorGuaranteed> {
if lhses.len() != rhses.len() {
psess.dcx.span_bug(span, "length mismatch between LHSes and RHSes")
psess.dcx().span_bug(span, "length mismatch between LHSes and RHSes")
}
let mut guar = None;
for (lhs, rhs) in iter::zip(lhses, rhses) {
@ -245,7 +245,7 @@ fn check_binders(
// MetaVar(fragment) and not as MetaVarDecl(y, fragment).
TokenTree::MetaVar(span, name) => {
if macros.is_empty() {
psess.dcx.span_bug(span, "unexpected MetaVar in lhs");
psess.dcx().span_bug(span, "unexpected MetaVar in lhs");
}
let name = MacroRulesNormalizedIdent::new(name);
// There are 3 possibilities:
@ -276,7 +276,7 @@ fn check_binders(
);
}
if !macros.is_empty() {
psess.dcx.span_bug(span, "unexpected MetaVarDecl in nested lhs");
psess.dcx().span_bug(span, "unexpected MetaVarDecl in nested lhs");
}
let name = MacroRulesNormalizedIdent::new(name);
if let Some(prev_info) = get_binder_info(macros, binders, name) {
@ -284,7 +284,7 @@ fn check_binders(
// for nested macro definitions.
*guar = Some(
psess
.dcx
.dcx()
.emit_err(errors::DuplicateMatcherBinding { span, prev: prev_info.span }),
);
} else {
@ -344,7 +344,7 @@ fn check_occurrences(
match *rhs {
TokenTree::Token(..) => {}
TokenTree::MetaVarDecl(span, _name, _kind) => {
psess.dcx.span_bug(span, "unexpected MetaVarDecl in rhs")
psess.dcx().span_bug(span, "unexpected MetaVarDecl in rhs")
}
TokenTree::MetaVar(span, name) => {
let name = MacroRulesNormalizedIdent::new(name);

View File

@ -383,7 +383,7 @@ pub fn compile_declarative_macro(
};
let dummy_syn_ext = |guar| (mk_syn_ext(Box::new(DummyExpander(guar))), Vec::new());
let dcx = &sess.psess.dcx;
let dcx = sess.dcx();
let lhs_nm = Ident::new(sym::lhs, def.span);
let rhs_nm = Ident::new(sym::rhs, def.span);
let tt_spec = Some(NonterminalKind::TT);

View File

@ -42,7 +42,7 @@ impl MetaVarExpr {
let ident = parse_ident(&mut tts, psess, outer_span)?;
let Some(TokenTree::Delimited(.., Delimiter::Parenthesis, args)) = tts.next() else {
let msg = "meta-variable expression parameter must be wrapped in parentheses";
return Err(psess.dcx.struct_span_err(ident.span, msg));
return Err(psess.dcx().struct_span_err(ident.span, msg));
};
check_trailing_token(&mut tts, psess)?;
let mut iter = args.trees();
@ -62,12 +62,12 @@ impl MetaVarExpr {
break;
}
if !try_eat_comma(&mut iter) {
return Err(psess.dcx.struct_span_err(outer_span, "expected comma"));
return Err(psess.dcx().struct_span_err(outer_span, "expected comma"));
}
}
if result.len() < 2 {
return Err(psess
.dcx
.dcx()
.struct_span_err(ident.span, "`concat` must have at least two elements"));
}
MetaVarExpr::Concat(result.into())
@ -81,7 +81,7 @@ impl MetaVarExpr {
"len" => MetaVarExpr::Len(parse_depth(&mut iter, psess, ident.span)?),
_ => {
let err_msg = "unrecognized meta-variable expression";
let mut err = psess.dcx.struct_span_err(ident.span, err_msg);
let mut err = psess.dcx().struct_span_err(ident.span, err_msg);
err.span_suggestion(
ident.span,
"supported expressions are count, ignore, index and len",
@ -120,7 +120,7 @@ fn check_trailing_token<'psess>(
) -> PResult<'psess, ()> {
if let Some(tt) = iter.next() {
let mut diag = psess
.dcx
.dcx()
.struct_span_err(tt.span(), format!("unexpected token: {}", pprust::tt_to_string(tt)));
diag.span_note(tt.span(), "meta-variable expression must not have trailing tokens");
Err(diag)
@ -139,7 +139,7 @@ fn parse_count<'psess>(
let ident = parse_ident(iter, psess, span)?;
let depth = if try_eat_comma(iter) {
if iter.look_ahead(0).is_none() {
return Err(psess.dcx.struct_span_err(
return Err(psess.dcx().struct_span_err(
span,
"`count` followed by a comma must have an associated index indicating its depth",
));
@ -160,7 +160,7 @@ fn parse_depth<'psess>(
let Some(tt) = iter.next() else { return Ok(0) };
let TokenTree::Token(token::Token { kind: token::TokenKind::Literal(lit), .. }, _) = tt else {
return Err(psess
.dcx
.dcx()
.struct_span_err(span, "meta-variable expression depth must be a literal"));
};
if let Ok(lit_kind) = LitKind::from_token_lit(*lit)
@ -170,7 +170,7 @@ fn parse_depth<'psess>(
Ok(n_usize)
} else {
let msg = "only unsuffixes integer literals are supported in meta-variable expressions";
Err(psess.dcx.struct_span_err(span, msg))
Err(psess.dcx().struct_span_err(span, msg))
}
}
@ -181,20 +181,21 @@ fn parse_ident<'psess>(
fallback_span: Span,
) -> PResult<'psess, Ident> {
let Some(tt) = iter.next() else {
return Err(psess.dcx.struct_span_err(fallback_span, "expected identifier"));
return Err(psess.dcx().struct_span_err(fallback_span, "expected identifier"));
};
let TokenTree::Token(token, _) = tt else {
return Err(psess.dcx.struct_span_err(tt.span(), "expected identifier"));
return Err(psess.dcx().struct_span_err(tt.span(), "expected identifier"));
};
if let Some((elem, is_raw)) = token.ident() {
if let IdentIsRaw::Yes = is_raw {
return Err(psess.dcx.struct_span_err(elem.span, RAW_IDENT_ERR));
return Err(psess.dcx().struct_span_err(elem.span, RAW_IDENT_ERR));
}
return Ok(elem);
}
let token_str = pprust::token_to_string(token);
let mut err =
psess.dcx.struct_span_err(token.span, format!("expected identifier, found `{token_str}`"));
let mut err = psess
.dcx()
.struct_span_err(token.span, format!("expected identifier, found `{token_str}`"));
err.span_suggestion(
token.span,
format!("try removing `{token_str}`"),
@ -236,7 +237,7 @@ fn eat_dollar<'psess>(
let _ = iter.next();
return Ok(());
}
Err(psess.dcx.struct_span_err(
Err(psess.dcx().struct_span_err(
span,
"meta-variables within meta-variable expressions must be referenced using a dollar sign",
))

View File

@ -141,7 +141,7 @@ pub(super) fn transcribe<'a>(
let mut result_stack = Vec::new();
let mut marker = Marker(expand_id, transparency, Default::default());
let dcx = &psess.dcx;
let dcx = psess.dcx();
loop {
// Look at the last frame on the stack.
// If it still has a TokenTree we have not looked at yet, use that tree.

View File

@ -522,7 +522,7 @@ impl server::FreeFunctions for Rustc<'_, '_> {
fn emit_diagnostic(&mut self, diagnostic: Diagnostic<Self::Span>) {
let message = rustc_errors::DiagMessage::from(diagnostic.message);
let mut diag: Diag<'_, ()> =
Diag::new(&self.psess().dcx, diagnostic.level.to_internal(), message);
Diag::new(self.psess().dcx(), diagnostic.level.to_internal(), message);
diag.span(MultiSpan::from_spans(diagnostic.spans));
for child in diagnostic.children {
// This message comes from another diagnostic, and we are just reconstructing the

View File

@ -63,7 +63,7 @@ fn handle_static_mut_ref(
} else {
(errors::StaticMutRefSugg::Shared { span, var }, "shared")
};
tcx.sess.psess.dcx.emit_err(errors::StaticMutRef { span, sugg, shared });
tcx.dcx().emit_err(errors::StaticMutRef { span, sugg, shared });
} else {
let (sugg, shared) = if mutable == Mutability::Mut {
(errors::RefOfMutStaticSugg::Mut { span, var }, "mutable")

View File

@ -146,7 +146,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
pub(crate) fn dcx(&self) -> &'tcx DiagCtxt {
self.tcx.dcx()
self.infcx.dcx()
}
pub fn cause(&self, span: Span, code: ObligationCauseCode<'tcx>) -> ObligationCause<'tcx> {

View File

@ -140,7 +140,7 @@ pub struct TypeErrCtxt<'a, 'tcx> {
impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
pub fn dcx(&self) -> &'tcx DiagCtxt {
self.infcx.tcx.dcx()
self.infcx.dcx()
}
/// This is just to avoid a potential footgun of accidentally

View File

@ -92,7 +92,7 @@ impl<'a, 'tcx> std::ops::Deref for CrateLoader<'a, 'tcx> {
impl<'a, 'tcx> CrateLoader<'a, 'tcx> {
fn dcx(&self) -> &'tcx DiagCtxt {
&self.tcx.dcx()
self.tcx.dcx()
}
}

View File

@ -114,7 +114,7 @@ struct StringReader<'psess, 'src> {
impl<'psess, 'src> StringReader<'psess, 'src> {
fn dcx(&self) -> &'psess DiagCtxt {
&self.psess.dcx
self.psess.dcx()
}
fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span {
@ -248,8 +248,8 @@ impl<'psess, 'src> StringReader<'psess, 'src> {
let suffix = if suffix_start < self.pos {
let string = self.str_from(suffix_start);
if string == "_" {
self.psess
.dcx
self
.dcx()
.emit_err(errors::UnderscoreLiteralSuffix { span: self.mk_sp(suffix_start, self.pos) });
None
} else {
@ -597,8 +597,7 @@ impl<'psess, 'src> StringReader<'psess, 'src> {
}
fn report_non_started_raw_string(&self, start: BytePos, bad_char: char) -> ! {
self.psess
.dcx
self.dcx()
.struct_span_fatal(
self.mk_sp(start, self.pos),
format!(

View File

@ -71,7 +71,7 @@ impl<'psess, 'src> TokenTreesReader<'psess, 'src> {
fn eof_err(&mut self) -> PErr<'psess> {
let msg = "this file contains an unclosed delimiter";
let mut err = self.string_reader.psess.dcx.struct_span_err(self.token.span, msg);
let mut err = self.string_reader.dcx().struct_span_err(self.token.span, msg);
for &(_, sp) in &self.diag_info.open_braces {
err.span_label(sp, "unclosed delimiter");
self.diag_info.unmatched_delims.push(UnmatchedDelim {
@ -290,7 +290,7 @@ impl<'psess, 'src> TokenTreesReader<'psess, 'src> {
// An unexpected closing delimiter (i.e., there is no matching opening delimiter).
let token_str = token_to_string(&self.token);
let msg = format!("unexpected closing delimiter: `{token_str}`");
let mut err = self.string_reader.psess.dcx.struct_span_err(self.token.span, msg);
let mut err = self.string_reader.dcx().struct_span_err(self.token.span, msg);
report_suspicious_mismatch_block(
&mut err,

View File

@ -351,7 +351,7 @@ pub(super) fn check_for_substitution(
let Some((_, ascii_name, token)) = ASCII_ARRAY.iter().find(|&&(s, _, _)| s == ascii_str) else {
let msg = format!("substitution character not found for '{ch}'");
reader.psess.dcx.span_bug(span, msg);
reader.dcx().span_bug(span, msg);
};
// special help suggestion for "directed" double quotes

View File

@ -73,7 +73,7 @@ pub fn new_parser_from_file<'a>(
) -> Result<Parser<'a>, Vec<Diag<'a>>> {
let source_file = psess.source_map().load_file(path).unwrap_or_else(|e| {
let msg = format!("couldn't read {}: {}", path.display(), e);
let mut err = psess.dcx.struct_fatal(msg);
let mut err = psess.dcx().struct_fatal(msg);
if let Some(sp) = sp {
err.span(sp);
}
@ -115,7 +115,7 @@ fn source_file_to_stream<'psess>(
override_span: Option<Span>,
) -> Result<TokenStream, Vec<Diag<'psess>>> {
let src = source_file.src.as_ref().unwrap_or_else(|| {
psess.dcx.bug(format!(
psess.dcx().bug(format!(
"cannot lex `source_file` without source: {}",
psess.source_map().filename_for_diagnostics(&source_file.name)
));
@ -179,7 +179,7 @@ pub fn parse_cfg_attr(
}
}
_ => {
psess.dcx.emit_err(errors::MalformedCfgAttr {
psess.dcx().emit_err(errors::MalformedCfgAttr {
span: attr.span,
sugg: CFG_ATTR_GRAMMAR_HELP,
});

View File

@ -41,7 +41,7 @@ impl AttrWrapper {
}
pub(crate) fn take_for_recovery(self, psess: &ParseSess) -> AttrVec {
psess.dcx.span_delayed_bug(
psess.dcx().span_delayed_bug(
self.attrs.get(0).map(|attr| attr.span).unwrap_or(DUMMY_SP),
"AttrVec is taken for recovery but no error is produced",
);

View File

@ -241,7 +241,7 @@ impl<'a> DerefMut for SnapshotParser<'a> {
impl<'a> Parser<'a> {
pub fn dcx(&self) -> &'a DiagCtxt {
&self.psess.dcx
self.psess.dcx()
}
/// Replace `self` with `snapshot.parser`.

View File

@ -1596,7 +1596,7 @@ pub(crate) fn make_unclosed_delims_error(
if let Some(sp) = unmatched.unclosed_span {
spans.push(sp);
};
let err = psess.dcx.create_err(MismatchedClosingDelimiter {
let err = psess.dcx().create_err(MismatchedClosingDelimiter {
spans,
delimiter: pprust::token_kind_to_string(&token::CloseDelim(found_delim)).to_string(),
unmatched: unmatched.found_span,

View File

@ -65,7 +65,7 @@ pub fn parse_meta<'a>(psess: &'a ParseSess, attr: &Attribute) -> PResult<'a, Met
let res = match res {
Ok(lit) => {
if token_lit.suffix.is_some() {
let mut err = psess.dcx.struct_span_err(
let mut err = psess.dcx().struct_span_err(
expr.span,
"suffixed literals are not allowed in attributes",
);
@ -98,7 +98,7 @@ pub fn parse_meta<'a>(psess: &'a ParseSess, attr: &Attribute) -> PResult<'a, Met
// the error because an earlier error will have already
// been reported.
let msg = "attribute value must be a literal";
let mut err = psess.dcx.struct_span_err(expr.span, msg);
let mut err = psess.dcx().struct_span_err(expr.span, msg);
if let ast::ExprKind::Err(_) = expr.kind {
err.downgrade_to_delayed_bug();
}
@ -114,7 +114,7 @@ fn check_meta_bad_delim(psess: &ParseSess, span: DelimSpan, delim: Delimiter) {
if let Delimiter::Parenthesis = delim {
return;
}
psess.dcx.emit_err(errors::MetaBadDelim {
psess.dcx().emit_err(errors::MetaBadDelim {
span: span.entire(),
sugg: errors::MetaBadDelimSugg { open: span.open, close: span.close },
});
@ -124,7 +124,7 @@ pub(super) fn check_cfg_attr_bad_delim(psess: &ParseSess, span: DelimSpan, delim
if let Delimiter::Parenthesis = delim {
return;
}
psess.dcx.emit_err(errors::CfgAttrBadDelim {
psess.dcx().emit_err(errors::CfgAttrBadDelim {
span: span.entire(),
sugg: errors::MetaBadDelimSugg { open: span.open, close: span.close },
});
@ -191,7 +191,7 @@ fn emit_malformed_attribute(
} else {
suggestions.sort();
psess
.dcx
.dcx()
.struct_span_err(span, error_msg)
.with_span_suggestions(
span,

View File

@ -401,7 +401,7 @@ pub fn report_lit_error(
valid.then(|| format!("0{}{}", base_char.to_ascii_lowercase(), &suffix[1..]))
}
let dcx = &psess.dcx;
let dcx = psess.dcx();
match err {
LitError::InvalidSuffix(suffix) => {
dcx.emit_err(InvalidLiteralSuffix { span, kind: lit.kind.descr(), suffix })

View File

@ -106,12 +106,12 @@ pub fn feature_err_issue(
// Cancel an earlier warning for this same error, if it exists.
if let Some(span) = span.primary_span() {
if let Some(err) = sess.psess.dcx.steal_non_err(span, StashKey::EarlySyntaxWarning) {
if let Some(err) = sess.dcx().steal_non_err(span, StashKey::EarlySyntaxWarning) {
err.cancel()
}
}
let mut err = sess.psess.dcx.create_err(FeatureGateError { span, explain: explain.into() });
let mut err = sess.dcx().create_err(FeatureGateError { span, explain: explain.into() });
add_feature_diagnostics_for_issue(&mut err, sess, feature, issue, false, None);
err
}
@ -140,7 +140,7 @@ pub fn feature_warn_issue(
issue: GateIssue,
explain: &'static str,
) {
let mut err = sess.psess.dcx.struct_span_warn(span, explain);
let mut err = sess.dcx().struct_span_warn(span, explain);
add_feature_diagnostics_for_issue(&mut err, sess, feature, issue, false, None);
// Decorate this as a future-incompatibility lint as in rustc_middle::lint::lint_level
@ -201,7 +201,7 @@ pub fn add_feature_diagnostics_for_issue<G: EmissionGuarantee>(
/// Info about a parsing session.
pub struct ParseSess {
pub dcx: DiagCtxt,
dcx: DiagCtxt,
pub unstable_features: UnstableFeatures,
pub config: Cfg,
pub check_config: CheckCfg,
@ -326,4 +326,8 @@ impl ParseSess {
// AppendOnlyVec, so we resort to this scheme.
self.proc_macro_quoted_spans.iter_enumerated()
}
pub fn dcx(&self) -> &DiagCtxt {
&self.dcx
}
}

View File

@ -329,7 +329,7 @@ impl Session {
#[inline]
pub fn dcx(&self) -> &DiagCtxt {
&self.psess.dcx
self.psess.dcx()
}
#[inline]