1 #![feature(let_chains)]
2 #![feature(lazy_cell)]
3 #![feature(rustc_attrs)]
4 #![feature(type_alias_impl_trait)]
5 #![deny(rustc::untranslatable_diagnostic)]
6 #![deny(rustc::diagnostic_outside_of_impl)]
7
8 #[macro_use]
9 extern crate tracing;
10
11 use fluent_bundle::FluentResource;
12 use fluent_syntax::parser::ParserError;
13 use icu_provider_adapters::fallback::{LocaleFallbackProvider, LocaleFallbacker};
14 use rustc_data_structures::sync::{IntoDynSyncSend, Lrc};
15 use rustc_fluent_macro::fluent_messages;
16 use rustc_macros::{Decodable, Encodable};
17 use rustc_span::Span;
18 use std::borrow::Cow;
19 use std::error::Error;
20 use std::fmt;
21 use std::fs;
22 use std::io;
23 use std::path::{Path, PathBuf};
24
25 #[cfg(not(parallel_compiler))]
26 use std::cell::LazyCell as Lazy;
27 #[cfg(parallel_compiler)]
28 use std::sync::LazyLock as Lazy;
29
30 #[cfg(parallel_compiler)]
31 use intl_memoizer::concurrent::IntlLangMemoizer;
32 #[cfg(not(parallel_compiler))]
33 use intl_memoizer::IntlLangMemoizer;
34
35 pub use fluent_bundle::{self, types::FluentType, FluentArgs, FluentError, FluentValue};
36 pub use unic_langid::{langid, LanguageIdentifier};
37
38 fluent_messages! { "../messages.ftl" }
39
40 pub type FluentBundle =
41 IntoDynSyncSend<fluent_bundle::bundle::FluentBundle<FluentResource, IntlLangMemoizer>>;
42
43 #[cfg(not(parallel_compiler))]
new_bundle(locales: Vec<LanguageIdentifier>) -> FluentBundle44 fn new_bundle(locales: Vec<LanguageIdentifier>) -> FluentBundle {
45 IntoDynSyncSend(fluent_bundle::bundle::FluentBundle::new(locales))
46 }
47
48 #[cfg(parallel_compiler)]
new_bundle(locales: Vec<LanguageIdentifier>) -> FluentBundle49 fn new_bundle(locales: Vec<LanguageIdentifier>) -> FluentBundle {
50 IntoDynSyncSend(fluent_bundle::bundle::FluentBundle::new_concurrent(locales))
51 }
52
53 #[derive(Debug)]
54 pub enum TranslationBundleError {
55 /// Failed to read from `.ftl` file.
56 ReadFtl(io::Error),
57 /// Failed to parse contents of `.ftl` file.
58 ParseFtl(ParserError),
59 /// Failed to add `FluentResource` to `FluentBundle`.
60 AddResource(FluentError),
61 /// `$sysroot/share/locale/$locale` does not exist.
62 MissingLocale,
63 /// Cannot read directory entries of `$sysroot/share/locale/$locale`.
64 ReadLocalesDir(io::Error),
65 /// Cannot read directory entry of `$sysroot/share/locale/$locale`.
66 ReadLocalesDirEntry(io::Error),
67 /// `$sysroot/share/locale/$locale` is not a directory.
68 LocaleIsNotDir,
69 }
70
71 impl fmt::Display for TranslationBundleError {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 match self {
74 TranslationBundleError::ReadFtl(e) => write!(f, "could not read ftl file: {}", e),
75 TranslationBundleError::ParseFtl(e) => {
76 write!(f, "could not parse ftl file: {}", e)
77 }
78 TranslationBundleError::AddResource(e) => write!(f, "failed to add resource: {}", e),
79 TranslationBundleError::MissingLocale => write!(f, "missing locale directory"),
80 TranslationBundleError::ReadLocalesDir(e) => {
81 write!(f, "could not read locales dir: {}", e)
82 }
83 TranslationBundleError::ReadLocalesDirEntry(e) => {
84 write!(f, "could not read locales dir entry: {}", e)
85 }
86 TranslationBundleError::LocaleIsNotDir => {
87 write!(f, "`$sysroot/share/locales/$locale` is not a directory")
88 }
89 }
90 }
91 }
92
93 impl Error for TranslationBundleError {
source(&self) -> Option<&(dyn Error + 'static)>94 fn source(&self) -> Option<&(dyn Error + 'static)> {
95 match self {
96 TranslationBundleError::ReadFtl(e) => Some(e),
97 TranslationBundleError::ParseFtl(e) => Some(e),
98 TranslationBundleError::AddResource(e) => Some(e),
99 TranslationBundleError::MissingLocale => None,
100 TranslationBundleError::ReadLocalesDir(e) => Some(e),
101 TranslationBundleError::ReadLocalesDirEntry(e) => Some(e),
102 TranslationBundleError::LocaleIsNotDir => None,
103 }
104 }
105 }
106
107 impl From<(FluentResource, Vec<ParserError>)> for TranslationBundleError {
from((_, mut errs): (FluentResource, Vec<ParserError>)) -> Self108 fn from((_, mut errs): (FluentResource, Vec<ParserError>)) -> Self {
109 TranslationBundleError::ParseFtl(errs.pop().expect("failed ftl parse with no errors"))
110 }
111 }
112
113 impl From<Vec<FluentError>> for TranslationBundleError {
from(mut errs: Vec<FluentError>) -> Self114 fn from(mut errs: Vec<FluentError>) -> Self {
115 TranslationBundleError::AddResource(
116 errs.pop().expect("failed adding resource to bundle with no errors"),
117 )
118 }
119 }
120
121 /// Returns Fluent bundle with the user's locale resources from
122 /// `$sysroot/share/locale/$requested_locale/*.ftl`.
123 ///
124 /// If `-Z additional-ftl-path` was provided, load that resource and add it to the bundle
125 /// (overriding any conflicting messages).
126 #[instrument(level = "trace")]
fluent_bundle( mut user_provided_sysroot: Option<PathBuf>, mut sysroot_candidates: Vec<PathBuf>, requested_locale: Option<LanguageIdentifier>, additional_ftl_path: Option<&Path>, with_directionality_markers: bool, ) -> Result<Option<Lrc<FluentBundle>>, TranslationBundleError>127 pub fn fluent_bundle(
128 mut user_provided_sysroot: Option<PathBuf>,
129 mut sysroot_candidates: Vec<PathBuf>,
130 requested_locale: Option<LanguageIdentifier>,
131 additional_ftl_path: Option<&Path>,
132 with_directionality_markers: bool,
133 ) -> Result<Option<Lrc<FluentBundle>>, TranslationBundleError> {
134 if requested_locale.is_none() && additional_ftl_path.is_none() {
135 return Ok(None);
136 }
137
138 let fallback_locale = langid!("en-US");
139 let requested_fallback_locale = requested_locale.as_ref() == Some(&fallback_locale);
140 trace!(?requested_fallback_locale);
141 if requested_fallback_locale && additional_ftl_path.is_none() {
142 return Ok(None);
143 }
144 // If there is only `-Z additional-ftl-path`, assume locale is "en-US", otherwise use user
145 // provided locale.
146 let locale = requested_locale.clone().unwrap_or(fallback_locale);
147 trace!(?locale);
148 let mut bundle = new_bundle(vec![locale]);
149
150 // Add convenience functions available to ftl authors.
151 register_functions(&mut bundle);
152
153 // Fluent diagnostics can insert directionality isolation markers around interpolated variables
154 // indicating that there may be a shift from right-to-left to left-to-right text (or
155 // vice-versa). These are disabled because they are sometimes visible in the error output, but
156 // may be worth investigating in future (for example: if type names are left-to-right and the
157 // surrounding diagnostic messages are right-to-left, then these might be helpful).
158 bundle.set_use_isolating(with_directionality_markers);
159
160 // If the user requests the default locale then don't try to load anything.
161 if let Some(requested_locale) = requested_locale {
162 let mut found_resources = false;
163 for sysroot in user_provided_sysroot.iter_mut().chain(sysroot_candidates.iter_mut()) {
164 sysroot.push("share");
165 sysroot.push("locale");
166 sysroot.push(requested_locale.to_string());
167 trace!(?sysroot);
168
169 if !sysroot.exists() {
170 trace!("skipping");
171 continue;
172 }
173
174 if !sysroot.is_dir() {
175 return Err(TranslationBundleError::LocaleIsNotDir);
176 }
177
178 for entry in sysroot.read_dir().map_err(TranslationBundleError::ReadLocalesDir)? {
179 let entry = entry.map_err(TranslationBundleError::ReadLocalesDirEntry)?;
180 let path = entry.path();
181 trace!(?path);
182 if path.extension().and_then(|s| s.to_str()) != Some("ftl") {
183 trace!("skipping");
184 continue;
185 }
186
187 let resource_str =
188 fs::read_to_string(path).map_err(TranslationBundleError::ReadFtl)?;
189 let resource =
190 FluentResource::try_new(resource_str).map_err(TranslationBundleError::from)?;
191 trace!(?resource);
192 bundle.add_resource(resource).map_err(TranslationBundleError::from)?;
193 found_resources = true;
194 }
195 }
196
197 if !found_resources {
198 return Err(TranslationBundleError::MissingLocale);
199 }
200 }
201
202 if let Some(additional_ftl_path) = additional_ftl_path {
203 let resource_str =
204 fs::read_to_string(additional_ftl_path).map_err(TranslationBundleError::ReadFtl)?;
205 let resource =
206 FluentResource::try_new(resource_str).map_err(TranslationBundleError::from)?;
207 trace!(?resource);
208 bundle.add_resource_overriding(resource);
209 }
210
211 let bundle = Lrc::new(bundle);
212 Ok(Some(bundle))
213 }
214
register_functions(bundle: &mut FluentBundle)215 fn register_functions(bundle: &mut FluentBundle) {
216 bundle
217 .add_function("STREQ", |positional, _named| match positional {
218 [FluentValue::String(a), FluentValue::String(b)] => format!("{}", (a == b)).into(),
219 _ => FluentValue::Error,
220 })
221 .expect("Failed to add a function to the bundle.");
222 }
223
224 /// Type alias for the result of `fallback_fluent_bundle` - a reference-counted pointer to a lazily
225 /// evaluated fluent bundle.
226 pub type LazyFallbackBundle = Lrc<Lazy<FluentBundle, impl FnOnce() -> FluentBundle>>;
227
228 /// Return the default `FluentBundle` with standard "en-US" diagnostic messages.
229 #[instrument(level = "trace", skip(resources))]
230 pub fn fallback_fluent_bundle(
231 resources: Vec<&'static str>,
232 with_directionality_markers: bool,
233 ) -> LazyFallbackBundle {
234 Lrc::new(Lazy::new(move || {
235 let mut fallback_bundle = new_bundle(vec![langid!("en-US")]);
236
237 register_functions(&mut fallback_bundle);
238
239 // See comment in `fluent_bundle`.
240 fallback_bundle.set_use_isolating(with_directionality_markers);
241
242 for resource in resources {
243 let resource = FluentResource::try_new(resource.to_string())
244 .expect("failed to parse fallback fluent resource");
245 fallback_bundle.add_resource_overriding(resource);
246 }
247
248 fallback_bundle
249 }))
250 }
251
252 /// Identifier for the Fluent message/attribute corresponding to a diagnostic message.
253 type FluentId = Cow<'static, str>;
254
255 /// Abstraction over a message in a subdiagnostic (i.e. label, note, help, etc) to support both
256 /// translatable and non-translatable diagnostic messages.
257 ///
258 /// Translatable messages for subdiagnostics are typically attributes attached to a larger Fluent
259 /// message so messages of this type must be combined with a `DiagnosticMessage` (using
260 /// `DiagnosticMessage::with_subdiagnostic_message`) before rendering. However, subdiagnostics from
261 /// the `Subdiagnostic` derive refer to Fluent identifiers directly.
262 #[rustc_diagnostic_item = "SubdiagnosticMessage"]
263 pub enum SubdiagnosticMessage {
264 /// Non-translatable diagnostic message.
265 Str(Cow<'static, str>),
266 /// Translatable message which has already been translated eagerly.
267 ///
268 /// Some diagnostics have repeated subdiagnostics where the same interpolated variables would
269 /// be instantiated multiple times with different values. As translation normally happens
270 /// immediately prior to emission, after the diagnostic and subdiagnostic derive logic has run,
271 /// the setting of diagnostic arguments in the derived code will overwrite previous variable
272 /// values and only the final value will be set when translation occurs - resulting in
273 /// incorrect diagnostics. Eager translation results in translation for a subdiagnostic
274 /// happening immediately after the subdiagnostic derive's logic has been run. This variant
275 /// stores messages which have been translated eagerly.
276 Eager(Cow<'static, str>),
277 /// Identifier of a Fluent message. Instances of this variant are generated by the
278 /// `Subdiagnostic` derive.
279 FluentIdentifier(FluentId),
280 /// Attribute of a Fluent message. Needs to be combined with a Fluent identifier to produce an
281 /// actual translated message. Instances of this variant are generated by the `fluent_messages`
282 /// macro.
283 ///
284 /// <https://projectfluent.org/fluent/guide/attributes.html>
285 FluentAttr(FluentId),
286 }
287
288 impl From<String> for SubdiagnosticMessage {
from(s: String) -> Self289 fn from(s: String) -> Self {
290 SubdiagnosticMessage::Str(Cow::Owned(s))
291 }
292 }
293 impl From<&'static str> for SubdiagnosticMessage {
from(s: &'static str) -> Self294 fn from(s: &'static str) -> Self {
295 SubdiagnosticMessage::Str(Cow::Borrowed(s))
296 }
297 }
298 impl From<Cow<'static, str>> for SubdiagnosticMessage {
from(s: Cow<'static, str>) -> Self299 fn from(s: Cow<'static, str>) -> Self {
300 SubdiagnosticMessage::Str(s)
301 }
302 }
303
304 /// Abstraction over a message in a diagnostic to support both translatable and non-translatable
305 /// diagnostic messages.
306 ///
307 /// Intended to be removed once diagnostics are entirely translatable.
308 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
309 #[rustc_diagnostic_item = "DiagnosticMessage"]
310 pub enum DiagnosticMessage {
311 /// Non-translatable diagnostic message.
312 Str(Cow<'static, str>),
313 /// Translatable message which has already been translated eagerly.
314 ///
315 /// Some diagnostics have repeated subdiagnostics where the same interpolated variables would
316 /// be instantiated multiple times with different values. As translation normally happens
317 /// immediately prior to emission, after the diagnostic and subdiagnostic derive logic has run,
318 /// the setting of diagnostic arguments in the derived code will overwrite previous variable
319 /// values and only the final value will be set when translation occurs - resulting in
320 /// incorrect diagnostics. Eager translation results in translation for a subdiagnostic
321 /// happening immediately after the subdiagnostic derive's logic has been run. This variant
322 /// stores messages which have been translated eagerly.
323 Eager(Cow<'static, str>),
324 /// Identifier for a Fluent message (with optional attribute) corresponding to the diagnostic
325 /// message.
326 ///
327 /// <https://projectfluent.org/fluent/guide/hello.html>
328 /// <https://projectfluent.org/fluent/guide/attributes.html>
329 FluentIdentifier(FluentId, Option<FluentId>),
330 }
331
332 impl DiagnosticMessage {
333 /// Given a `SubdiagnosticMessage` which may contain a Fluent attribute, create a new
334 /// `DiagnosticMessage` that combines that attribute with the Fluent identifier of `self`.
335 ///
336 /// - If the `SubdiagnosticMessage` is non-translatable then return the message as a
337 /// `DiagnosticMessage`.
338 /// - If `self` is non-translatable then return `self`'s message.
with_subdiagnostic_message(&self, sub: SubdiagnosticMessage) -> Self339 pub fn with_subdiagnostic_message(&self, sub: SubdiagnosticMessage) -> Self {
340 let attr = match sub {
341 SubdiagnosticMessage::Str(s) => return DiagnosticMessage::Str(s),
342 SubdiagnosticMessage::Eager(s) => return DiagnosticMessage::Eager(s),
343 SubdiagnosticMessage::FluentIdentifier(id) => {
344 return DiagnosticMessage::FluentIdentifier(id, None);
345 }
346 SubdiagnosticMessage::FluentAttr(attr) => attr,
347 };
348
349 match self {
350 DiagnosticMessage::Str(s) => DiagnosticMessage::Str(s.clone()),
351 DiagnosticMessage::Eager(s) => DiagnosticMessage::Eager(s.clone()),
352 DiagnosticMessage::FluentIdentifier(id, _) => {
353 DiagnosticMessage::FluentIdentifier(id.clone(), Some(attr))
354 }
355 }
356 }
357 }
358
359 impl From<String> for DiagnosticMessage {
from(s: String) -> Self360 fn from(s: String) -> Self {
361 DiagnosticMessage::Str(Cow::Owned(s))
362 }
363 }
364 impl From<&'static str> for DiagnosticMessage {
from(s: &'static str) -> Self365 fn from(s: &'static str) -> Self {
366 DiagnosticMessage::Str(Cow::Borrowed(s))
367 }
368 }
369 impl From<Cow<'static, str>> for DiagnosticMessage {
from(s: Cow<'static, str>) -> Self370 fn from(s: Cow<'static, str>) -> Self {
371 DiagnosticMessage::Str(s)
372 }
373 }
374
375 /// A workaround for "good path" ICEs when formatting types in disabled lints.
376 ///
377 /// Delays formatting until `.into(): DiagnosticMessage` is used.
378 pub struct DelayDm<F>(pub F);
379
380 impl<F: FnOnce() -> String> From<DelayDm<F>> for DiagnosticMessage {
from(DelayDm(f): DelayDm<F>) -> Self381 fn from(DelayDm(f): DelayDm<F>) -> Self {
382 DiagnosticMessage::from(f())
383 }
384 }
385
386 /// Translating *into* a subdiagnostic message from a diagnostic message is a little strange - but
387 /// the subdiagnostic functions (e.g. `span_label`) take a `SubdiagnosticMessage` and the
388 /// subdiagnostic derive refers to typed identifiers that are `DiagnosticMessage`s, so need to be
389 /// able to convert between these, as much as they'll be converted back into `DiagnosticMessage`
390 /// using `with_subdiagnostic_message` eventually. Don't use this other than for the derive.
391 impl Into<SubdiagnosticMessage> for DiagnosticMessage {
into(self) -> SubdiagnosticMessage392 fn into(self) -> SubdiagnosticMessage {
393 match self {
394 DiagnosticMessage::Str(s) => SubdiagnosticMessage::Str(s),
395 DiagnosticMessage::Eager(s) => SubdiagnosticMessage::Eager(s),
396 DiagnosticMessage::FluentIdentifier(id, None) => {
397 SubdiagnosticMessage::FluentIdentifier(id)
398 }
399 // There isn't really a sensible behaviour for this because it loses information but
400 // this is the most sensible of the behaviours.
401 DiagnosticMessage::FluentIdentifier(_, Some(attr)) => {
402 SubdiagnosticMessage::FluentAttr(attr)
403 }
404 }
405 }
406 }
407
408 /// A span together with some additional data.
409 #[derive(Clone, Debug)]
410 pub struct SpanLabel {
411 /// The span we are going to include in the final snippet.
412 pub span: Span,
413
414 /// Is this a primary span? This is the "locus" of the message,
415 /// and is indicated with a `^^^^` underline, versus `----`.
416 pub is_primary: bool,
417
418 /// What label should we attach to this span (if any)?
419 pub label: Option<DiagnosticMessage>,
420 }
421
422 /// A collection of `Span`s.
423 ///
424 /// Spans have two orthogonal attributes:
425 ///
426 /// - They can be *primary spans*. In this case they are the locus of
427 /// the error, and would be rendered with `^^^`.
428 /// - They can have a *label*. In this case, the label is written next
429 /// to the mark in the snippet when we render.
430 #[derive(Clone, Debug, Hash, PartialEq, Eq, Encodable, Decodable)]
431 pub struct MultiSpan {
432 primary_spans: Vec<Span>,
433 span_labels: Vec<(Span, DiagnosticMessage)>,
434 }
435
436 impl MultiSpan {
437 #[inline]
new() -> MultiSpan438 pub fn new() -> MultiSpan {
439 MultiSpan { primary_spans: vec![], span_labels: vec![] }
440 }
441
from_span(primary_span: Span) -> MultiSpan442 pub fn from_span(primary_span: Span) -> MultiSpan {
443 MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
444 }
445
from_spans(mut vec: Vec<Span>) -> MultiSpan446 pub fn from_spans(mut vec: Vec<Span>) -> MultiSpan {
447 vec.sort();
448 MultiSpan { primary_spans: vec, span_labels: vec![] }
449 }
450
push_span_label(&mut self, span: Span, label: impl Into<DiagnosticMessage>)451 pub fn push_span_label(&mut self, span: Span, label: impl Into<DiagnosticMessage>) {
452 self.span_labels.push((span, label.into()));
453 }
454
455 /// Selects the first primary span (if any).
primary_span(&self) -> Option<Span>456 pub fn primary_span(&self) -> Option<Span> {
457 self.primary_spans.first().cloned()
458 }
459
460 /// Returns all primary spans.
primary_spans(&self) -> &[Span]461 pub fn primary_spans(&self) -> &[Span] {
462 &self.primary_spans
463 }
464
465 /// Returns `true` if any of the primary spans are displayable.
has_primary_spans(&self) -> bool466 pub fn has_primary_spans(&self) -> bool {
467 !self.is_dummy()
468 }
469
470 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
is_dummy(&self) -> bool471 pub fn is_dummy(&self) -> bool {
472 self.primary_spans.iter().all(|sp| sp.is_dummy())
473 }
474
475 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
476 /// display well (like std macros). Returns whether replacements occurred.
replace(&mut self, before: Span, after: Span) -> bool477 pub fn replace(&mut self, before: Span, after: Span) -> bool {
478 let mut replacements_occurred = false;
479 for primary_span in &mut self.primary_spans {
480 if *primary_span == before {
481 *primary_span = after;
482 replacements_occurred = true;
483 }
484 }
485 for span_label in &mut self.span_labels {
486 if span_label.0 == before {
487 span_label.0 = after;
488 replacements_occurred = true;
489 }
490 }
491 replacements_occurred
492 }
493
pop_span_label(&mut self) -> Option<(Span, DiagnosticMessage)>494 pub fn pop_span_label(&mut self) -> Option<(Span, DiagnosticMessage)> {
495 self.span_labels.pop()
496 }
497
498 /// Returns the strings to highlight. We always ensure that there
499 /// is an entry for each of the primary spans -- for each primary
500 /// span `P`, if there is at least one label with span `P`, we return
501 /// those labels (marked as primary). But otherwise we return
502 /// `SpanLabel` instances with empty labels.
span_labels(&self) -> Vec<SpanLabel>503 pub fn span_labels(&self) -> Vec<SpanLabel> {
504 let is_primary = |span| self.primary_spans.contains(&span);
505
506 let mut span_labels = self
507 .span_labels
508 .iter()
509 .map(|&(span, ref label)| SpanLabel {
510 span,
511 is_primary: is_primary(span),
512 label: Some(label.clone()),
513 })
514 .collect::<Vec<_>>();
515
516 for &span in &self.primary_spans {
517 if !span_labels.iter().any(|sl| sl.span == span) {
518 span_labels.push(SpanLabel { span, is_primary: true, label: None });
519 }
520 }
521
522 span_labels
523 }
524
525 /// Returns `true` if any of the span labels is displayable.
has_span_labels(&self) -> bool526 pub fn has_span_labels(&self) -> bool {
527 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
528 }
529 }
530
531 impl From<Span> for MultiSpan {
from(span: Span) -> MultiSpan532 fn from(span: Span) -> MultiSpan {
533 MultiSpan::from_span(span)
534 }
535 }
536
537 impl From<Vec<Span>> for MultiSpan {
from(spans: Vec<Span>) -> MultiSpan538 fn from(spans: Vec<Span>) -> MultiSpan {
539 MultiSpan::from_spans(spans)
540 }
541 }
542
icu_locale_from_unic_langid(lang: LanguageIdentifier) -> Option<icu_locid::Locale>543 fn icu_locale_from_unic_langid(lang: LanguageIdentifier) -> Option<icu_locid::Locale> {
544 icu_locid::Locale::try_from_bytes(lang.to_string().as_bytes()).ok()
545 }
546
fluent_value_from_str_list_sep_by_and(l: Vec<Cow<'_, str>>) -> FluentValue<'_>547 pub fn fluent_value_from_str_list_sep_by_and(l: Vec<Cow<'_, str>>) -> FluentValue<'_> {
548 // Fluent requires 'static value here for its AnyEq usages.
549 #[derive(Clone, PartialEq, Debug)]
550 struct FluentStrListSepByAnd(Vec<String>);
551
552 impl FluentType for FluentStrListSepByAnd {
553 fn duplicate(&self) -> Box<dyn FluentType + Send> {
554 Box::new(self.clone())
555 }
556
557 fn as_string(&self, intls: &intl_memoizer::IntlLangMemoizer) -> Cow<'static, str> {
558 let result = intls
559 .with_try_get::<MemoizableListFormatter, _, _>((), |list_formatter| {
560 list_formatter.format_to_string(self.0.iter())
561 })
562 .unwrap();
563 Cow::Owned(result)
564 }
565
566 #[cfg(not(parallel_compiler))]
567 fn as_string_threadsafe(
568 &self,
569 _intls: &intl_memoizer::concurrent::IntlLangMemoizer,
570 ) -> Cow<'static, str> {
571 unreachable!("`as_string_threadsafe` is not used in non-parallel rustc")
572 }
573
574 #[cfg(parallel_compiler)]
575 fn as_string_threadsafe(
576 &self,
577 intls: &intl_memoizer::concurrent::IntlLangMemoizer,
578 ) -> Cow<'static, str> {
579 let result = intls
580 .with_try_get::<MemoizableListFormatter, _, _>((), |list_formatter| {
581 list_formatter.format_to_string(self.0.iter())
582 })
583 .unwrap();
584 Cow::Owned(result)
585 }
586 }
587
588 struct MemoizableListFormatter(icu_list::ListFormatter);
589
590 impl std::ops::Deref for MemoizableListFormatter {
591 type Target = icu_list::ListFormatter;
592 fn deref(&self) -> &Self::Target {
593 &self.0
594 }
595 }
596
597 impl intl_memoizer::Memoizable for MemoizableListFormatter {
598 type Args = ();
599 type Error = ();
600
601 fn construct(lang: LanguageIdentifier, _args: Self::Args) -> Result<Self, Self::Error>
602 where
603 Self: Sized,
604 {
605 let baked_data_provider = rustc_baked_icu_data::baked_data_provider();
606 let locale_fallbacker =
607 LocaleFallbacker::try_new_with_any_provider(&baked_data_provider)
608 .expect("Failed to create fallback provider");
609 let data_provider =
610 LocaleFallbackProvider::new_with_fallbacker(baked_data_provider, locale_fallbacker);
611 let locale = icu_locale_from_unic_langid(lang)
612 .unwrap_or_else(|| rustc_baked_icu_data::supported_locales::EN);
613 let list_formatter =
614 icu_list::ListFormatter::try_new_and_with_length_with_any_provider(
615 &data_provider,
616 &locale.into(),
617 icu_list::ListLength::Wide,
618 )
619 .expect("Failed to create list formatter");
620
621 Ok(MemoizableListFormatter(list_formatter))
622 }
623 }
624
625 let l = l.into_iter().map(|x| x.into_owned()).collect();
626
627 FluentValue::Custom(Box::new(FluentStrListSepByAnd(l)))
628 }
629