Rename ParseSess::span_diagnostic as ParseSess::dcx.

This commit is contained in:
Nicholas Nethercote 2023-12-17 22:25:47 +11:00
parent 9b1f87c7e8
commit 9df1576e1d
26 changed files with 89 additions and 98 deletions

View file

@ -47,7 +47,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 diag = &sess.span_diagnostic; let diag = &sess.dcx;
if p.token == token::Eof { if p.token == token::Eof {
return Err(diag.create_err(errors::AsmRequiresTemplate { span: sp })); return Err(diag.create_err(errors::AsmRequiresTemplate { span: sp }));
@ -298,7 +298,7 @@ pub fn parse_asm_args<'a>(
fn err_duplicate_option(p: &mut Parser<'_>, symbol: Symbol, span: Span) { fn err_duplicate_option(p: &mut 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.sess.span_diagnostic.emit_err(errors::AsmOptAlreadyprovided { span, symbol, full_span }); p.sess.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`.
@ -370,7 +370,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.sess.span_diagnostic.create_err(errors::NonABI { span: p.token.span })); return Err(p.sess.dcx.create_err(errors::NonABI { span: p.token.span }));
} }
let mut new_abis = Vec::new(); let mut new_abis = Vec::new();
@ -381,8 +381,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 = let mut err = p.sess.dcx.struct_span_err(span, "expected string literal");
p.sess.span_diagnostic.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

@ -25,9 +25,7 @@ pub fn inject(krate: &mut ast::Crate, parse_sess: &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 {
parse_sess parse_sess.dcx.emit_err(errors::InvalidCrateAttr { span: start_span.to(end_span) });
.span_diagnostic
.emit_err(errors::InvalidCrateAttr { span: start_span.to(end_span) });
continue; continue;
} }

View file

@ -1208,7 +1208,7 @@ pub fn resolve_path(
span, span,
path: parse_sess.source_map().filename_for_diagnostics(&other).to_string(), path: parse_sess.source_map().filename_for_diagnostics(&other).to_string(),
} }
.into_diagnostic(&parse_sess.span_diagnostic)); .into_diagnostic(&parse_sess.dcx));
} }
}; };
result.pop(); result.pop();

View file

@ -205,7 +205,7 @@ pub(super) fn check_meta_variables(
rhses: &[TokenTree], rhses: &[TokenTree],
) -> bool { ) -> bool {
if lhses.len() != rhses.len() { if lhses.len() != rhses.len() {
sess.span_diagnostic.span_bug(span, "length mismatch between LHSes and RHSes") sess.dcx.span_bug(span, "length mismatch between LHSes and RHSes")
} }
let mut valid = true; let mut valid = true;
for (lhs, rhs) in iter::zip(lhses, rhses) { for (lhs, rhs) in iter::zip(lhses, rhses) {
@ -244,7 +244,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() {
sess.span_diagnostic.span_bug(span, "unexpected MetaVar in lhs"); sess.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:
@ -275,14 +275,13 @@ fn check_binders(
); );
} }
if !macros.is_empty() { if !macros.is_empty() {
sess.span_diagnostic.span_bug(span, "unexpected MetaVarDecl in nested lhs"); sess.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) {
// Duplicate binders at the top-level macro definition are errors. The lint is only // Duplicate binders at the top-level macro definition are errors. The lint is only
// for nested macro definitions. // for nested macro definitions.
sess.span_diagnostic sess.dcx.emit_err(errors::DuplicateMatcherBinding { span, prev: prev_info.span });
.emit_err(errors::DuplicateMatcherBinding { span, prev: prev_info.span });
*valid = false; *valid = false;
} else { } else {
binders.insert(name, BinderInfo { span, ops: ops.into() }); binders.insert(name, BinderInfo { span, ops: ops.into() });
@ -341,7 +340,7 @@ fn check_occurrences(
match *rhs { match *rhs {
TokenTree::Token(..) => {} TokenTree::Token(..) => {}
TokenTree::MetaVarDecl(span, _name, _kind) => { TokenTree::MetaVarDecl(span, _name, _kind) => {
sess.span_diagnostic.span_bug(span, "unexpected MetaVarDecl in rhs") sess.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

@ -402,7 +402,7 @@ pub fn compile_declarative_macro(
}; };
let dummy_syn_ext = || (mk_syn_ext(Box::new(macro_rules_dummy_expander)), Vec::new()); let dummy_syn_ext = || (mk_syn_ext(Box::new(macro_rules_dummy_expander)), Vec::new());
let diag = &sess.parse_sess.span_diagnostic; let diag = &sess.parse_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);
@ -626,7 +626,7 @@ fn check_lhs_nt_follows(sess: &ParseSess, def: &ast::Item, lhs: &mbe::TokenTree)
check_matcher(sess, def, &delimited.tts) check_matcher(sess, def, &delimited.tts)
} else { } else {
let msg = "invalid macro matcher; matchers must be contained in balanced delimiters"; let msg = "invalid macro matcher; matchers must be contained in balanced delimiters";
sess.span_diagnostic.span_err(lhs.span(), msg); sess.dcx.span_err(lhs.span(), msg);
false false
} }
// we don't abort on errors on rejection, the driver will do that for us // we don't abort on errors on rejection, the driver will do that for us
@ -652,8 +652,7 @@ fn is_empty_token_tree(sess: &ParseSess, seq: &mbe::SequenceRepetition) -> bool
iter.next(); iter.next();
} }
let span = t.span.to(now.span); let span = t.span.to(now.span);
sess.span_diagnostic sess.dcx.span_note(span, "doc comments are ignored in matcher position");
.span_note(span, "doc comments are ignored in matcher position");
} }
mbe::TokenTree::Sequence(_, sub_seq) mbe::TokenTree::Sequence(_, sub_seq)
if (sub_seq.kleene.op == mbe::KleeneOp::ZeroOrMore if (sub_seq.kleene.op == mbe::KleeneOp::ZeroOrMore
@ -683,7 +682,7 @@ fn check_lhs_no_empty_seq(sess: &ParseSess, tts: &[mbe::TokenTree]) -> bool {
TokenTree::Sequence(span, seq) => { TokenTree::Sequence(span, seq) => {
if is_empty_token_tree(sess, seq) { if is_empty_token_tree(sess, seq) {
let sp = span.entire(); let sp = span.entire();
sess.span_diagnostic.span_err(sp, "repetition matches empty token tree"); sess.dcx.span_err(sp, "repetition matches empty token tree");
return false; return false;
} }
if !check_lhs_no_empty_seq(sess, &seq.tts) { if !check_lhs_no_empty_seq(sess, &seq.tts) {
@ -700,7 +699,7 @@ fn check_rhs(sess: &ParseSess, rhs: &mbe::TokenTree) -> bool {
match *rhs { match *rhs {
mbe::TokenTree::Delimited(..) => return true, mbe::TokenTree::Delimited(..) => return true,
_ => { _ => {
sess.span_diagnostic.span_err(rhs.span(), "macro rhs must be delimited"); sess.dcx.span_err(rhs.span(), "macro rhs must be delimited");
} }
} }
false false
@ -709,9 +708,9 @@ fn check_rhs(sess: &ParseSess, rhs: &mbe::TokenTree) -> bool {
fn check_matcher(sess: &ParseSess, def: &ast::Item, matcher: &[mbe::TokenTree]) -> bool { fn check_matcher(sess: &ParseSess, def: &ast::Item, matcher: &[mbe::TokenTree]) -> bool {
let first_sets = FirstSets::new(matcher); let first_sets = FirstSets::new(matcher);
let empty_suffix = TokenSet::empty(); let empty_suffix = TokenSet::empty();
let err = sess.span_diagnostic.err_count(); let err = sess.dcx.err_count();
check_matcher_core(sess, def, &first_sets, matcher, &empty_suffix); check_matcher_core(sess, def, &first_sets, matcher, &empty_suffix);
err == sess.span_diagnostic.err_count() err == sess.dcx.err_count()
} }
fn has_compile_error_macro(rhs: &mbe::TokenTree) -> bool { fn has_compile_error_macro(rhs: &mbe::TokenTree) -> bool {
@ -1190,7 +1189,7 @@ fn check_matcher_core<'tt>(
}; };
let sp = next_token.span(); let sp = next_token.span();
let mut err = sess.span_diagnostic.struct_span_err( let mut err = sess.dcx.struct_span_err(
sp, sp,
format!( format!(
"`${name}:{frag}` {may_be} followed by `{next}`, which \ "`${name}:{frag}` {may_be} followed by `{next}`, which \

View file

@ -36,7 +36,7 @@ impl MetaVarExpr {
let ident = parse_ident(&mut tts, sess, outer_span)?; let ident = parse_ident(&mut tts, sess, 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(sess.span_diagnostic.struct_span_err(ident.span, msg)); return Err(sess.dcx.struct_span_err(ident.span, msg));
}; };
check_trailing_token(&mut tts, sess)?; check_trailing_token(&mut tts, sess)?;
let mut iter = args.trees(); let mut iter = args.trees();
@ -50,7 +50,7 @@ impl MetaVarExpr {
"length" => MetaVarExpr::Length(parse_depth(&mut iter, sess, ident.span)?), "length" => MetaVarExpr::Length(parse_depth(&mut iter, sess, ident.span)?),
_ => { _ => {
let err_msg = "unrecognized meta-variable expression"; let err_msg = "unrecognized meta-variable expression";
let mut err = sess.span_diagnostic.struct_span_err(ident.span, err_msg); let mut err = sess.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 length", "supported expressions are count, ignore, index and length",
@ -79,7 +79,7 @@ fn check_trailing_token<'sess>(
) -> PResult<'sess, ()> { ) -> PResult<'sess, ()> {
if let Some(tt) = iter.next() { if let Some(tt) = iter.next() {
let mut diag = sess let mut diag = sess
.span_diagnostic .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)
@ -98,7 +98,7 @@ fn parse_count<'sess>(
let ident = parse_ident(iter, sess, span)?; let ident = parse_ident(iter, sess, 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(sess.span_diagnostic.struct_span_err( return Err(sess.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",
)); ));
@ -119,7 +119,7 @@ fn parse_depth<'sess>(
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(sess return Err(sess
.span_diagnostic .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)
@ -129,7 +129,7 @@ fn parse_depth<'sess>(
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(sess.span_diagnostic.struct_span_err(span, msg)) Err(sess.dcx.struct_span_err(span, msg))
} }
} }
@ -146,9 +146,8 @@ fn parse_ident<'sess>(
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 = sess let mut err =
.span_diagnostic sess.dcx.struct_span_err(span, format!("expected identifier, found `{}`", &token_str));
.struct_span_err(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),
@ -157,7 +156,7 @@ fn parse_ident<'sess>(
); );
return Err(err); return Err(err);
} }
Err(sess.span_diagnostic.struct_span_err(span, "expected identifier")) Err(sess.dcx.struct_span_err(span, "expected identifier"))
} }
/// Tries to move the iterator forward returning `true` if there is a comma. If not, then the /// Tries to move the iterator forward returning `true` if there is a comma. If not, then the
@ -181,7 +180,7 @@ fn eat_dollar<'sess>(
let _ = iter.next(); let _ = iter.next();
return Ok(()); return Ok(());
} }
Err(sess.span_diagnostic.struct_span_err( Err(sess.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

@ -84,7 +84,7 @@ pub(super) fn parse(
"invalid fragment specifier `{}`", "invalid fragment specifier `{}`",
frag.name frag.name
); );
sess.span_diagnostic sess.dcx
.struct_span_err(span, msg) .struct_span_err(span, msg)
.help(VALID_FRAGMENT_NAMES_MSG) .help(VALID_FRAGMENT_NAMES_MSG)
.emit(); .emit();
@ -195,7 +195,7 @@ fn parse_tree<'a>(
_ => { _ => {
let tok = pprust::token_kind_to_string(&token::OpenDelim(delim)); let tok = pprust::token_kind_to_string(&token::OpenDelim(delim));
let msg = format!("expected `(` or `{{`, found `{tok}`"); let msg = format!("expected `(` or `{{`, found `{tok}`");
sess.span_diagnostic.span_err(delim_span.entire(), msg); sess.dcx.span_err(delim_span.entire(), msg);
} }
} }
} }
@ -244,7 +244,7 @@ fn parse_tree<'a>(
Some(tokenstream::TokenTree::Token(token, _)) => { Some(tokenstream::TokenTree::Token(token, _)) => {
let msg = let msg =
format!("expected identifier, found `{}`", pprust::token_to_string(token),); format!("expected identifier, found `{}`", pprust::token_to_string(token),);
sess.span_diagnostic.span_err(token.span, msg); sess.dcx.span_err(token.span, msg);
TokenTree::MetaVar(token.span, Ident::empty()) TokenTree::MetaVar(token.span, Ident::empty())
} }
@ -325,7 +325,7 @@ fn parse_sep_and_kleene_op<'a>(
// #2 is the `?` Kleene op, which does not take a separator (error) // #2 is the `?` Kleene op, which does not take a separator (error)
Ok(Ok((KleeneOp::ZeroOrOne, span))) => { Ok(Ok((KleeneOp::ZeroOrOne, span))) => {
// Error! // Error!
sess.span_diagnostic.span_err( sess.dcx.span_err(
token.span, token.span,
"the `?` macro repetition operator does not take a separator", "the `?` macro repetition operator does not take a separator",
); );
@ -346,7 +346,7 @@ fn parse_sep_and_kleene_op<'a>(
}; };
// If we ever get to this point, we have experienced an "unexpected token" error // If we ever get to this point, we have experienced an "unexpected token" error
sess.span_diagnostic.span_err(span, "expected one of: `*`, `+`, or `?`"); sess.dcx.span_err(span, "expected one of: `*`, `+`, or `?`");
// Return a dummy // Return a dummy
(None, KleeneToken::new(KleeneOp::ZeroOrMore, span)) (None, KleeneToken::new(KleeneOp::ZeroOrMore, span))
@ -356,9 +356,8 @@ fn parse_sep_and_kleene_op<'a>(
// //
// For example, `macro_rules! foo { ( ${length()} ) => {} }` // For example, `macro_rules! foo { ( ${length()} ) => {} }`
fn span_dollar_dollar_or_metavar_in_the_lhs_err(sess: &ParseSess, token: &Token) { fn span_dollar_dollar_or_metavar_in_the_lhs_err(sess: &ParseSess, token: &Token) {
sess.span_diagnostic sess.dcx.span_err(token.span, format!("unexpected token: {}", pprust::token_to_string(token)));
.span_err(token.span, format!("unexpected token: {}", pprust::token_to_string(token))); sess.dcx.span_note(
sess.span_diagnostic.span_note(
token.span, token.span,
"`$$` and meta-variable expressions are not allowed inside macro parameter definitions", "`$$` and meta-variable expressions are not allowed inside macro parameter definitions",
); );

View file

@ -506,7 +506,7 @@ impl server::FreeFunctions for Rustc<'_, '_> {
None, None,
); );
} }
self.sess().span_diagnostic.emit_diagnostic(diag); self.sess().dcx.emit_diagnostic(diag);
} }
} }

View file

@ -46,7 +46,7 @@ where
{ {
let mut p = string_to_parser(&ps, s); let mut p = string_to_parser(&ps, s);
let x = f(&mut p).unwrap(); let x = f(&mut p).unwrap();
p.sess.span_diagnostic.abort_if_errors(); p.sess.dcx.abort_if_errors();
x x
} }

View file

@ -227,7 +227,7 @@ impl<'a> StringReader<'a> {
let string = self.str_from(suffix_start); let string = self.str_from(suffix_start);
if string == "_" { if string == "_" {
self.sess self.sess
.span_diagnostic .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 {
@ -346,7 +346,7 @@ impl<'a> StringReader<'a> {
c: char, c: char,
) -> DiagnosticBuilder<'a, !> { ) -> DiagnosticBuilder<'a, !> {
self.sess self.sess
.span_diagnostic .dcx
.struct_span_fatal(self.mk_sp(from_pos, to_pos), format!("{}: {}", m, escaped_char(c))) .struct_span_fatal(self.mk_sp(from_pos, to_pos), format!("{}: {}", m, escaped_char(c)))
} }
@ -403,7 +403,7 @@ impl<'a> StringReader<'a> {
match kind { match kind {
rustc_lexer::LiteralKind::Char { terminated } => { rustc_lexer::LiteralKind::Char { terminated } => {
if !terminated { if !terminated {
self.sess.span_diagnostic.span_fatal_with_code( self.sess.dcx.span_fatal_with_code(
self.mk_sp(start, end), self.mk_sp(start, end),
"unterminated character literal", "unterminated character literal",
error_code!(E0762), error_code!(E0762),
@ -413,7 +413,7 @@ impl<'a> StringReader<'a> {
} }
rustc_lexer::LiteralKind::Byte { terminated } => { rustc_lexer::LiteralKind::Byte { terminated } => {
if !terminated { if !terminated {
self.sess.span_diagnostic.span_fatal_with_code( self.sess.dcx.span_fatal_with_code(
self.mk_sp(start + BytePos(1), end), self.mk_sp(start + BytePos(1), end),
"unterminated byte constant", "unterminated byte constant",
error_code!(E0763), error_code!(E0763),
@ -423,7 +423,7 @@ impl<'a> StringReader<'a> {
} }
rustc_lexer::LiteralKind::Str { terminated } => { rustc_lexer::LiteralKind::Str { terminated } => {
if !terminated { if !terminated {
self.sess.span_diagnostic.span_fatal_with_code( self.sess.dcx.span_fatal_with_code(
self.mk_sp(start, end), self.mk_sp(start, end),
"unterminated double quote string", "unterminated double quote string",
error_code!(E0765), error_code!(E0765),
@ -433,7 +433,7 @@ impl<'a> StringReader<'a> {
} }
rustc_lexer::LiteralKind::ByteStr { terminated } => { rustc_lexer::LiteralKind::ByteStr { terminated } => {
if !terminated { if !terminated {
self.sess.span_diagnostic.span_fatal_with_code( self.sess.dcx.span_fatal_with_code(
self.mk_sp(start + BytePos(1), end), self.mk_sp(start + BytePos(1), end),
"unterminated double quote byte string", "unterminated double quote byte string",
error_code!(E0766), error_code!(E0766),
@ -443,7 +443,7 @@ impl<'a> StringReader<'a> {
} }
rustc_lexer::LiteralKind::CStr { terminated } => { rustc_lexer::LiteralKind::CStr { terminated } => {
if !terminated { if !terminated {
self.sess.span_diagnostic.span_fatal_with_code( self.sess.dcx.span_fatal_with_code(
self.mk_sp(start + BytePos(1), end), self.mk_sp(start + BytePos(1), end),
"unterminated C string", "unterminated C string",
error_code!(E0767), error_code!(E0767),
@ -578,7 +578,7 @@ impl<'a> StringReader<'a> {
possible_offset: Option<u32>, possible_offset: Option<u32>,
found_terminators: u32, found_terminators: u32,
) -> ! { ) -> ! {
let mut err = self.sess.span_diagnostic.struct_span_fatal_with_code( let mut err = self.sess.dcx.struct_span_fatal_with_code(
self.mk_sp(start, start), self.mk_sp(start, start),
"unterminated raw string", "unterminated raw string",
error_code!(E0748), error_code!(E0748),
@ -614,7 +614,7 @@ impl<'a> StringReader<'a> {
None => "unterminated block comment", None => "unterminated block comment",
}; };
let last_bpos = self.pos; let last_bpos = self.pos;
let mut err = self.sess.span_diagnostic.struct_span_fatal_with_code( let mut err = self.sess.dcx.struct_span_fatal_with_code(
self.mk_sp(start, last_bpos), self.mk_sp(start, last_bpos),
msg, msg,
error_code!(E0758), error_code!(E0758),
@ -719,7 +719,7 @@ impl<'a> StringReader<'a> {
has_fatal_err = true; has_fatal_err = true;
} }
emit_unescape_error( emit_unescape_error(
&self.sess.span_diagnostic, &self.sess.dcx,
lit_content, lit_content,
span_with_quotes, span_with_quotes,
span, span,

View file

@ -73,7 +73,7 @@ impl<'a> TokenTreesReader<'a> {
fn eof_err(&mut self) -> PErr<'a> { fn eof_err(&mut self) -> PErr<'a> {
let msg = "this file contains an unclosed delimiter"; let msg = "this file contains an unclosed delimiter";
let mut err = self.string_reader.sess.span_diagnostic.struct_span_err(self.token.span, msg); let mut err = self.string_reader.sess.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<'a> TokenTreesReader<'a> {
// matching opening delimiter). // 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.sess.span_diagnostic.struct_span_err(self.token.span, msg); let mut err = self.string_reader.sess.dcx.struct_span_err(self.token.span, msg);
report_suspicious_mismatch_block( report_suspicious_mismatch_block(
&mut err, &mut err,

View file

@ -350,7 +350,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.sess.span_diagnostic.span_bug(span, msg); reader.sess.dcx.span_bug(span, msg);
}; };
// special help suggestion for "directed" double quotes // special help suggestion for "directed" double quotes

View file

@ -100,7 +100,7 @@ pub fn parse_stream_from_source_str(
/// Creates a new parser from a source string. /// Creates a new parser from a source string.
pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> { pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source)) panictry_buffer!(&sess.dcx, maybe_new_parser_from_source_str(sess, name, source))
} }
/// Creates a new parser from a source string. Returns any buffered errors from lexing the initial /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial
@ -121,7 +121,7 @@ pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path, sp: Option<Spa
/// Given a session and a `source_file`, returns a parser. /// Given a session and a `source_file`, returns a parser.
fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> { fn source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>) -> Parser<'_> {
panictry_buffer!(&sess.span_diagnostic, maybe_source_file_to_parser(sess, source_file)) panictry_buffer!(&sess.dcx, maybe_source_file_to_parser(sess, source_file))
} }
/// Given a session and a `source_file`, return a parser. Returns any buffered errors from lexing the /// Given a session and a `source_file`, return a parser. Returns any buffered errors from lexing the
@ -166,7 +166,7 @@ fn file_to_source_file(sess: &ParseSess, path: &Path, spanopt: Option<Span>) ->
match try_file_to_source_file(sess, path, spanopt) { match try_file_to_source_file(sess, path, spanopt) {
Ok(source_file) => source_file, Ok(source_file) => source_file,
Err(d) => { Err(d) => {
sess.span_diagnostic.emit_diagnostic(d); sess.dcx.emit_diagnostic(d);
FatalError.raise(); FatalError.raise();
} }
} }
@ -178,7 +178,7 @@ pub fn source_file_to_stream(
source_file: Lrc<SourceFile>, source_file: Lrc<SourceFile>,
override_span: Option<Span>, override_span: Option<Span>,
) -> TokenStream { ) -> TokenStream {
panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span)) panictry_buffer!(&sess.dcx, maybe_file_to_stream(sess, source_file, override_span))
} }
/// Given a source file, produces a sequence of token trees. Returns any buffered errors from /// Given a source file, produces a sequence of token trees. Returns any buffered errors from
@ -189,7 +189,7 @@ pub fn maybe_file_to_stream(
override_span: Option<Span>, override_span: Option<Span>,
) -> Result<TokenStream, Vec<Diagnostic>> { ) -> Result<TokenStream, Vec<Diagnostic>> {
let src = source_file.src.as_ref().unwrap_or_else(|| { let src = source_file.src.as_ref().unwrap_or_else(|| {
sess.span_diagnostic.bug(format!( sess.dcx.bug(format!(
"cannot lex `source_file` without source: {}", "cannot lex `source_file` without source: {}",
sess.source_map().filename_for_diagnostics(&source_file.name) sess.source_map().filename_for_diagnostics(&source_file.name)
)); ));

View file

@ -41,7 +41,7 @@ impl AttrWrapper {
} }
pub(crate) fn take_for_recovery(self, sess: &ParseSess) -> AttrVec { pub(crate) fn take_for_recovery(self, sess: &ParseSess) -> AttrVec {
sess.span_diagnostic.span_delayed_bug( sess.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

@ -254,7 +254,7 @@ impl<'a> Parser<'a> {
} }
pub(super) fn diagnostic(&self) -> &'a DiagCtxt { pub(super) fn diagnostic(&self) -> &'a DiagCtxt {
&self.sess.span_diagnostic &self.sess.dcx
} }
/// Replace `self` with `snapshot.parser`. /// Replace `self` with `snapshot.parser`.

View file

@ -3537,7 +3537,7 @@ impl<'a> Parser<'a> {
ident_span: this.token.span, ident_span: this.token.span,
token: this.look_ahead(1, |t| t.clone()), token: this.look_ahead(1, |t| t.clone()),
} }
.into_diagnostic(&self.sess.span_diagnostic)); .into_diagnostic(&self.sess.dcx));
} }
let (ident, expr) = if is_shorthand { let (ident, expr) = if is_shorthand {
// Mimic `x: x` for the `x` field shorthand. // Mimic `x: x` for the `x` field shorthand.

View file

@ -1507,7 +1507,7 @@ pub(crate) fn make_unclosed_delims_error(
opening_candidate: unmatched.candidate_span, opening_candidate: unmatched.candidate_span,
unclosed: unmatched.unclosed_span, unclosed: unmatched.unclosed_span,
} }
.into_diagnostic(&sess.span_diagnostic); .into_diagnostic(&sess.dcx);
Some(err) Some(err)
} }

View file

@ -56,7 +56,7 @@ pub fn parse_meta<'a>(sess: &'a ParseSess, attr: &Attribute) -> PResult<'a, Meta
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 = sess.span_diagnostic.struct_span_err( let mut err = sess.dcx.struct_span_err(
expr.span, expr.span,
"suffixed literals are not allowed in attributes", "suffixed literals are not allowed in attributes",
); );
@ -89,7 +89,7 @@ pub fn parse_meta<'a>(sess: &'a ParseSess, attr: &Attribute) -> PResult<'a, Meta
// the error because an earlier error will have already // the error because an earlier error will have already
// been reported. // been reported.
let msg = format!("attribute value must be a literal"); let msg = format!("attribute value must be a literal");
let mut err = sess.span_diagnostic.struct_span_err(expr.span, msg); let mut err = sess.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();
} }
@ -206,7 +206,7 @@ fn emit_malformed_attribute(
if should_warn(name) { if should_warn(name) {
sess.buffer_lint(ILL_FORMED_ATTRIBUTE_INPUT, span, ast::CRATE_NODE_ID, msg); sess.buffer_lint(ILL_FORMED_ATTRIBUTE_INPUT, span, ast::CRATE_NODE_ID, msg);
} else { } else {
sess.span_diagnostic sess.dcx
.struct_span_err(span, error_msg) .struct_span_err(span, error_msg)
.span_suggestions( .span_suggestions(
span, span,

View file

@ -103,8 +103,7 @@ 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.span_diagnostic.steal_diagnostic(span, StashKey::EarlySyntaxWarning) if let Some(err) = sess.dcx.steal_diagnostic(span, StashKey::EarlySyntaxWarning) {
{
err.cancel() err.cancel()
} }
} }
@ -138,7 +137,7 @@ pub fn feature_warn_issue(
issue: GateIssue, issue: GateIssue,
explain: &'static str, explain: &'static str,
) { ) {
let mut err = sess.span_diagnostic.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); add_feature_diagnostics_for_issue(&mut err, sess, feature, issue, false);
// Decorate this as a future-incompatibility lint as in rustc_middle::lint::struct_lint_level // Decorate this as a future-incompatibility lint as in rustc_middle::lint::struct_lint_level
@ -189,7 +188,7 @@ pub fn add_feature_diagnostics_for_issue(
/// Info about a parsing session. /// Info about a parsing session.
pub struct ParseSess { pub struct ParseSess {
pub span_diagnostic: DiagCtxt, pub dcx: DiagCtxt,
pub unstable_features: UnstableFeatures, pub unstable_features: UnstableFeatures,
pub config: Cfg, pub config: Cfg,
pub check_config: CheckCfg, pub check_config: CheckCfg,
@ -233,7 +232,7 @@ impl ParseSess {
pub fn with_span_handler(handler: DiagCtxt, source_map: Lrc<SourceMap>) -> Self { pub fn with_span_handler(handler: DiagCtxt, source_map: Lrc<SourceMap>) -> Self {
Self { Self {
span_diagnostic: handler, dcx: handler,
unstable_features: UnstableFeatures::from_environment(None), unstable_features: UnstableFeatures::from_environment(None),
config: Cfg::default(), config: Cfg::default(),
check_config: CheckCfg::default(), check_config: CheckCfg::default(),
@ -323,7 +322,7 @@ impl ParseSess {
&'a self, &'a self,
err: impl IntoDiagnostic<'a>, err: impl IntoDiagnostic<'a>,
) -> DiagnosticBuilder<'a, ErrorGuaranteed> { ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
err.into_diagnostic(&self.span_diagnostic) err.into_diagnostic(&self.dcx)
} }
#[track_caller] #[track_caller]
@ -336,7 +335,7 @@ impl ParseSess {
&'a self, &'a self,
warning: impl IntoDiagnostic<'a, ()>, warning: impl IntoDiagnostic<'a, ()>,
) -> DiagnosticBuilder<'a, ()> { ) -> DiagnosticBuilder<'a, ()> {
warning.into_diagnostic(&self.span_diagnostic) warning.into_diagnostic(&self.dcx)
} }
#[track_caller] #[track_caller]
@ -349,7 +348,7 @@ impl ParseSess {
&'a self, &'a self,
note: impl IntoDiagnostic<'a, Noted>, note: impl IntoDiagnostic<'a, Noted>,
) -> DiagnosticBuilder<'a, Noted> { ) -> DiagnosticBuilder<'a, Noted> {
note.into_diagnostic(&self.span_diagnostic) note.into_diagnostic(&self.dcx)
} }
#[track_caller] #[track_caller]
@ -362,7 +361,7 @@ impl ParseSess {
&'a self, &'a self,
fatal: impl IntoDiagnostic<'a, !>, fatal: impl IntoDiagnostic<'a, !>,
) -> DiagnosticBuilder<'a, !> { ) -> DiagnosticBuilder<'a, !> {
fatal.into_diagnostic(&self.span_diagnostic) fatal.into_diagnostic(&self.dcx)
} }
#[track_caller] #[track_caller]
@ -376,18 +375,18 @@ impl ParseSess {
&self, &self,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, ErrorGuaranteed> { ) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
self.span_diagnostic.struct_err(msg) self.dcx.struct_err(msg)
} }
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
#[track_caller] #[track_caller]
pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> { pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
self.span_diagnostic.struct_warn(msg) self.dcx.struct_warn(msg)
} }
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
#[track_caller] #[track_caller]
pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> { pub fn struct_fatal(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, !> {
self.span_diagnostic.struct_fatal(msg) self.dcx.struct_fatal(msg)
} }
} }

View file

@ -678,7 +678,7 @@ impl Session {
#[inline] #[inline]
pub fn diagnostic(&self) -> &DiagCtxt { pub fn diagnostic(&self) -> &DiagCtxt {
&self.parse_sess.span_diagnostic &self.parse_sess.dcx
} }
#[inline] #[inline]

View file

@ -641,7 +641,7 @@ pub(crate) fn make_test(
// handler. Any errors in the tests will be reported when the test file is compiled, // handler. Any errors in the tests will be reported when the test file is compiled,
// Note that we still need to cancel the errors above otherwise `DiagnosticBuilder` // Note that we still need to cancel the errors above otherwise `DiagnosticBuilder`
// will panic on drop. // will panic on drop.
sess.span_diagnostic.reset_err_count(); sess.dcx.reset_err_count();
(found_main, found_extern_crate, found_macro) (found_main, found_extern_crate, found_macro)
}) })

View file

@ -66,9 +66,8 @@ pub(crate) fn look_for_custom_classes<'tcx>(cx: &DocContext<'tcx>, item: &Item)
if !tests.custom_classes_found.is_empty() { if !tests.custom_classes_found.is_empty() {
let span = item.attr_span(cx.tcx); let span = item.attr_span(cx.tcx);
let sess = &cx.tcx.sess.parse_sess; let sess = &cx.tcx.sess.parse_sess;
let mut err = sess let mut err =
.span_diagnostic sess.dcx.struct_span_warn(span, "custom classes in code blocks will change behaviour");
.struct_span_warn(span, "custom classes in code blocks will change behaviour");
add_feature_diagnostics_for_issue( add_feature_diagnostics_for_issue(
&mut err, &mut err,
sess, sess,

View file

@ -67,7 +67,7 @@ fn parse_cfg_if_inner<'a>(
Ok(None) => continue, Ok(None) => continue,
Err(err) => { Err(err) => {
err.cancel(); err.cancel();
parser.sess.span_diagnostic.reset_err_count(); parser.sess.dcx.reset_err_count();
return Err( return Err(
"Expected item inside cfg_if block, but failed to parse it as an item", "Expected item inside cfg_if block, but failed to parse it as an item",
); );

View file

@ -16,8 +16,8 @@ pub(crate) fn parse_lazy_static(
($method:ident $(,)* $($arg:expr),* $(,)*) => { ($method:ident $(,)* $($arg:expr),* $(,)*) => {
match parser.$method($($arg,)*) { match parser.$method($($arg,)*) {
Ok(val) => { Ok(val) => {
if parser.sess.span_diagnostic.has_errors().is_some() { if parser.sess.dcx.has_errors().is_some() {
parser.sess.span_diagnostic.reset_err_count(); parser.sess.dcx.reset_err_count();
return None; return None;
} else { } else {
val val
@ -25,7 +25,7 @@ pub(crate) fn parse_lazy_static(
} }
Err(err) => { Err(err) => {
err.cancel(); err.cancel();
parser.sess.span_diagnostic.reset_err_count(); parser.sess.dcx.reset_err_count();
return None; return None;
} }
} }

View file

@ -28,8 +28,8 @@ fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
let mut cloned_parser = (*parser).clone(); let mut cloned_parser = (*parser).clone();
match $parser(&mut cloned_parser) { match $parser(&mut cloned_parser) {
Ok(x) => { Ok(x) => {
if parser.sess.span_diagnostic.has_errors().is_some() { if parser.sess.dcx.has_errors().is_some() {
parser.sess.span_diagnostic.reset_err_count(); parser.sess.dcx.reset_err_count();
} else { } else {
// Parsing succeeded. // Parsing succeeded.
*parser = cloned_parser; *parser = cloned_parser;
@ -38,7 +38,7 @@ fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
} }
Err(e) => { Err(e) => {
e.cancel(); e.cancel();
parser.sess.span_diagnostic.reset_err_count(); parser.sess.dcx.reset_err_count();
} }
} }
}; };

View file

@ -218,7 +218,7 @@ impl ParseSess {
} }
pub(crate) fn set_silent_emitter(&mut self) { pub(crate) fn set_silent_emitter(&mut self) {
self.parse_sess.span_diagnostic = DiagCtxt::with_emitter(silent_emitter()); self.parse_sess.dcx = DiagCtxt::with_emitter(silent_emitter());
} }
pub(crate) fn span_to_filename(&self, span: Span) -> FileName { pub(crate) fn span_to_filename(&self, span: Span) -> FileName {
@ -285,7 +285,7 @@ impl ParseSess {
impl ParseSess { impl ParseSess {
pub(super) fn emit_diagnostics(&self, diagnostics: Vec<Diagnostic>) { pub(super) fn emit_diagnostics(&self, diagnostics: Vec<Diagnostic>) {
for diagnostic in diagnostics { for diagnostic in diagnostics {
self.parse_sess.span_diagnostic.emit_diagnostic(diagnostic); self.parse_sess.dcx.emit_diagnostic(diagnostic);
} }
} }
@ -294,11 +294,11 @@ impl ParseSess {
} }
pub(super) fn has_errors(&self) -> bool { pub(super) fn has_errors(&self) -> bool {
self.parse_sess.span_diagnostic.has_errors().is_some() self.parse_sess.dcx.has_errors().is_some()
} }
pub(super) fn reset_errors(&self) { pub(super) fn reset_errors(&self) {
self.parse_sess.span_diagnostic.reset_err_count(); self.parse_sess.dcx.reset_err_count();
} }
} }