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>, features: Option<&Features>,
eval: &mut impl FnMut(Condition) -> bool, eval: &mut impl FnMut(Condition) -> bool,
) -> bool { ) -> bool {
let dcx = &sess.psess.dcx; let dcx = sess.dcx();
match &cfg.kind { match &cfg.kind {
ast::MetaItemKind::List(mis) if cfg.name_or_empty() == sym::version => { ast::MetaItemKind::List(mis) if cfg.name_or_empty() == sym::version => {
try_gate_cfg(sym::version, cfg.span, sess, features); try_gate_cfg(sym::version, cfg.span, sess, features);

View File

@ -46,7 +46,7 @@ pub fn parse_asm_args<'a>(
sp: Span, sp: Span,
is_global_asm: bool, is_global_asm: bool,
) -> PResult<'a, AsmArgs> { ) -> PResult<'a, AsmArgs> {
let dcx = &p.psess.dcx; let dcx = p.dcx();
if p.token == token::Eof { if p.token == token::Eof {
return Err(dcx.create_err(errors::AsmRequiresTemplate { span: sp })); 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) { fn err_duplicate_option(p: &Parser<'_>, symbol: Symbol, span: Span) {
// Tool-only output // Tool-only output
let full_span = if p.token.kind == token::Comma { span.to(p.token.span) } else { span }; 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`. /// 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))?; p.expect(&token::OpenDelim(Delimiter::Parenthesis))?;
if p.eat(&token::CloseDelim(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(); 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) => { Err(opt_lit) => {
let span = opt_lit.map_or(p.token.span, |lit| lit.span); 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"); err.span_label(span, "not a string literal");
return Err(err); 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; let end_span = parser.token.span;
if parser.token != token::Eof { 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; continue;
} }

View File

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

View File

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

View File

@ -42,7 +42,7 @@ impl MetaVarExpr {
let ident = parse_ident(&mut tts, psess, outer_span)?; let ident = parse_ident(&mut tts, psess, outer_span)?;
let Some(TokenTree::Delimited(.., Delimiter::Parenthesis, args)) = tts.next() else { let Some(TokenTree::Delimited(.., Delimiter::Parenthesis, args)) = tts.next() else {
let msg = "meta-variable expression parameter must be wrapped in parentheses"; 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)?; check_trailing_token(&mut tts, psess)?;
let mut iter = args.trees(); let mut iter = args.trees();
@ -62,12 +62,12 @@ impl MetaVarExpr {
break; break;
} }
if !try_eat_comma(&mut iter) { 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 { if result.len() < 2 {
return Err(psess return Err(psess
.dcx .dcx()
.struct_span_err(ident.span, "`concat` must have at least two elements")); .struct_span_err(ident.span, "`concat` must have at least two elements"));
} }
MetaVarExpr::Concat(result.into()) MetaVarExpr::Concat(result.into())
@ -81,7 +81,7 @@ impl MetaVarExpr {
"len" => MetaVarExpr::Len(parse_depth(&mut iter, psess, ident.span)?), "len" => MetaVarExpr::Len(parse_depth(&mut iter, psess, ident.span)?),
_ => { _ => {
let err_msg = "unrecognized meta-variable expression"; 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( err.span_suggestion(
ident.span, ident.span,
"supported expressions are count, ignore, index and len", "supported expressions are count, ignore, index and len",
@ -120,7 +120,7 @@ fn check_trailing_token<'psess>(
) -> PResult<'psess, ()> { ) -> PResult<'psess, ()> {
if let Some(tt) = iter.next() { if let Some(tt) = iter.next() {
let mut diag = psess let mut diag = psess
.dcx .dcx()
.struct_span_err(tt.span(), format!("unexpected token: {}", pprust::tt_to_string(tt))); .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"); diag.span_note(tt.span(), "meta-variable expression must not have trailing tokens");
Err(diag) Err(diag)
@ -139,7 +139,7 @@ fn parse_count<'psess>(
let ident = parse_ident(iter, psess, span)?; let ident = parse_ident(iter, psess, span)?;
let depth = if try_eat_comma(iter) { let depth = if try_eat_comma(iter) {
if iter.look_ahead(0).is_none() { if iter.look_ahead(0).is_none() {
return Err(psess.dcx.struct_span_err( return Err(psess.dcx().struct_span_err(
span, span,
"`count` followed by a comma must have an associated index indicating its depth", "`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 Some(tt) = iter.next() else { return Ok(0) };
let TokenTree::Token(token::Token { kind: token::TokenKind::Literal(lit), .. }, _) = tt else { let TokenTree::Token(token::Token { kind: token::TokenKind::Literal(lit), .. }, _) = tt else {
return Err(psess return Err(psess
.dcx .dcx()
.struct_span_err(span, "meta-variable expression depth must be a literal")); .struct_span_err(span, "meta-variable expression depth must be a literal"));
}; };
if let Ok(lit_kind) = LitKind::from_token_lit(*lit) if let Ok(lit_kind) = LitKind::from_token_lit(*lit)
@ -170,7 +170,7 @@ fn parse_depth<'psess>(
Ok(n_usize) Ok(n_usize)
} else { } else {
let msg = "only unsuffixes integer literals are supported in meta-variable expressions"; 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, fallback_span: Span,
) -> PResult<'psess, Ident> { ) -> PResult<'psess, Ident> {
let Some(tt) = iter.next() else { 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 { 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 Some((elem, is_raw)) = token.ident() {
if let IdentIsRaw::Yes = is_raw { 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); return Ok(elem);
} }
let token_str = pprust::token_to_string(token); let token_str = pprust::token_to_string(token);
let mut err = let mut err = psess
psess.dcx.struct_span_err(token.span, format!("expected identifier, found `{token_str}`")); .dcx()
.struct_span_err(token.span, format!("expected identifier, found `{token_str}`"));
err.span_suggestion( err.span_suggestion(
token.span, token.span,
format!("try removing `{token_str}`"), format!("try removing `{token_str}`"),
@ -236,7 +237,7 @@ fn eat_dollar<'psess>(
let _ = iter.next(); let _ = iter.next();
return Ok(()); return Ok(());
} }
Err(psess.dcx.struct_span_err( Err(psess.dcx().struct_span_err(
span, span,
"meta-variables within meta-variable expressions must be referenced using a dollar sign", "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 result_stack = Vec::new();
let mut marker = Marker(expand_id, transparency, Default::default()); let mut marker = Marker(expand_id, transparency, Default::default());
let dcx = &psess.dcx; let dcx = psess.dcx();
loop { loop {
// Look at the last frame on the stack. // Look at the last frame on the stack.
// If it still has a TokenTree we have not looked at yet, use that tree. // 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>) { fn emit_diagnostic(&mut self, diagnostic: Diagnostic<Self::Span>) {
let message = rustc_errors::DiagMessage::from(diagnostic.message); let message = rustc_errors::DiagMessage::from(diagnostic.message);
let mut diag: Diag<'_, ()> = 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)); diag.span(MultiSpan::from_spans(diagnostic.spans));
for child in diagnostic.children { for child in diagnostic.children {
// This message comes from another diagnostic, and we are just reconstructing the // This message comes from another diagnostic, and we are just reconstructing the

View File

@ -63,7 +63,7 @@ fn handle_static_mut_ref(
} else { } else {
(errors::StaticMutRefSugg::Shared { span, var }, "shared") (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 { } else {
let (sugg, shared) = if mutable == Mutability::Mut { let (sugg, shared) = if mutable == Mutability::Mut {
(errors::RefOfMutStaticSugg::Mut { span, var }, "mutable") (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 { pub(crate) fn dcx(&self) -> &'tcx DiagCtxt {
self.tcx.dcx() self.infcx.dcx()
} }
pub fn cause(&self, span: Span, code: ObligationCauseCode<'tcx>) -> ObligationCause<'tcx> { 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> { impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
pub fn dcx(&self) -> &'tcx DiagCtxt { pub fn dcx(&self) -> &'tcx DiagCtxt {
self.infcx.tcx.dcx() self.infcx.dcx()
} }
/// This is just to avoid a potential footgun of accidentally /// 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> { impl<'a, 'tcx> CrateLoader<'a, 'tcx> {
fn dcx(&self) -> &'tcx DiagCtxt { 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> { impl<'psess, 'src> StringReader<'psess, 'src> {
fn dcx(&self) -> &'psess DiagCtxt { fn dcx(&self) -> &'psess DiagCtxt {
&self.psess.dcx self.psess.dcx()
} }
fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span { 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 suffix = if suffix_start < self.pos {
let string = self.str_from(suffix_start); let string = self.str_from(suffix_start);
if string == "_" { if string == "_" {
self.psess self
.dcx .dcx()
.emit_err(errors::UnderscoreLiteralSuffix { span: self.mk_sp(suffix_start, self.pos) }); .emit_err(errors::UnderscoreLiteralSuffix { span: self.mk_sp(suffix_start, self.pos) });
None None
} else { } else {
@ -597,8 +597,7 @@ impl<'psess, 'src> StringReader<'psess, 'src> {
} }
fn report_non_started_raw_string(&self, start: BytePos, bad_char: char) -> ! { fn report_non_started_raw_string(&self, start: BytePos, bad_char: char) -> ! {
self.psess self.dcx()
.dcx
.struct_span_fatal( .struct_span_fatal(
self.mk_sp(start, self.pos), self.mk_sp(start, self.pos),
format!( format!(

View File

@ -71,7 +71,7 @@ impl<'psess, 'src> TokenTreesReader<'psess, 'src> {
fn eof_err(&mut self) -> PErr<'psess> { fn eof_err(&mut self) -> PErr<'psess> {
let msg = "this file contains an unclosed delimiter"; 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 { for &(_, sp) in &self.diag_info.open_braces {
err.span_label(sp, "unclosed delimiter"); err.span_label(sp, "unclosed delimiter");
self.diag_info.unmatched_delims.push(UnmatchedDelim { 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). // An unexpected closing delimiter (i.e., there is no matching opening delimiter).
let token_str = token_to_string(&self.token); let token_str = token_to_string(&self.token);
let msg = format!("unexpected closing delimiter: `{token_str}`"); 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( report_suspicious_mismatch_block(
&mut err, &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 Some((_, ascii_name, token)) = ASCII_ARRAY.iter().find(|&&(s, _, _)| s == ascii_str) else {
let msg = format!("substitution character not found for '{ch}'"); 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 // 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>>> { ) -> Result<Parser<'a>, Vec<Diag<'a>>> {
let source_file = psess.source_map().load_file(path).unwrap_or_else(|e| { let source_file = psess.source_map().load_file(path).unwrap_or_else(|e| {
let msg = format!("couldn't read {}: {}", path.display(), 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 { if let Some(sp) = sp {
err.span(sp); err.span(sp);
} }
@ -115,7 +115,7 @@ fn source_file_to_stream<'psess>(
override_span: Option<Span>, override_span: Option<Span>,
) -> Result<TokenStream, Vec<Diag<'psess>>> { ) -> Result<TokenStream, Vec<Diag<'psess>>> {
let src = source_file.src.as_ref().unwrap_or_else(|| { let src = source_file.src.as_ref().unwrap_or_else(|| {
psess.dcx.bug(format!( psess.dcx().bug(format!(
"cannot lex `source_file` without source: {}", "cannot lex `source_file` without source: {}",
psess.source_map().filename_for_diagnostics(&source_file.name) 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, span: attr.span,
sugg: CFG_ATTR_GRAMMAR_HELP, sugg: CFG_ATTR_GRAMMAR_HELP,
}); });

View File

@ -41,7 +41,7 @@ impl AttrWrapper {
} }
pub(crate) fn take_for_recovery(self, psess: &ParseSess) -> AttrVec { 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), self.attrs.get(0).map(|attr| attr.span).unwrap_or(DUMMY_SP),
"AttrVec is taken for recovery but no error is produced", "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> { impl<'a> Parser<'a> {
pub fn dcx(&self) -> &'a DiagCtxt { pub fn dcx(&self) -> &'a DiagCtxt {
&self.psess.dcx self.psess.dcx()
} }
/// Replace `self` with `snapshot.parser`. /// 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 { if let Some(sp) = unmatched.unclosed_span {
spans.push(sp); spans.push(sp);
}; };
let err = psess.dcx.create_err(MismatchedClosingDelimiter { let err = psess.dcx().create_err(MismatchedClosingDelimiter {
spans, spans,
delimiter: pprust::token_kind_to_string(&token::CloseDelim(found_delim)).to_string(), delimiter: pprust::token_kind_to_string(&token::CloseDelim(found_delim)).to_string(),
unmatched: unmatched.found_span, 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 { let res = match res {
Ok(lit) => { Ok(lit) => {
if token_lit.suffix.is_some() { if token_lit.suffix.is_some() {
let mut err = psess.dcx.struct_span_err( let mut err = psess.dcx().struct_span_err(
expr.span, expr.span,
"suffixed literals are not allowed in attributes", "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 // the error because an earlier error will have already
// been reported. // been reported.
let msg = "attribute value must be a literal"; 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 { if let ast::ExprKind::Err(_) = expr.kind {
err.downgrade_to_delayed_bug(); 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 { if let Delimiter::Parenthesis = delim {
return; return;
} }
psess.dcx.emit_err(errors::MetaBadDelim { psess.dcx().emit_err(errors::MetaBadDelim {
span: span.entire(), span: span.entire(),
sugg: errors::MetaBadDelimSugg { open: span.open, close: span.close }, 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 { if let Delimiter::Parenthesis = delim {
return; return;
} }
psess.dcx.emit_err(errors::CfgAttrBadDelim { psess.dcx().emit_err(errors::CfgAttrBadDelim {
span: span.entire(), span: span.entire(),
sugg: errors::MetaBadDelimSugg { open: span.open, close: span.close }, sugg: errors::MetaBadDelimSugg { open: span.open, close: span.close },
}); });
@ -191,7 +191,7 @@ fn emit_malformed_attribute(
} else { } else {
suggestions.sort(); suggestions.sort();
psess psess
.dcx .dcx()
.struct_span_err(span, error_msg) .struct_span_err(span, error_msg)
.with_span_suggestions( .with_span_suggestions(
span, span,

View File

@ -401,7 +401,7 @@ pub fn report_lit_error(
valid.then(|| format!("0{}{}", base_char.to_ascii_lowercase(), &suffix[1..])) valid.then(|| format!("0{}{}", base_char.to_ascii_lowercase(), &suffix[1..]))
} }
let dcx = &psess.dcx; let dcx = psess.dcx();
match err { match err {
LitError::InvalidSuffix(suffix) => { LitError::InvalidSuffix(suffix) => {
dcx.emit_err(InvalidLiteralSuffix { span, kind: lit.kind.descr(), 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. // Cancel an earlier warning for this same error, if it exists.
if let Some(span) = span.primary_span() { 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() 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); add_feature_diagnostics_for_issue(&mut err, sess, feature, issue, false, None);
err err
} }
@ -140,7 +140,7 @@ pub fn feature_warn_issue(
issue: GateIssue, issue: GateIssue,
explain: &'static str, 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); 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 // 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. /// Info about a parsing session.
pub struct ParseSess { pub struct ParseSess {
pub dcx: DiagCtxt, dcx: DiagCtxt,
pub unstable_features: UnstableFeatures, pub unstable_features: UnstableFeatures,
pub config: Cfg, pub config: Cfg,
pub check_config: CheckCfg, pub check_config: CheckCfg,
@ -326,4 +326,8 @@ impl ParseSess {
// AppendOnlyVec, so we resort to this scheme. // AppendOnlyVec, so we resort to this scheme.
self.proc_macro_quoted_spans.iter_enumerated() self.proc_macro_quoted_spans.iter_enumerated()
} }
pub fn dcx(&self) -> &DiagCtxt {
&self.dcx
}
} }

View File

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