Skip to content

Commit 714a940

Browse files
committed
more cleanup on diags
1 parent 8752ce9 commit 714a940

File tree

9 files changed

+52
-108
lines changed

9 files changed

+52
-108
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: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ impl<'a> DiagnosticDerive<'a> {
3030
pub(crate) fn into_tokens(self) -> TokenStream {
3131
let DiagnosticDerive { mut structure, mut builder } = self;
3232

33+
let slugs = RefCell::new(Vec::new());
3334
let implementation = builder.each_variant(&mut structure, |mut builder, variant| {
3435
let diag = &builder.parent.diag;
3536
let DiagnosticDeriveKind::Diagnostic { handler } = &builder.parent.kind else {
@@ -61,17 +62,18 @@ impl<'a> DiagnosticDerive<'a> {
6162
return DiagnosticDeriveError::ErrorHandled.to_compile_error();
6263
}
6364
(Some(slug), None) => {
65+
slugs.borrow_mut().push(slug.clone());
6466
quote! {
6567
let mut #diag = #handler.struct_diagnostic(crate::fluent_generated::#slug);
6668
}
6769
}
68-
(None, Some(text)) => {
70+
(None, Some(raw_label)) => {
6971
quote! {
70-
let mut #diag = #handler.struct_diagnostic(DiagnosticMessage::Str(#text.into()));
72+
let mut #diag = #handler.struct_diagnostic(DiagnosticMessage::Str(#raw_label.into()));
7173
}
7274
}
73-
(Some(_slug), Some(_text)) => {
74-
unreachable!("BUG: slug and text specified");
75+
(Some(_slug), Some(_raw_label)) => {
76+
unreachable!("BUG: slug and raw label specified");
7577
}
7678
};
7779

@@ -89,7 +91,7 @@ impl<'a> DiagnosticDerive<'a> {
8991
unreachable!();
9092
};
9193

92-
let imp = structure.gen_impl(quote! {
94+
let mut imp = structure.gen_impl(quote! {
9395
gen impl<'__diagnostic_handler_sess, G>
9496
rustc_errors::IntoDiagnostic<'__diagnostic_handler_sess, G>
9597
for @Self
@@ -106,6 +108,10 @@ impl<'a> DiagnosticDerive<'a> {
106108
}
107109
}
108110
});
111+
112+
for test in slugs.borrow().iter().map(|s| generate_test(s, &structure)) {
113+
imp.extend(test);
114+
}
109115
imp
110116
}
111117
}

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;
@@ -66,9 +65,6 @@ pub(crate) struct DiagnosticDeriveVariantBuilder<'parent> {
6665

6766
/// Attributes on the variant.
6867
pub attrs: HashMap<String, LitStr>,
69-
70-
/// fields for bidnings in the variant.
71-
pub fields: FieldMap,
7268
}
7369

7470
impl<'a> HasFieldMap for DiagnosticDeriveVariantBuilder<'a> {
@@ -121,7 +117,6 @@ impl DiagnosticDeriveBuilder {
121117
code: None,
122118
label: None,
123119
attrs: HashMap::new(),
124-
fields: HashMap::new(),
125120
};
126121
f(builder, variant)
127122
});
@@ -140,9 +135,6 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> {
140135
pub fn preamble(&mut self, variant: &VariantInfo<'_>) -> TokenStream {
141136
let ast = variant.ast();
142137
let attrs = &ast.attrs;
143-
for binding in variant.bindings().iter().filter(|bi| should_generate_set_arg(bi.ast())) {
144-
self.generate_binding_for_attr(binding);
145-
}
146138

147139
let preamble = attrs.iter().map(|attr| {
148140
self.generate_structure_code_for_attr(attr).unwrap_or_else(|v| v.to_compile_error())
@@ -193,7 +185,7 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> {
193185
SubdiagnosticKind::MultipartSuggestion { .. } => unreachable!(),
194186
});
195187

196-
Ok(Some((subdiag.kind, slug, subdiag.no_span, subdiag.text.map(|t| t.value()))))
188+
Ok(Some((subdiag.kind, slug, subdiag.no_span, subdiag.raw_label.map(|t| t.value()))))
197189
}
198190

199191
/// Establishes state in the `DiagnosticDeriveBuilder` resulting from the struct
@@ -283,7 +275,7 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> {
283275
return Ok(());
284276
};
285277

286-
if path.is_ident("text") || path.is_ident("label") {
278+
if path.is_ident("label") {
287279
let value = nested.parse::<syn::LitStr>()?;
288280
self.label.set_once(value, path.span().unwrap());
289281
} else if path.is_ident("code") {
@@ -314,15 +306,15 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> {
314306
return Ok(tokens);
315307
}
316308

317-
let Some((subdiag, slug, _no_span, text)) = self.parse_subdiag_attribute(attr)? else {
309+
let Some((subdiag, slug, _no_span, raw_label)) = self.parse_subdiag_attribute(attr)? else {
318310
// Some attributes aren't errors - like documentation comments - but also aren't
319311
// subdiagnostics.
320312
return Ok(quote! {});
321313
};
322314
let fn_ident = format_ident!("{}", subdiag);
323315
match subdiag {
324316
SubdiagnosticKind::Note | SubdiagnosticKind::Help | SubdiagnosticKind::Warn => {
325-
Ok(self.add_subdiagnostic(&fn_ident, slug, text))
317+
Ok(self.add_subdiagnostic(&fn_ident, slug, raw_label))
326318
}
327319
SubdiagnosticKind::Label | SubdiagnosticKind::Suggestion { .. } => {
328320
throw_invalid_attr!(attr, |diag| diag
@@ -349,16 +341,6 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> {
349341
}
350342
}
351343

352-
fn generate_binding_for_attr(&mut self, binding_info: &BindingInfo<'_>) {
353-
let field = binding_info.ast();
354-
let mut field_binding = binding_info.binding.clone();
355-
field_binding.set_span(field.ty.span());
356-
357-
let ident = field.ident.as_ref().unwrap();
358-
let ident = format_ident!("{}", ident); // strip `r#` prefix, if present
359-
self.fields.insert(ident.to_string(), field_binding.into_token_stream());
360-
}
361-
362344
fn generate_field_attrs_code(&mut self, binding_info: &BindingInfo<'_>) -> TokenStream {
363345
let field = binding_info.ast();
364346
let field_binding = &binding_info.binding;
@@ -474,7 +456,7 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> {
474456
_ => (),
475457
}
476458

477-
let Some((subdiag, slug, _no_span, text)) = self.parse_subdiag_attribute(attr)? else {
459+
let Some((subdiag, slug, _no_span, raw_label)) = self.parse_subdiag_attribute(attr)? else {
478460
// Some attributes aren't errors - like documentation comments - but also aren't
479461
// subdiagnostics.
480462
return Ok(quote! {});
@@ -483,18 +465,18 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> {
483465
match subdiag {
484466
SubdiagnosticKind::Label => {
485467
report_error_if_not_applied_to_span(attr, &info)?;
486-
Ok(self.add_spanned_subdiagnostic(binding, &fn_ident, slug, text))
468+
Ok(self.add_spanned_subdiagnostic(binding, &fn_ident, slug, raw_label))
487469
}
488470
SubdiagnosticKind::Note | SubdiagnosticKind::Help | SubdiagnosticKind::Warn => {
489471
let inner = info.ty.inner_type();
490472
if type_matches_path(inner, &["rustc_span", "Span"])
491473
|| type_matches_path(inner, &["rustc_span", "MultiSpan"])
492474
{
493-
Ok(self.add_spanned_subdiagnostic(binding, &fn_ident, slug, text))
475+
Ok(self.add_spanned_subdiagnostic(binding, &fn_ident, slug, raw_label))
494476
} else if type_is_unit(inner)
495477
|| (matches!(info.ty, FieldInnerTy::Plain(_)) && type_is_bool(inner))
496478
{
497-
Ok(self.add_subdiagnostic(&fn_ident, slug, text))
479+
Ok(self.add_subdiagnostic(&fn_ident, slug, raw_label))
498480
} else {
499481
report_type_error(attr, "`Span`, `MultiSpan`, `bool` or `()`")?
500482
}
@@ -525,10 +507,9 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> {
525507
.unwrap_or_else(|| quote! { rustc_errors::Applicability::Unspecified });
526508
let style = suggestion_kind.to_suggestion_style();
527509

528-
let suggestion_label = if let Some(text) = text {
529-
//let text = format_for_variables(&text, &self.fields);
510+
let suggestion_label = if let Some(raw_label) = raw_label {
530511
quote! {
531-
#text
512+
#raw_label
532513
}
533514
} else {
534515
quote! {
@@ -558,24 +539,23 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> {
558539
field_binding: TokenStream,
559540
kind: &Ident,
560541
fluent_attr_identifier: Path,
561-
text: Option<String>,
542+
raw_label: Option<String>,
562543
) -> TokenStream {
563544
let diag = &self.parent.diag;
564545
let fn_name = format_ident!("span_{}", kind);
565-
if let Some(text) = text {
566-
//let text = format_for_variables(&text, &self.fields);
546+
if let Some(raw_label) = raw_label {
567547
return quote! {
568548
#diag.#fn_name(
569549
#field_binding,
570-
#text
550+
#raw_label
571551
);
572552
};
573553
}
574-
if let Some(text) = self.get_attr(kind.to_string().as_str()) {
554+
if let Some(raw_label) = self.get_attr(kind.to_string().as_str()) {
575555
quote! {
576556
#diag.#fn_name(
577557
#field_binding,
578-
#text
558+
#raw_label
579559
);
580560
}
581561
} else {
@@ -594,22 +574,17 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> {
594574
&self,
595575
kind: &Ident,
596576
fluent_attr_identifier: Path,
597-
text: Option<String>,
577+
raw_label: Option<String>,
598578
) -> TokenStream {
599579
let diag = &self.parent.diag;
600-
// eprintln!(
601-
// "add_subdiagnostic fluent_attr_identifier: {:?} text: {:?}",
602-
// fluent_attr_identifier, text
603-
// );
604-
if let Some(text) = text {
605-
//let text = format_for_variables(&text, &self.fields);
580+
if let Some(raw_label) = raw_label {
606581
return quote! {
607-
#diag.#kind(#text);
582+
#diag.#kind(#raw_label);
608583
};
609584
}
610-
if let Some(text) = self.get_attr(kind.to_string().as_str()) {
585+
if let Some(raw_label) = self.get_attr(kind.to_string().as_str()) {
611586
quote! {
612-
#diag.#kind(#text);
587+
#diag.#kind(#raw_label);
613588
}
614589
} else {
615590
quote! {
@@ -677,7 +652,6 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> {
677652

678653
fn get_attr(&self, key: &str) -> Option<TokenStream> {
679654
self.attrs.get(key).map(|val| {
680-
//let text = format_for_variables(&val.value(), &self.fields);
681655
let text = &val.value();
682656
quote! {
683657
#text

compiler/rustc_macros/src/diagnostics/subdiagnostic.rs

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

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

201-
match (&slug, &text) {
201+
match (&slug, &raw_label) {
202202
(None, None) => {
203203
throw_span_err!(
204204
attr.span().unwrap(),
205-
"diagnostic slug or text must be first argument of a `#[{name}(...)]` attribute"
205+
"diagnostic slug or raw_label must be first argument of a `#[{name}(...)]` attribute"
206206
);
207207
}
208208
(Some(_), Some(_)) => {
209209
throw_span_err!(
210210
attr.span().unwrap(),
211-
"diagnostic slug and text cannot both be specified"
211+
"diagnostic slug and raw_label cannot both be specified"
212212
);
213213
}
214214
_ => (),
215215
}
216-
kind_slugs.push((kind, slug, no_span, text));
216+
kind_slugs.push((kind, slug, no_span, raw_label));
217217
}
218218

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

533533
let name = format_ident!(

0 commit comments

Comments
 (0)