Skip to content

Commit 6c4bda6

Browse files
authored
Rollup merge of #100730 - CleanCut:diagnostics-rustc_monomorphize, r=davidtwco
Migrate rustc_monomorphize to use SessionDiagnostic ### Description - Migrates diagnostics in `rustc_monomorphize` to use `SessionDiagnostic` - Adds an `impl IntoDiagnosticArg for PathBuf` ### TODO / Help! - [x] I'm having trouble figuring out how to apply an optional note. 😕 Help!? - Resolved. It was bad docs. Fixed in https://github.com/rust-lang/rustc-dev-guide/pull/1437/files - [x] `errors:RecursionLimit` should be `#[fatal ...]`, but that doesn't exist so it's `#[error ...]` at the moment. - Maybe I can switch after this is merged in? --> #100694 - Or maybe I need to manually implement `SessionDiagnostic` instead of deriving it? - [x] How does one go about converting an error inside of [a call to struct_span_lint_hir](https://github.com/rust-lang/rust/blob/8064a495086c2e63c0ef77e8e82fe3b9b5dc535f/compiler/rustc_monomorphize/src/collector.rs#L917-L927)? - [x] ~What placeholder do you use in the fluent template to refer to the value in a vector? It seems like [this code](https://github.com/rust-lang/rust/blob/0b79f758c9aa6646606662a6d623a0752286cd17/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs#L83-L114) ought to have the answer (or something near it)...but I can't figure it out.~ You can't. Punted.
2 parents 775e969 + 845d567 commit 6c4bda6

File tree

16 files changed

+196
-52
lines changed

16 files changed

+196
-52
lines changed

Cargo.lock

+2
Original file line numberDiff line numberDiff line change
@@ -3905,8 +3905,10 @@ name = "rustc_monomorphize"
39053905
version = "0.0.0"
39063906
dependencies = [
39073907
"rustc_data_structures",
3908+
"rustc_errors",
39083909
"rustc_hir",
39093910
"rustc_index",
3911+
"rustc_macros",
39103912
"rustc_middle",
39113913
"rustc_session",
39123914
"rustc_span",

compiler/rustc_codegen_cranelift/src/base.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -925,8 +925,11 @@ pub(crate) fn codegen_panic_inner<'tcx>(
925925
args: &[Value],
926926
span: Span,
927927
) {
928-
let def_id =
929-
fx.tcx.lang_items().require(lang_item).unwrap_or_else(|s| fx.tcx.sess.span_fatal(span, &s));
928+
let def_id = fx
929+
.tcx
930+
.lang_items()
931+
.require(lang_item)
932+
.unwrap_or_else(|e| fx.tcx.sess.span_fatal(span, e.to_string()));
930933

931934
let instance = Instance::mono(fx.tcx, def_id).polymorphize(fx.tcx);
932935
let symbol_name = fx.tcx.symbol_name(instance).name;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
monomorphize_recursion_limit =
2+
reached the recursion limit while instantiating `{$shrunk}`
3+
.note = `{$def_path_str}` defined here
4+
5+
monomorphize_written_to_path = the full type name has been written to '{$path}'
6+
7+
monomorphize_type_length_limit = reached the type-length limit while instantiating `{$shrunk}`
8+
9+
monomorphize_consider_type_length_limit =
10+
consider adding a `#![type_length_limit="{$type_length}"]` attribute to your crate
11+
12+
monomorphize_fatal_error = {$error_message}
13+
14+
monomorphize_unknown_partition_strategy = unknown partitioning strategy
15+
16+
monomorphize_symbol_already_defined = symbol `{$symbol}` is already defined
17+
18+
monomorphize_unused_generic_params = item has unused generic parameters
19+
20+
monomorphize_large_assignments =
21+
moving {$size} bytes
22+
.label = value moved from here
23+
.note = The current maximum size is {$limit}, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]`
24+
25+
monomorphize_requires_lang_item =
26+
requires `{$lang_item}` lang_item

compiler/rustc_error_messages/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ fluent_messages! {
4444
interface => "../locales/en-US/interface.ftl",
4545
infer => "../locales/en-US/infer.ftl",
4646
lint => "../locales/en-US/lint.ftl",
47+
monomorphize => "../locales/en-US/monomorphize.ftl",
4748
parser => "../locales/en-US/parser.ftl",
4849
passes => "../locales/en-US/passes.ftl",
4950
plugin_impl => "../locales/en-US/plugin_impl.ftl",

compiler/rustc_hir/src/errors.rs

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
use crate::LangItem;
2+
3+
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable)]
4+
pub struct LangItemError(pub LangItem);
5+
6+
impl ToString for LangItemError {
7+
fn to_string(&self) -> String {
8+
format!("requires `{}` lang_item", self.0.name())
9+
}
10+
}

compiler/rustc_hir/src/lang_items.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
//! * Functions called by the compiler itself.
99
1010
use crate::def_id::DefId;
11+
use crate::errors::LangItemError;
1112
use crate::{MethodKind, Target};
1213

1314
use rustc_ast as ast;
@@ -115,9 +116,9 @@ macro_rules! language_item_table {
115116

116117
/// Requires that a given `LangItem` was bound and returns the corresponding `DefId`.
117118
/// If it wasn't bound, e.g. due to a missing `#[lang = "<it.name()>"]`,
118-
/// returns an error message as a string.
119-
pub fn require(&self, it: LangItem) -> Result<DefId, String> {
120-
self.items[it as usize].ok_or_else(|| format!("requires `{}` lang_item", it.name()))
119+
/// returns an error encapsulating the `LangItem`.
120+
pub fn require(&self, it: LangItem) -> Result<DefId, LangItemError> {
121+
self.items[it as usize].ok_or_else(|| LangItemError(it))
121122
}
122123

123124
/// Returns the [`DefId`]s of all lang items in a group.

compiler/rustc_hir/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ pub mod def;
2727
pub mod def_path_hash_map;
2828
pub mod definitions;
2929
pub mod diagnostic_items;
30+
pub mod errors;
3031
pub use rustc_span::def_id;
3132
mod hir;
3233
pub mod hir_id;

compiler/rustc_middle/src/middle/lang_items.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,11 @@ impl<'tcx> TyCtxt<'tcx> {
1818
/// Returns the `DefId` for a given `LangItem`.
1919
/// If not found, fatally aborts compilation.
2020
pub fn require_lang_item(self, lang_item: LangItem, span: Option<Span>) -> DefId {
21-
self.lang_items().require(lang_item).unwrap_or_else(|msg| {
21+
self.lang_items().require(lang_item).unwrap_or_else(|err| {
2222
if let Some(span) = span {
23-
self.sess.span_fatal(span, &msg)
23+
self.sess.span_fatal(span, err.to_string())
2424
} else {
25-
self.sess.fatal(&msg)
25+
self.sess.fatal(err.to_string())
2626
}
2727
})
2828
}

compiler/rustc_monomorphize/Cargo.toml

+3-1
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,13 @@ edition = "2021"
77
doctest = false
88

99
[dependencies]
10-
smallvec = { version = "1.8.1", features = ["union", "may_dangle"] }
10+
smallvec = { version = "1.8.1", features = [ "union", "may_dangle" ] }
1111
tracing = "0.1"
1212
rustc_data_structures = { path = "../rustc_data_structures" }
13+
rustc_errors = { path = "../rustc_errors" }
1314
rustc_hir = { path = "../rustc_hir" }
1415
rustc_index = { path = "../rustc_index" }
16+
rustc_macros = { path = "../rustc_macros" }
1517
rustc_middle = { path = "../rustc_middle" }
1618
rustc_session = { path = "../rustc_session" }
1719
rustc_span = { path = "../rustc_span" }

compiler/rustc_monomorphize/src/collector.rs

+39-28
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,8 @@ use std::iter;
207207
use std::ops::Range;
208208
use std::path::PathBuf;
209209

210+
use crate::errors::{LargeAssignmentsLint, RecursionLimit, RequiresLangItem, TypeLengthLimit};
211+
210212
#[derive(PartialEq)]
211213
pub enum MonoItemCollectionMode {
212214
Eager,
@@ -604,17 +606,24 @@ fn check_recursion_limit<'tcx>(
604606
// more than the recursion limit is assumed to be causing an
605607
// infinite expansion.
606608
if !recursion_limit.value_within_limit(adjusted_recursion_depth) {
609+
let def_span = tcx.def_span(def_id);
610+
let def_path_str = tcx.def_path_str(def_id);
607611
let (shrunk, written_to_path) = shrunk_instance_name(tcx, &instance, 32, 32);
608-
let error = format!("reached the recursion limit while instantiating `{}`", shrunk);
609-
let mut err = tcx.sess.struct_span_fatal(span, &error);
610-
err.span_note(
611-
tcx.def_span(def_id),
612-
&format!("`{}` defined here", tcx.def_path_str(def_id)),
613-
);
614-
if let Some(path) = written_to_path {
615-
err.note(&format!("the full type name has been written to '{}'", path.display()));
616-
}
617-
err.emit()
612+
let mut path = PathBuf::new();
613+
let was_written = if written_to_path.is_some() {
614+
path = written_to_path.unwrap();
615+
Some(())
616+
} else {
617+
None
618+
};
619+
tcx.sess.emit_fatal(RecursionLimit {
620+
span,
621+
shrunk,
622+
def_span,
623+
def_path_str,
624+
was_written,
625+
path,
626+
});
618627
}
619628

620629
recursion_depths.insert(def_id, recursion_depth + 1);
@@ -642,16 +651,15 @@ fn check_type_length_limit<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) {
642651
// Bail out in these cases to avoid that bad user experience.
643652
if !tcx.type_length_limit().value_within_limit(type_length) {
644653
let (shrunk, written_to_path) = shrunk_instance_name(tcx, &instance, 32, 32);
645-
let msg = format!("reached the type-length limit while instantiating `{}`", shrunk);
646-
let mut diag = tcx.sess.struct_span_fatal(tcx.def_span(instance.def_id()), &msg);
647-
if let Some(path) = written_to_path {
648-
diag.note(&format!("the full type name has been written to '{}'", path.display()));
649-
}
650-
diag.help(&format!(
651-
"consider adding a `#![type_length_limit=\"{}\"]` attribute to your crate",
652-
type_length
653-
));
654-
diag.emit()
654+
let span = tcx.def_span(instance.def_id());
655+
let mut path = PathBuf::new();
656+
let was_written = if written_to_path.is_some() {
657+
path = written_to_path.unwrap();
658+
Some(())
659+
} else {
660+
None
661+
};
662+
tcx.sess.emit_fatal(TypeLengthLimit { span, shrunk, was_written, path, type_length });
655663
}
656664
}
657665

@@ -914,17 +922,16 @@ impl<'a, 'tcx> MirVisitor<'tcx> for MirNeighborCollector<'a, 'tcx> {
914922
// but correct span? This would make the lint at least accept crate-level lint attributes.
915923
return;
916924
};
917-
self.tcx.struct_span_lint_hir(
925+
self.tcx.emit_spanned_lint(
918926
LARGE_ASSIGNMENTS,
919927
lint_root,
920928
source_info.span,
921-
|lint| {
922-
let mut err = lint.build(&format!("moving {} bytes", layout.size.bytes()));
923-
err.span_label(source_info.span, "value moved from here");
924-
err.note(&format!(r#"The current maximum size is {}, but it can be customized with the move_size_limit attribute: `#![move_size_limit = "..."]`"#, limit.bytes()));
925-
err.emit();
929+
LargeAssignmentsLint {
930+
span: source_info.span,
931+
size: layout.size.bytes(),
932+
limit: limit.bytes(),
926933
},
927-
);
934+
)
928935
}
929936
}
930937
}
@@ -1321,7 +1328,11 @@ impl<'v> RootCollector<'_, 'v> {
13211328

13221329
let start_def_id = match self.tcx.lang_items().require(LangItem::Start) {
13231330
Ok(s) => s,
1324-
Err(err) => self.tcx.sess.fatal(&err),
1331+
Err(lang_item_err) => {
1332+
self.tcx
1333+
.sess
1334+
.emit_fatal(RequiresLangItem { lang_item: lang_item_err.0.name().to_string() });
1335+
}
13251336
};
13261337
let main_ret_ty = self.tcx.fn_sig(main_def_id).output();
13271338

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
use std::path::PathBuf;
2+
3+
use rustc_errors::ErrorGuaranteed;
4+
use rustc_macros::{LintDiagnostic, SessionDiagnostic};
5+
use rustc_session::SessionDiagnostic;
6+
use rustc_span::Span;
7+
8+
#[derive(SessionDiagnostic)]
9+
#[diag(monomorphize::recursion_limit)]
10+
pub struct RecursionLimit {
11+
#[primary_span]
12+
pub span: Span,
13+
pub shrunk: String,
14+
#[note]
15+
pub def_span: Span,
16+
pub def_path_str: String,
17+
#[note(monomorphize::written_to_path)]
18+
pub was_written: Option<()>,
19+
pub path: PathBuf,
20+
}
21+
22+
#[derive(SessionDiagnostic)]
23+
#[diag(monomorphize::type_length_limit)]
24+
#[help(monomorphize::consider_type_length_limit)]
25+
pub struct TypeLengthLimit {
26+
#[primary_span]
27+
pub span: Span,
28+
pub shrunk: String,
29+
#[note(monomorphize::written_to_path)]
30+
pub was_written: Option<()>,
31+
pub path: PathBuf,
32+
pub type_length: usize,
33+
}
34+
35+
#[derive(SessionDiagnostic)]
36+
#[diag(monomorphize::requires_lang_item)]
37+
pub struct RequiresLangItem {
38+
pub lang_item: String,
39+
}
40+
41+
pub struct UnusedGenericParams {
42+
pub span: Span,
43+
pub param_spans: Vec<Span>,
44+
pub param_names: Vec<String>,
45+
}
46+
47+
impl SessionDiagnostic<'_> for UnusedGenericParams {
48+
fn into_diagnostic(
49+
self,
50+
sess: &'_ rustc_session::parse::ParseSess,
51+
) -> rustc_errors::DiagnosticBuilder<'_, ErrorGuaranteed> {
52+
let mut diag = sess.struct_err(rustc_errors::fluent::monomorphize::unused_generic_params);
53+
diag.set_span(self.span);
54+
for (span, name) in self.param_spans.into_iter().zip(self.param_names) {
55+
// FIXME: I can figure out how to do a label with a fluent string with a fixed message,
56+
// or a label with a dynamic value in a hard-coded string, but I haven't figured out
57+
// how to combine the two. 😢
58+
diag.span_label(span, format!("generic parameter `{}` is unused", name));
59+
}
60+
diag
61+
}
62+
}
63+
64+
#[derive(LintDiagnostic)]
65+
#[diag(monomorphize::large_assignments)]
66+
#[note]
67+
pub struct LargeAssignmentsLint {
68+
#[label]
69+
pub span: Span,
70+
pub size: u64,
71+
pub limit: u64,
72+
}
73+
74+
#[derive(SessionDiagnostic)]
75+
#[diag(monomorphize::unknown_partition_strategy)]
76+
pub struct UnknownPartitionStrategy;
77+
78+
#[derive(SessionDiagnostic)]
79+
#[diag(monomorphize::symbol_already_defined)]
80+
pub struct SymbolAlreadyDefined {
81+
#[primary_span]
82+
pub span: Option<Span>,
83+
pub symbol: String,
84+
}

compiler/rustc_monomorphize/src/lib.rs

+3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
#![feature(let_else)]
44
#![recursion_limit = "256"]
55
#![allow(rustc::potential_query_instability)]
6+
#![deny(rustc::untranslatable_diagnostic)]
7+
#![deny(rustc::diagnostic_outside_of_impl)]
68

79
#[macro_use]
810
extern crate tracing;
@@ -16,6 +18,7 @@ use rustc_middle::ty::query::Providers;
1618
use rustc_middle::ty::{self, Ty, TyCtxt};
1719

1820
mod collector;
21+
mod errors;
1922
mod partitioning;
2023
mod polymorphize;
2124
mod util;

compiler/rustc_monomorphize/src/partitioning/mod.rs

+5-8
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ use rustc_span::symbol::Symbol;
108108

109109
use crate::collector::InliningMap;
110110
use crate::collector::{self, MonoItemCollectionMode};
111+
use crate::errors::{SymbolAlreadyDefined, UnknownPartitionStrategy};
111112

112113
pub struct PartitioningCx<'a, 'tcx> {
113114
tcx: TyCtxt<'tcx>,
@@ -149,7 +150,9 @@ fn get_partitioner<'tcx>(tcx: TyCtxt<'tcx>) -> Box<dyn Partitioner<'tcx>> {
149150

150151
match strategy {
151152
"default" => Box::new(default::DefaultPartitioning),
152-
_ => tcx.sess.fatal("unknown partitioning strategy"),
153+
_ => {
154+
tcx.sess.emit_fatal(UnknownPartitionStrategy);
155+
}
153156
}
154157
}
155158

@@ -331,13 +334,7 @@ where
331334
(span1, span2) => span1.or(span2),
332335
};
333336

334-
let error_message = format!("symbol `{}` is already defined", sym1);
335-
336-
if let Some(span) = span {
337-
tcx.sess.span_fatal(span, &error_message)
338-
} else {
339-
tcx.sess.fatal(&error_message)
340-
}
337+
tcx.sess.emit_fatal(SymbolAlreadyDefined { span, symbol: sym1.to_string() });
341338
}
342339
}
343340
}

0 commit comments

Comments
 (0)