1
Fork 0

Remove ExtCtxt methods that duplicate DiagCtxt methods.

This commit is contained in:
Nicholas Nethercote 2023-12-18 20:54:03 +11:00
parent 5eccfc388e
commit d86a48278f
33 changed files with 155 additions and 180 deletions

View file

@ -14,10 +14,7 @@ use rustc_ast::{self as ast, AttrVec, Attribute, HasAttrs, Item, NodeId, PatKind
use rustc_attr::{self as attr, Deprecation, Stability};
use rustc_data_structures::fx::FxIndexMap;
use rustc_data_structures::sync::{self, Lrc};
use rustc_errors::{
Applicability, DiagnosticBuilder, DiagnosticMessage, ErrorGuaranteed, IntoDiagnostic,
MultiSpan, PResult,
};
use rustc_errors::{Applicability, DiagCtxt, DiagnosticBuilder, ErrorGuaranteed, PResult};
use rustc_feature::Features;
use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT;
use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics, RegisteredTools};
@ -1058,6 +1055,10 @@ impl<'a> ExtCtxt<'a> {
}
}
pub fn dcx(&self) -> &'a DiagCtxt {
self.sess.dcx()
}
/// Returns a `Folder` for deeply expanding all macros in an AST node.
pub fn expander<'b>(&'b mut self) -> expand::MacroExpander<'b, 'a> {
expand::MacroExpander::new(self, false)
@ -1112,39 +1113,6 @@ impl<'a> ExtCtxt<'a> {
self.current_expansion.id.expansion_cause()
}
#[rustc_lint_diagnostics]
#[track_caller]
pub fn struct_span_err<S: Into<MultiSpan>>(
&self,
sp: S,
msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'a> {
self.sess.dcx().struct_span_err(sp, msg)
}
#[track_caller]
pub fn create_err(&self, err: impl IntoDiagnostic<'a>) -> DiagnosticBuilder<'a> {
self.sess.create_err(err)
}
#[track_caller]
pub fn emit_err(&self, err: impl IntoDiagnostic<'a>) -> ErrorGuaranteed {
self.sess.emit_err(err)
}
/// Emit `msg` attached to `sp`, without immediately stopping
/// compilation.
///
/// Compilation will be stopped in the near future (at the end of
/// the macro expansion phase).
#[rustc_lint_diagnostics]
#[track_caller]
pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) {
self.sess.dcx().span_err(sp, msg);
}
pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) -> ! {
self.sess.dcx().span_bug(sp, msg);
}
pub fn trace_macros_diag(&mut self) {
for (span, notes) in self.expansions.iter() {
let mut db = self.sess.parse_sess.create_note(errors::TraceMacro { span: *span });
@ -1156,10 +1124,6 @@ impl<'a> ExtCtxt<'a> {
// Fixme: does this result in errors?
self.expansions.clear();
}
#[rustc_lint_diagnostics]
pub fn bug(&self, msg: &'static str) -> ! {
self.sess.dcx().bug(msg);
}
pub fn trace_macros(&self) -> bool {
self.ecfg.trace_mac
}
@ -1236,7 +1200,7 @@ pub fn expr_to_spanned_string<'a>(
ast::ExprKind::Lit(token_lit) => match ast::LitKind::from_token_lit(token_lit) {
Ok(ast::LitKind::Str(s, style)) => return Ok((s, style, expr.span)),
Ok(ast::LitKind::ByteStr(..)) => {
let mut err = cx.struct_span_err(expr.span, err_msg);
let mut err = cx.dcx().struct_span_err(expr.span, err_msg);
let span = expr.span.shrink_to_lo();
err.span_suggestion(
span.with_hi(span.lo() + BytePos(1)),
@ -1251,10 +1215,10 @@ pub fn expr_to_spanned_string<'a>(
report_lit_error(&cx.sess.parse_sess, err, token_lit, expr.span);
None
}
_ => Some((cx.struct_span_err(expr.span, err_msg), false)),
_ => Some((cx.dcx().struct_span_err(expr.span, err_msg), false)),
},
ast::ExprKind::Err => None,
_ => Some((cx.struct_span_err(expr.span, err_msg), false)),
_ => Some((cx.dcx().struct_span_err(expr.span, err_msg), false)),
})
}
@ -1282,7 +1246,7 @@ pub fn expr_to_string(
/// (this should be done as rarely as possible).
pub fn check_zero_tts(cx: &ExtCtxt<'_>, span: Span, tts: TokenStream, name: &str) {
if !tts.is_empty() {
cx.emit_err(errors::TakesNoArguments { span, name });
cx.dcx().emit_err(errors::TakesNoArguments { span, name });
}
}
@ -1310,14 +1274,14 @@ pub fn get_single_str_from_tts(
) -> Option<Symbol> {
let mut p = cx.new_parser_from_tts(tts);
if p.token == token::Eof {
cx.emit_err(errors::OnlyOneArgument { span, name });
cx.dcx().emit_err(errors::OnlyOneArgument { span, name });
return None;
}
let ret = parse_expr(&mut p)?;
let _ = p.eat(&token::Comma);
if p.token != token::Eof {
cx.emit_err(errors::OnlyOneArgument { span, name });
cx.dcx().emit_err(errors::OnlyOneArgument { span, name });
}
expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s)
}
@ -1339,7 +1303,7 @@ pub fn get_exprs_from_tts(cx: &mut ExtCtxt<'_>, tts: TokenStream) -> Option<Vec<
continue;
}
if p.token != token::Eof {
cx.emit_err(errors::ExpectedCommaInList { span: p.token.span });
cx.dcx().emit_err(errors::ExpectedCommaInList { span: p.token.span });
return None;
}
}

View file

@ -513,7 +513,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
}
ExpandResult::Retry(invoc) => {
if force {
self.cx.span_bug(
self.cx.dcx().span_bug(
invoc.span(),
"expansion entered force mode but is still stuck",
);
@ -611,7 +611,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
limit => limit * 2,
};
self.cx.emit_err(RecursionLimitReached {
self.cx.dcx().emit_err(RecursionLimitReached {
span: expn_data.call_site,
descr: expn_data.kind.descr(),
suggested_limit,
@ -624,7 +624,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
/// A macro's expansion does not fit in this fragment kind.
/// For example, a non-type macro in a type position.
fn error_wrong_fragment_kind(&mut self, kind: AstFragmentKind, mac: &ast::MacCall, span: Span) {
self.cx.emit_err(WrongFragmentKind { span, kind: kind.name(), name: &mac.path });
self.cx.dcx().emit_err(WrongFragmentKind { span, kind: kind.name(), name: &mac.path });
self.cx.trace_macros_diag();
}
@ -702,7 +702,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
};
let attr_item = attr.unwrap_normal_item();
if let AttrArgs::Eq(..) = attr_item.args {
self.cx.emit_err(UnsupportedKeyValue { span });
self.cx.dcx().emit_err(UnsupportedKeyValue { span });
}
let inner_tokens = attr_item.args.inner_tokens();
let Ok(tok_result) = expander.expand(self.cx, span, inner_tokens, tokens)
@ -729,7 +729,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
AstFragmentKind::Expr | AstFragmentKind::MethodReceiverExpr
) && items.is_empty()
{
self.cx.emit_err(RemoveExprNotSupported { span });
self.cx.dcx().emit_err(RemoveExprNotSupported { span });
fragment_kind.dummy(span)
} else {
fragment_kind.expect_from_annotatables(items)
@ -1050,7 +1050,7 @@ trait InvocationCollectorNode: HasAttrs + HasNodeId + Sized {
_pos: usize,
span: Span,
) {
collector.cx.emit_err(RemoveNodeNotSupported { span, descr: Self::descr() });
collector.cx.dcx().emit_err(RemoveNodeNotSupported { span, descr: Self::descr() });
}
/// All of the names (items) declared by this node.

View file

@ -49,7 +49,7 @@ pub(super) fn failed_to_match_macro<'cx>(
let span = token.span.substitute_dummy(sp);
let mut err = cx.struct_span_err(span, parse_failure_msg(&token));
let mut err = cx.dcx().struct_span_err(span, parse_failure_msg(&token));
err.span_label(span, label);
if !def_span.is_dummy() && !cx.source_map().is_imported(def_span) {
err.span_label(cx.source_map().guess_head_span(def_span), "when calling this macro");
@ -177,7 +177,7 @@ impl<'a, 'cx, 'matcher> Tracker<'matcher> for CollectTrackerAndEmitter<'a, 'cx,
}
Error(err_sp, msg) => {
let span = err_sp.substitute_dummy(self.root_span);
self.cx.struct_span_err(span, msg.clone()).emit();
self.cx.dcx().struct_span_err(span, msg.clone()).emit();
self.result = Some(DummyResult::any(span));
}
ErrorReported(_) => self.result = Some(DummyResult::any(self.root_span)),

View file

@ -208,7 +208,7 @@ fn expand_macro<'cx>(
Ok((i, named_matches)) => {
let (rhs, rhs_span): (&mbe::Delimited, DelimSpan) = match &rhses[i] {
mbe::TokenTree::Delimited(span, _, delimited) => (&delimited, *span),
_ => cx.span_bug(sp, "malformed macro rhs"),
_ => cx.dcx().span_bug(sp, "malformed macro rhs"),
};
let arm_span = rhses[i].span();

View file

@ -185,7 +185,9 @@ pub(super) fn transcribe<'a>(
seq @ mbe::TokenTree::Sequence(_, delimited) => {
match lockstep_iter_size(seq, interp, &repeats) {
LockstepIterSize::Unconstrained => {
return Err(cx.create_err(NoSyntaxVarsExprRepeat { span: seq.span() }));
return Err(cx
.dcx()
.create_err(NoSyntaxVarsExprRepeat { span: seq.span() }));
}
LockstepIterSize::Contradiction(msg) => {
@ -193,7 +195,9 @@ pub(super) fn transcribe<'a>(
// happens when two meta-variables are used in the same repetition in a
// sequence, but they come from different sequence matchers and repeat
// different amounts.
return Err(cx.create_err(MetaVarsDifSeqMatchers { span: seq.span(), msg }));
return Err(cx
.dcx()
.create_err(MetaVarsDifSeqMatchers { span: seq.span(), msg }));
}
LockstepIterSize::Constraint(len, _) => {
@ -207,7 +211,9 @@ pub(super) fn transcribe<'a>(
// FIXME: this really ought to be caught at macro definition
// time... It happens when the Kleene operator in the matcher and
// the body for the same meta-variable do not match.
return Err(cx.create_err(MustRepeatOnce { span: sp.entire() }));
return Err(cx
.dcx()
.create_err(MustRepeatOnce { span: sp.entire() }));
}
} else {
// 0 is the initial counter (we have done 0 repetitions so far). `len`
@ -249,7 +255,7 @@ pub(super) fn transcribe<'a>(
}
MatchedSeq(..) => {
// We were unable to descend far enough. This is an error.
return Err(cx.create_err(VarStillRepeating { span: sp, ident }));
return Err(cx.dcx().create_err(VarStillRepeating { span: sp, ident }));
}
}
} else {
@ -501,7 +507,7 @@ fn count_repetitions<'a>(
}
if let MatchedTokenTree(_) | MatchedNonterminal(_) = matched {
return Err(cx.create_err(CountRepetitionMisplaced { span: sp.entire() }));
return Err(cx.dcx().create_err(CountRepetitionMisplaced { span: sp.entire() }));
}
count(cx, depth_user, depth_max, matched, sp)
@ -518,7 +524,7 @@ where
{
let span = ident.span;
let key = MacroRulesNormalizedIdent::new(ident);
interp.get(&key).ok_or_else(|| cx.create_err(MetaVarExprUnrecognizedVar { span, key }))
interp.get(&key).ok_or_else(|| cx.dcx().create_err(MetaVarExprUnrecognizedVar { span, key }))
}
/// Used by meta-variable expressions when an user input is out of the actual declared bounds. For
@ -540,7 +546,7 @@ fn out_of_bounds_err<'a>(
must be less than {max}"
)
};
cx.struct_span_err(span, msg)
cx.dcx().struct_span_err(span, msg)
}
fn transcribe_metavar_expr<'a>(

View file

@ -93,7 +93,7 @@ impl base::AttrProcMacro for AttrProcMacro {
let server = proc_macro_server::Rustc::new(ecx);
self.client.run(&strategy, server, annotation, annotated, proc_macro_backtrace).map_err(
|e| {
let mut err = ecx.struct_span_err(span, "custom attribute panicked");
let mut err = ecx.dcx().struct_span_err(span, "custom attribute panicked");
if let Some(s) = e.as_str() {
err.help(format!("message: {s}"));
}
@ -146,7 +146,7 @@ impl MultiItemModifier for DeriveProcMacro {
match self.client.run(&strategy, server, input, proc_macro_backtrace) {
Ok(stream) => stream,
Err(e) => {
let mut err = ecx.struct_span_err(span, "proc-macro derive panicked");
let mut err = ecx.dcx().struct_span_err(span, "proc-macro derive panicked");
if let Some(s) = e.as_str() {
err.help(format!("message: {s}"));
}
@ -156,7 +156,7 @@ impl MultiItemModifier for DeriveProcMacro {
}
};
let error_count_before = ecx.sess.dcx().err_count();
let error_count_before = ecx.dcx().err_count();
let mut parser =
rustc_parse::stream_to_parser(&ecx.sess.parse_sess, stream, Some("proc-macro derive"));
let mut items = vec![];
@ -179,7 +179,7 @@ impl MultiItemModifier for DeriveProcMacro {
}
// fail if there have been errors emitted
if ecx.sess.dcx().err_count() > error_count_before {
if ecx.dcx().err_count() > error_count_before {
ecx.sess.emit_err(errors::ProcMacroDeriveTokens { span });
}