Skip to content

Commit 46c8b80

Browse files
committed
more cleanup on diags
1 parent ce78bfb commit 46c8b80

File tree

9 files changed

+60
-107
lines changed

9 files changed

+60
-107
lines changed

compiler/rustc_errors/Cargo.toml

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ edition = "2021"
77
# tidy-alphabetical-start
88
annotate-snippets = "0.9"
99
derive_setters = "0.1.6"
10+
fluent = "0.16.0"
1011
rustc_ast = { path = "../rustc_ast" }
1112
rustc_ast_pretty = { path = "../rustc_ast_pretty" }
1213
rustc_data_structures = { path = "../rustc_data_structures" }
@@ -24,10 +25,8 @@ serde_json = "1.0.59"
2425
termcolor = "1.2.0"
2526
termize = "0.1.1"
2627
tracing = "0.1"
27-
unicode-width = "0.1.4"
28-
fluent = "0.16.0"
2928
unic-langid = {version = "0.9.1", features = ["unic-langid-macros"]}
30-
29+
unicode-width = "0.1.4"
3130
# tidy-alphabetical-end
3231

3332
[target.'cfg(windows)'.dependencies.windows]

compiler/rustc_errors/src/translation.rs

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -68,23 +68,19 @@ pub trait Translate {
6868
if args.iter().next().is_none() || (!msg.contains("$") && !msg.contains("`{")) {
6969
return Ok(Cow::Borrowed(msg));
7070
} else {
71-
// FIXME(yukang) A hacky for raw fluent content
71+
// FIXME(yukang): A hack for raw fluent content for new diagnostics proc format
7272
let fluent_text = format!("dummy = {}", msg);
7373
if let Ok(resource) = FluentResource::try_new(fluent_text) {
74-
let langid_en = langid!("en-US");
75-
let mut bundle = RawFluentBundle::new(vec![langid_en]);
74+
let mut bundle = RawFluentBundle::new(vec![langid!("en-US")]);
7675
bundle.add_resource(resource).unwrap();
7776
let mut errors = vec![];
7877
let pattern = bundle.get_message("dummy").unwrap().value().unwrap();
7978
let res = bundle.format_pattern(&pattern, Some(args), &mut errors);
80-
//eprintln!("translated: {:?}", msg);
81-
//eprintln!("args: {:?}", args);
82-
//eprintln!("res: {:?}", res);
8379
return Ok(Cow::Owned(
8480
res.to_string().replace("\u{2068}", "").replace("\u{2069}", ""),
8581
));
8682
} else {
87-
//eprintln!("translate error: {}, args: {:?}", msg, args);
83+
// If the message is not a valid Fluent resource, just return the original
8884
return Ok(Cow::Borrowed(msg));
8985
}
9086
}

compiler/rustc_macros/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ proc-macro = true
1010
# tidy-alphabetical-start
1111
proc-macro2 = "1"
1212
quote = "1"
13+
regex = "1.3.3"
1314
syn = { version = "2.0.9", features = ["full"] }
1415
synstructure = "0.13.0"
15-
regex = "1.3.3"
1616
# tidy-alphabetical-end

compiler/rustc_macros/src/diagnostics/diagnostic.rs

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ impl<'a> DiagnosticDerive<'a> {
4949
return DiagnosticDeriveError::ErrorHandled.to_compile_error();
5050
}
5151
(Some(slug), None) => {
52+
slugs.borrow_mut().push(slug.clone());
5253
quote! {
5354
let mut diag = rustc_errors::DiagnosticBuilder::new(
5455
dcx,
@@ -57,13 +58,13 @@ impl<'a> DiagnosticDerive<'a> {
5758
);
5859
}
5960
}
60-
(None, Some(text)) => {
61+
(None, Some(raw_label)) => {
6162
quote! {
62-
let mut #diag = #handler.struct_diagnostic(DiagnosticMessage::Str(#text.into()));
63+
let mut #diag = #handler.struct_diagnostic(DiagnosticMessage::Str(#raw_label.into()));
6364
}
6465
}
65-
(Some(_slug), Some(_text)) => {
66-
unreachable!("BUG: slug and text specified");
66+
(Some(_slug), Some(_raw_label)) => {
67+
unreachable!("BUG: slug and raw label specified");
6768
}
6869
};
6970

@@ -77,10 +78,20 @@ impl<'a> DiagnosticDerive<'a> {
7778
}
7879
});
7980

81+
<<<<<<< HEAD
8082
// A lifetime of `'a` causes conflicts, but `_sess` is fine.
8183
let mut imp = structure.gen_impl(quote! {
8284
gen impl<'_sess, G>
8385
rustc_errors::IntoDiagnostic<'_sess, G>
86+
=======
87+
let DiagnosticDeriveKind::Diagnostic { handler } = &builder.kind else {
88+
unreachable!();
89+
};
90+
91+
let mut imp = structure.gen_impl(quote! {
92+
gen impl<'__diagnostic_handler_sess, G>
93+
rustc_errors::IntoDiagnostic<'__diagnostic_handler_sess, G>
94+
>>>>>>> bd3289ea826 (more cleanup on diags)
8495
for @Self
8596
where G: rustc_errors::EmissionGuarantee
8697
{
@@ -95,6 +106,10 @@ impl<'a> DiagnosticDerive<'a> {
95106
}
96107
}
97108
});
109+
110+
for test in slugs.borrow().iter().map(|s| generate_test(s, &structure)) {
111+
imp.extend(test);
112+
}
98113
imp
99114
}
100115
}

compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs

Lines changed: 21 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,13 @@ use super::utils::{convert_to_litstr, SubdiagnosticVariant};
44
use crate::diagnostics::error::{
55
span_err, throw_invalid_attr, throw_span_err, DiagnosticDeriveError,
66
};
7-
//use crate::diagnostics::utils::format_for_variables;
87
use crate::diagnostics::utils::{
98
build_field_mapping, is_doc_comment, report_error_if_not_applied_to_span, report_type_error,
109
should_generate_set_arg, type_is_bool, type_is_unit, type_matches_path, FieldInfo,
1110
FieldInnerTy, FieldMap, HasFieldMap, SetOnce, SpannedOption, SubdiagnosticKind,
1211
};
1312
use proc_macro2::{Ident, Span, TokenStream, TokenTree};
14-
use quote::{format_ident, quote, quote_spanned, ToTokens};
13+
use quote::{format_ident, quote, quote_spanned};
1514
use std::collections::HashMap;
1615
use syn::MetaList;
1716
use syn::Token;
@@ -56,9 +55,6 @@ pub(crate) struct DiagnosticDeriveVariantBuilder {
5655

5756
/// Attributes on the variant.
5857
pub attrs: HashMap<String, LitStr>,
59-
60-
/// fields for bidnings in the variant.
61-
pub fields: FieldMap,
6258
}
6359

6460
impl HasFieldMap for DiagnosticDeriveVariantBuilder {
@@ -111,7 +107,6 @@ impl DiagnosticDeriveKind {
111107
code: None,
112108
label: None,
113109
attrs: HashMap::new(),
114-
fields: HashMap::new(),
115110
};
116111
f(builder, variant)
117112
});
@@ -130,9 +125,6 @@ impl DiagnosticDeriveVariantBuilder {
130125
pub(crate) fn preamble(&mut self, variant: &VariantInfo<'_>) -> TokenStream {
131126
let ast = variant.ast();
132127
let attrs = &ast.attrs;
133-
for binding in variant.bindings().iter().filter(|bi| should_generate_set_arg(bi.ast())) {
134-
self.generate_binding_for_attr(binding);
135-
}
136128

137129
let preamble = attrs.iter().map(|attr| {
138130
self.generate_structure_code_for_attr(attr).unwrap_or_else(|v| v.to_compile_error())
@@ -183,7 +175,7 @@ impl DiagnosticDeriveVariantBuilder {
183175
SubdiagnosticKind::MultipartSuggestion { .. } => unreachable!(),
184176
});
185177

186-
Ok(Some((subdiag.kind, slug, subdiag.no_span, subdiag.text.map(|t| t.value()))))
178+
Ok(Some((subdiag.kind, slug, subdiag.no_span, subdiag.raw_label.map(|t| t.value()))))
187179
}
188180

189181
/// Establishes state in the `DiagnosticDeriveBuilder` resulting from the struct
@@ -271,7 +263,7 @@ impl DiagnosticDeriveVariantBuilder {
271263
return Ok(());
272264
};
273265

274-
if path.is_ident("text") || path.is_ident("label") {
266+
if path.is_ident("label") {
275267
let value = nested.parse::<syn::LitStr>()?;
276268
self.label.set_once(value, path.span().unwrap());
277269
} else if path.is_ident("code") {
@@ -302,15 +294,15 @@ impl DiagnosticDeriveVariantBuilder {
302294
return Ok(tokens);
303295
}
304296

305-
let Some((subdiag, slug, _no_span, text)) = self.parse_subdiag_attribute(attr)? else {
297+
let Some((subdiag, slug, _no_span, raw_label)) = self.parse_subdiag_attribute(attr)? else {
306298
// Some attributes aren't errors - like documentation comments - but also aren't
307299
// subdiagnostics.
308300
return Ok(quote! {});
309301
};
310302
let fn_ident = format_ident!("{}", subdiag);
311303
match subdiag {
312304
SubdiagnosticKind::Note | SubdiagnosticKind::Help | SubdiagnosticKind::Warn => {
313-
Ok(self.add_subdiagnostic(&fn_ident, slug, text))
305+
Ok(self.add_subdiagnostic(&fn_ident, slug, raw_label))
314306
}
315307
SubdiagnosticKind::Label | SubdiagnosticKind::Suggestion { .. } => {
316308
throw_invalid_attr!(attr, |diag| diag
@@ -335,16 +327,6 @@ impl DiagnosticDeriveVariantBuilder {
335327
}
336328
}
337329

338-
fn generate_binding_for_attr(&mut self, binding_info: &BindingInfo<'_>) {
339-
let field = binding_info.ast();
340-
let mut field_binding = binding_info.binding.clone();
341-
field_binding.set_span(field.ty.span());
342-
343-
let ident = field.ident.as_ref().unwrap();
344-
let ident = format_ident!("{}", ident); // strip `r#` prefix, if present
345-
self.fields.insert(ident.to_string(), field_binding.into_token_stream());
346-
}
347-
348330
fn generate_field_attrs_code(&mut self, binding_info: &BindingInfo<'_>) -> TokenStream {
349331
let field = binding_info.ast();
350332
let field_binding = &binding_info.binding;
@@ -458,7 +440,7 @@ impl DiagnosticDeriveVariantBuilder {
458440
_ => (),
459441
}
460442

461-
let Some((subdiag, slug, _no_span, text)) = self.parse_subdiag_attribute(attr)? else {
443+
let Some((subdiag, slug, _no_span, raw_label)) = self.parse_subdiag_attribute(attr)? else {
462444
// Some attributes aren't errors - like documentation comments - but also aren't
463445
// subdiagnostics.
464446
return Ok(quote! {});
@@ -467,18 +449,18 @@ impl DiagnosticDeriveVariantBuilder {
467449
match subdiag {
468450
SubdiagnosticKind::Label => {
469451
report_error_if_not_applied_to_span(attr, &info)?;
470-
Ok(self.add_spanned_subdiagnostic(binding, &fn_ident, slug, text))
452+
Ok(self.add_spanned_subdiagnostic(binding, &fn_ident, slug, raw_label))
471453
}
472454
SubdiagnosticKind::Note | SubdiagnosticKind::Help | SubdiagnosticKind::Warn => {
473455
let inner = info.ty.inner_type();
474456
if type_matches_path(inner, &["rustc_span", "Span"])
475457
|| type_matches_path(inner, &["rustc_span", "MultiSpan"])
476458
{
477-
Ok(self.add_spanned_subdiagnostic(binding, &fn_ident, slug, text))
459+
Ok(self.add_spanned_subdiagnostic(binding, &fn_ident, slug, raw_label))
478460
} else if type_is_unit(inner)
479461
|| (matches!(info.ty, FieldInnerTy::Plain(_)) && type_is_bool(inner))
480462
{
481-
Ok(self.add_subdiagnostic(&fn_ident, slug, text))
463+
Ok(self.add_subdiagnostic(&fn_ident, slug, raw_label))
482464
} else {
483465
report_type_error(attr, "`Span`, `MultiSpan`, `bool` or `()`")?
484466
}
@@ -509,10 +491,9 @@ impl DiagnosticDeriveVariantBuilder {
509491
.unwrap_or_else(|| quote! { rustc_errors::Applicability::Unspecified });
510492
let style = suggestion_kind.to_suggestion_style();
511493

512-
let suggestion_label = if let Some(text) = text {
513-
//let text = format_for_variables(&text, &self.fields);
494+
let suggestion_label = if let Some(raw_label) = raw_label {
514495
quote! {
515-
#text
496+
#raw_label
516497
}
517498
} else {
518499
quote! {
@@ -542,23 +523,22 @@ impl DiagnosticDeriveVariantBuilder {
542523
field_binding: TokenStream,
543524
kind: &Ident,
544525
fluent_attr_identifier: Path,
545-
text: Option<String>,
526+
raw_label: Option<String>,
546527
) -> TokenStream {
547528
let fn_name = format_ident!("span_{}", kind);
548-
if let Some(text) = text {
549-
//let text = format_for_variables(&text, &self.fields);
529+
if let Some(raw_label) = raw_label {
550530
return quote! {
551531
#diag.#fn_name(
552532
#field_binding,
553-
#text
533+
#raw_label
554534
);
555535
};
556536
}
557-
if let Some(text) = self.get_attr(kind.to_string().as_str()) {
537+
if let Some(raw_label) = self.get_attr(kind.to_string().as_str()) {
558538
quote! {
559539
#diag.#fn_name(
560540
#field_binding,
561-
#text
541+
#raw_label
562542
);
563543
}
564544
} else {
@@ -577,22 +557,17 @@ impl DiagnosticDeriveVariantBuilder {
577557
&self,
578558
kind: &Ident,
579559
fluent_attr_identifier: Path,
580-
text: Option<String>,
560+
raw_label: Option<String>,
581561
) -> TokenStream {
582562
let diag = &self.parent.diag;
583-
// eprintln!(
584-
// "add_subdiagnostic fluent_attr_identifier: {:?} text: {:?}",
585-
// fluent_attr_identifier, text
586-
// );
587-
if let Some(text) = text {
588-
//let text = format_for_variables(&text, &self.fields);
563+
if let Some(raw_label) = raw_label {
589564
return quote! {
590-
#diag.#kind(#text);
565+
#diag.#kind(#raw_label);
591566
};
592567
}
593-
if let Some(text) = self.get_attr(kind.to_string().as_str()) {
568+
if let Some(raw_label) = self.get_attr(kind.to_string().as_str()) {
594569
quote! {
595-
#diag.#kind(#text);
570+
#diag.#kind(#raw_label);
596571
}
597572
} else {
598573
quote! {
@@ -660,7 +635,6 @@ impl DiagnosticDeriveVariantBuilder {
660635

661636
fn get_attr(&self, key: &str) -> Option<TokenStream> {
662637
self.attrs.get(key).map(|val| {
663-
//let text = format_for_variables(&val.value(), &self.fields);
664638
let text = &val.value();
665639
quote! {
666640
#text

compiler/rustc_macros/src/diagnostics/subdiagnostic.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -189,30 +189,30 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> {
189189
let mut kind_slugs = vec![];
190190

191191
for attr in self.variant.ast().attrs {
192-
let Some(SubdiagnosticVariant { kind, slug, no_span, text }) =
192+
let Some(SubdiagnosticVariant { kind, slug, no_span, raw_label }) =
193193
SubdiagnosticVariant::from_attr(attr, self)?
194194
else {
195195
// Some attributes aren't errors - like documentation comments - but also aren't
196196
// subdiagnostics.
197197
continue;
198198
};
199199

200-
match (&slug, &text) {
200+
match (&slug, &raw_label) {
201201
(None, None) => {
202202
throw_span_err!(
203203
attr.span().unwrap(),
204-
"diagnostic slug or text must be first argument of a `#[{name}(...)]` attribute"
204+
"diagnostic slug or raw_label must be first argument of a `#[{name}(...)]` attribute"
205205
);
206206
}
207207
(Some(_), Some(_)) => {
208208
throw_span_err!(
209209
attr.span().unwrap(),
210-
"diagnostic slug and text cannot both be specified"
210+
"diagnostic slug and raw_label cannot both be specified"
211211
);
212212
}
213213
_ => (),
214214
}
215-
kind_slugs.push((kind, slug, no_span, text));
215+
kind_slugs.push((kind, slug, no_span, raw_label));
216216
}
217217

218218
Ok(kind_slugs)
@@ -519,14 +519,14 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> {
519519
let diag = &self.parent.diag;
520520
let f = &self.parent.f;
521521
let mut calls = TokenStream::new();
522-
for (kind, slug, no_span, text) in kind_slugs {
522+
for (kind, slug, no_span, raw_label) in kind_slugs {
523523
let message = format_ident!("__message");
524524
if let Some(slug) = slug {
525525
calls.extend(
526526
quote! { let #message = #f(#diag, crate::fluent_generated::#slug.into()); },
527527
);
528528
} else {
529-
calls.extend(quote! { let #message = #f(#diag, #text.into()); });
529+
calls.extend(quote! { let #message = #f(#diag, #raw_label.into()); });
530530
}
531531

532532
let name = format_ident!(

0 commit comments

Comments
 (0)