Skip to content

Commit c694499

Browse files
committed
Extract Translator struct
1 parent 55d4364 commit c694499

File tree

18 files changed

+190
-250
lines changed

18 files changed

+190
-250
lines changed

compiler/rustc_codegen_ssa/src/back/write.rs

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@ use rustc_data_structures::jobserver::{self, Acquired};
1414
use rustc_data_structures::memmap::Mmap;
1515
use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard};
1616
use rustc_errors::emitter::Emitter;
17-
use rustc_errors::translation::Translate;
17+
use rustc_errors::translation::Translator;
1818
use rustc_errors::{
19-
Diag, DiagArgMap, DiagCtxt, DiagMessage, ErrCode, FatalError, FluentBundle, Level, MultiSpan,
20-
Style, Suggestions,
19+
Diag, DiagArgMap, DiagCtxt, DiagMessage, ErrCode, FatalError, Level, MultiSpan, Style,
20+
Suggestions,
2121
};
2222
use rustc_fs_util::link_or_copy;
2323
use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
@@ -1889,16 +1889,6 @@ impl SharedEmitter {
18891889
}
18901890
}
18911891

1892-
impl Translate for SharedEmitter {
1893-
fn fluent_bundle(&self) -> Option<&FluentBundle> {
1894-
None
1895-
}
1896-
1897-
fn fallback_fluent_bundle(&self) -> &FluentBundle {
1898-
panic!("shared emitter attempted to translate a diagnostic");
1899-
}
1900-
}
1901-
19021892
impl Emitter for SharedEmitter {
19031893
fn emit_diagnostic(
19041894
&mut self,
@@ -1932,6 +1922,10 @@ impl Emitter for SharedEmitter {
19321922
fn source_map(&self) -> Option<&SourceMap> {
19331923
None
19341924
}
1925+
1926+
fn translator(&self) -> &Translator {
1927+
panic!("shared emitter attempted to translate a diagnostic");
1928+
}
19351929
}
19361930

19371931
impl SharedEmitterMain {

compiler/rustc_driver_impl/src/lib.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ use rustc_data_structures::profiling::{
3838
};
3939
use rustc_errors::emitter::stderr_destination;
4040
use rustc_errors::registry::Registry;
41+
use rustc_errors::translation::Translator;
4142
use rustc_errors::{ColorConfig, DiagCtxt, ErrCode, FatalError, PResult, markdown};
4243
use rustc_feature::find_gated_cfg;
4344
// This avoids a false positive with `-Wunused_crate_dependencies`.
@@ -109,6 +110,10 @@ use crate::session_diagnostics::{
109110

110111
rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
111112

113+
pub fn default_translator() -> Translator {
114+
Translator::with_fallback_bundle(DEFAULT_LOCALE_RESOURCES.to_vec(), false)
115+
}
116+
112117
pub static DEFAULT_LOCALE_RESOURCES: &[&str] = &[
113118
// tidy-alphabetical-start
114119
crate::DEFAULT_LOCALE_RESOURCE,
@@ -1413,11 +1418,10 @@ fn report_ice(
14131418
extra_info: fn(&DiagCtxt),
14141419
using_internal_features: &AtomicBool,
14151420
) {
1416-
let fallback_bundle =
1417-
rustc_errors::fallback_fluent_bundle(crate::DEFAULT_LOCALE_RESOURCES.to_vec(), false);
1421+
let translator = default_translator();
14181422
let emitter = Box::new(rustc_errors::emitter::HumanEmitter::new(
14191423
stderr_destination(rustc_errors::ColorConfig::Auto),
1420-
fallback_bundle,
1424+
translator,
14211425
));
14221426
let dcx = rustc_errors::DiagCtxt::new(emitter);
14231427
let dcx = dcx.handle();

compiler/rustc_error_messages/src/lib.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ pub use fluent_bundle::{self, FluentArgs, FluentError, FluentValue};
1818
use fluent_syntax::parser::ParserError;
1919
use icu_provider_adapters::fallback::{LocaleFallbackProvider, LocaleFallbacker};
2020
use intl_memoizer::concurrent::IntlLangMemoizer;
21-
use rustc_data_structures::sync::IntoDynSyncSend;
21+
use rustc_data_structures::sync::{DynSend, IntoDynSyncSend};
2222
use rustc_macros::{Decodable, Encodable};
2323
use rustc_span::Span;
2424
use smallvec::SmallVec;
@@ -204,16 +204,16 @@ fn register_functions(bundle: &mut FluentBundle) {
204204

205205
/// Type alias for the result of `fallback_fluent_bundle` - a reference-counted pointer to a lazily
206206
/// evaluated fluent bundle.
207-
pub type LazyFallbackBundle = Arc<LazyLock<FluentBundle, impl FnOnce() -> FluentBundle>>;
207+
pub type LazyFallbackBundle =
208+
Arc<LazyLock<FluentBundle, Box<dyn FnOnce() -> FluentBundle + DynSend>>>;
208209

209210
/// Return the default `FluentBundle` with standard "en-US" diagnostic messages.
210211
#[instrument(level = "trace", skip(resources))]
211-
#[define_opaque(LazyFallbackBundle)]
212212
pub fn fallback_fluent_bundle(
213213
resources: Vec<&'static str>,
214214
with_directionality_markers: bool,
215215
) -> LazyFallbackBundle {
216-
Arc::new(LazyLock::new(move || {
216+
Arc::new(LazyLock::new(Box::new(move || {
217217
let mut fallback_bundle = new_bundle(vec![langid!("en-US")]);
218218

219219
register_functions(&mut fallback_bundle);
@@ -228,7 +228,7 @@ pub fn fallback_fluent_bundle(
228228
}
229229

230230
fallback_bundle
231-
}))
231+
})))
232232
}
233233

234234
/// Identifier for the Fluent message/attribute corresponding to a diagnostic message.

compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs

Lines changed: 10 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,15 @@ use rustc_span::source_map::SourceMap;
1515
use crate::emitter::FileWithAnnotatedLines;
1616
use crate::registry::Registry;
1717
use crate::snippet::Line;
18-
use crate::translation::{Translate, to_fluent_args};
18+
use crate::translation::{Translator, to_fluent_args};
1919
use crate::{
20-
CodeSuggestion, DiagInner, DiagMessage, Emitter, ErrCode, FluentBundle, LazyFallbackBundle,
21-
Level, MultiSpan, Style, Subdiag,
20+
CodeSuggestion, DiagInner, DiagMessage, Emitter, ErrCode, Level, MultiSpan, Style, Subdiag,
2221
};
2322

2423
/// Generates diagnostics using annotate-snippet
2524
pub struct AnnotateSnippetEmitter {
2625
source_map: Option<Arc<SourceMap>>,
27-
fluent_bundle: Option<Arc<FluentBundle>>,
28-
fallback_bundle: LazyFallbackBundle,
26+
translator: Translator,
2927

3028
/// If true, hides the longer explanation text
3129
short_message: bool,
@@ -35,16 +33,6 @@ pub struct AnnotateSnippetEmitter {
3533
macro_backtrace: bool,
3634
}
3735

38-
impl Translate for AnnotateSnippetEmitter {
39-
fn fluent_bundle(&self) -> Option<&FluentBundle> {
40-
self.fluent_bundle.as_deref()
41-
}
42-
43-
fn fallback_fluent_bundle(&self) -> &FluentBundle {
44-
&self.fallback_bundle
45-
}
46-
}
47-
4836
impl Emitter for AnnotateSnippetEmitter {
4937
/// The entry point for the diagnostics generation
5038
fn emit_diagnostic(&mut self, mut diag: DiagInner, _registry: &Registry) {
@@ -78,6 +66,10 @@ impl Emitter for AnnotateSnippetEmitter {
7866
fn should_show_explain(&self) -> bool {
7967
!self.short_message
8068
}
69+
70+
fn translator(&self) -> &Translator {
71+
&self.translator
72+
}
8173
}
8274

8375
/// Provides the source string for the given `line` of `file`
@@ -104,19 +96,11 @@ fn annotation_level_for_level(level: Level) -> annotate_snippets::Level {
10496
impl AnnotateSnippetEmitter {
10597
pub fn new(
10698
source_map: Option<Arc<SourceMap>>,
107-
fluent_bundle: Option<Arc<FluentBundle>>,
108-
fallback_bundle: LazyFallbackBundle,
99+
translator: Translator,
109100
short_message: bool,
110101
macro_backtrace: bool,
111102
) -> Self {
112-
Self {
113-
source_map,
114-
fluent_bundle,
115-
fallback_bundle,
116-
short_message,
117-
ui_testing: false,
118-
macro_backtrace,
119-
}
103+
Self { source_map, translator, short_message, ui_testing: false, macro_backtrace }
120104
}
121105

122106
/// Allows to modify `Self` to enable or disable the `ui_testing` flag.
@@ -137,7 +121,7 @@ impl AnnotateSnippetEmitter {
137121
_children: &[Subdiag],
138122
_suggestions: &[CodeSuggestion],
139123
) {
140-
let message = self.translate_messages(messages, args);
124+
let message = self.translator.translate_messages(messages, args);
141125
if let Some(source_map) = &self.source_map {
142126
// Make sure our primary file comes first
143127
let primary_lo = if let Some(primary_span) = msp.primary_span().as_ref() {

compiler/rustc_errors/src/emitter.rs

Lines changed: 32 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,10 @@ use crate::snippet::{
3434
Annotation, AnnotationColumn, AnnotationType, Line, MultilineAnnotation, Style, StyledString,
3535
};
3636
use crate::styled_buffer::StyledBuffer;
37-
use crate::translation::{Translate, to_fluent_args};
37+
use crate::translation::{Translator, to_fluent_args};
3838
use crate::{
39-
CodeSuggestion, DiagInner, DiagMessage, ErrCode, FluentBundle, LazyFallbackBundle, Level,
40-
MultiSpan, Subdiag, SubstitutionHighlight, SuggestionStyle, TerminalUrl,
39+
CodeSuggestion, DiagInner, DiagMessage, ErrCode, Level, MultiSpan, Subdiag,
40+
SubstitutionHighlight, SuggestionStyle, TerminalUrl,
4141
};
4242

4343
/// Default column width, used in tests and when terminal dimensions cannot be determined.
@@ -169,7 +169,7 @@ const ANONYMIZED_LINE_NUM: &str = "LL";
169169
pub type DynEmitter = dyn Emitter + DynSend;
170170

171171
/// Emitter trait for emitting errors.
172-
pub trait Emitter: Translate {
172+
pub trait Emitter {
173173
/// Emit a structured diagnostic.
174174
fn emit_diagnostic(&mut self, diag: DiagInner, registry: &Registry);
175175

@@ -202,6 +202,8 @@ pub trait Emitter: Translate {
202202

203203
fn source_map(&self) -> Option<&SourceMap>;
204204

205+
fn translator(&self) -> &Translator;
206+
205207
/// Formats the substitutions of the primary_span
206208
///
207209
/// There are a lot of conditions to this method, but in short:
@@ -214,13 +216,17 @@ pub trait Emitter: Translate {
214216
/// * If the current `DiagInner` has multiple suggestions,
215217
/// we leave `primary_span` and the suggestions untouched.
216218
fn primary_span_formatted(
217-
&mut self,
219+
&self,
218220
primary_span: &mut MultiSpan,
219221
suggestions: &mut Vec<CodeSuggestion>,
220222
fluent_args: &FluentArgs<'_>,
221223
) {
222224
if let Some((sugg, rest)) = suggestions.split_first() {
223-
let msg = self.translate_message(&sugg.msg, fluent_args).map_err(Report::new).unwrap();
225+
let msg = self
226+
.translator()
227+
.translate_message(&sugg.msg, fluent_args)
228+
.map_err(Report::new)
229+
.unwrap();
224230
if rest.is_empty()
225231
// ^ if there is only one suggestion
226232
// don't display multi-suggestions as labels
@@ -481,16 +487,6 @@ pub trait Emitter: Translate {
481487
}
482488
}
483489

484-
impl Translate for HumanEmitter {
485-
fn fluent_bundle(&self) -> Option<&FluentBundle> {
486-
self.fluent_bundle.as_deref()
487-
}
488-
489-
fn fallback_fluent_bundle(&self) -> &FluentBundle {
490-
&self.fallback_bundle
491-
}
492-
}
493-
494490
impl Emitter for HumanEmitter {
495491
fn source_map(&self) -> Option<&SourceMap> {
496492
self.sm.as_deref()
@@ -528,6 +524,10 @@ impl Emitter for HumanEmitter {
528524
fn supports_color(&self) -> bool {
529525
self.dst.supports_color()
530526
}
527+
528+
fn translator(&self) -> &Translator {
529+
&self.translator
530+
}
531531
}
532532

533533
/// An emitter that does nothing when emitting a non-fatal diagnostic.
@@ -539,16 +539,6 @@ pub struct SilentEmitter {
539539
pub emit_fatal_diagnostic: bool,
540540
}
541541

542-
impl Translate for SilentEmitter {
543-
fn fluent_bundle(&self) -> Option<&FluentBundle> {
544-
None
545-
}
546-
547-
fn fallback_fluent_bundle(&self) -> &FluentBundle {
548-
self.fatal_emitter.fallback_fluent_bundle()
549-
}
550-
}
551-
552542
impl Emitter for SilentEmitter {
553543
fn source_map(&self) -> Option<&SourceMap> {
554544
None
@@ -562,6 +552,10 @@ impl Emitter for SilentEmitter {
562552
self.fatal_emitter.emit_diagnostic(diag, registry);
563553
}
564554
}
555+
556+
fn translator(&self) -> &Translator {
557+
self.fatal_emitter.translator()
558+
}
565559
}
566560

567561
/// Maximum number of suggestions to be shown
@@ -605,9 +599,8 @@ pub struct HumanEmitter {
605599
#[setters(skip)]
606600
dst: IntoDynSyncSend<Destination>,
607601
sm: Option<Arc<SourceMap>>,
608-
fluent_bundle: Option<Arc<FluentBundle>>,
609602
#[setters(skip)]
610-
fallback_bundle: LazyFallbackBundle,
603+
translator: Translator,
611604
short_message: bool,
612605
ui_testing: bool,
613606
ignored_directories_in_source_blocks: Vec<String>,
@@ -627,12 +620,11 @@ pub(crate) struct FileWithAnnotatedLines {
627620
}
628621

629622
impl HumanEmitter {
630-
pub fn new(dst: Destination, fallback_bundle: LazyFallbackBundle) -> HumanEmitter {
623+
pub fn new(dst: Destination, translator: Translator) -> HumanEmitter {
631624
HumanEmitter {
632625
dst: IntoDynSyncSend(dst),
633626
sm: None,
634-
fluent_bundle: None,
635-
fallback_bundle,
627+
translator,
636628
short_message: false,
637629
ui_testing: false,
638630
ignored_directories_in_source_blocks: Vec::new(),
@@ -1423,7 +1415,7 @@ impl HumanEmitter {
14231415
// very *weird* formats
14241416
// see?
14251417
for (text, style) in msgs.iter() {
1426-
let text = self.translate_message(text, args).map_err(Report::new).unwrap();
1418+
let text = self.translator.translate_message(text, args).map_err(Report::new).unwrap();
14271419
let text = &normalize_whitespace(&text);
14281420
let lines = text.split('\n').collect::<Vec<_>>();
14291421
if lines.len() > 1 {
@@ -1518,7 +1510,8 @@ impl HumanEmitter {
15181510
}
15191511
let mut line = 0;
15201512
for (text, style) in msgs.iter() {
1521-
let text = self.translate_message(text, args).map_err(Report::new).unwrap();
1513+
let text =
1514+
self.translator.translate_message(text, args).map_err(Report::new).unwrap();
15221515
// Account for newlines to align output to its label.
15231516
for text in normalize_whitespace(&text).lines() {
15241517
buffer.append(
@@ -1550,7 +1543,7 @@ impl HumanEmitter {
15501543
.into_iter()
15511544
.filter_map(|label| match label.label {
15521545
Some(msg) if label.is_primary => {
1553-
let text = self.translate_message(&msg, args).ok()?;
1546+
let text = self.translator.translate_message(&msg, args).ok()?;
15541547
if !text.trim().is_empty() { Some(text.to_string()) } else { None }
15551548
}
15561549
_ => None,
@@ -3094,7 +3087,11 @@ impl FileWithAnnotatedLines {
30943087

30953088
let label = label.as_ref().map(|m| {
30963089
normalize_whitespace(
3097-
&emitter.translate_message(m, args).map_err(Report::new).unwrap(),
3090+
&emitter
3091+
.translator()
3092+
.translate_message(m, args)
3093+
.map_err(Report::new)
3094+
.unwrap(),
30983095
)
30993096
});
31003097

0 commit comments

Comments
 (0)