1 #![feature(let_chains)]
3 #![feature(rustc_attrs)]
4 #![feature(type_alias_impl_trait)]
6 use fluent_bundle::FluentResource;
7 use fluent_syntax::parser::ParserError;
8 use rustc_data_structures::sync::Lrc;
9 use rustc_macros::{fluent_messages, Decodable, Encodable};
12 use std::error::Error;
16 use std::path::{Path, PathBuf};
17 use tracing::{instrument, trace};
19 #[cfg(not(parallel_compiler))]
20 use std::cell::LazyCell as Lazy;
21 #[cfg(parallel_compiler)]
22 use std::sync::LazyLock as Lazy;
24 #[cfg(parallel_compiler)]
25 use intl_memoizer::concurrent::IntlLangMemoizer;
26 #[cfg(not(parallel_compiler))]
27 use intl_memoizer::IntlLangMemoizer;
29 pub use fluent_bundle::{FluentArgs, FluentError, FluentValue};
30 pub use unic_langid::{langid, LanguageIdentifier};
32 // Generates `DEFAULT_LOCALE_RESOURCES` static and `fluent_generated` module.
34 borrowck => "../locales/en-US/borrowck.ftl",
35 builtin_macros => "../locales/en-US/builtin_macros.ftl",
36 const_eval => "../locales/en-US/const_eval.ftl",
37 expand => "../locales/en-US/expand.ftl",
38 lint => "../locales/en-US/lint.ftl",
39 parser => "../locales/en-US/parser.ftl",
40 privacy => "../locales/en-US/privacy.ftl",
41 typeck => "../locales/en-US/typeck.ftl",
44 pub use fluent_generated::{self as fluent, DEFAULT_LOCALE_RESOURCES};
46 pub type FluentBundle = fluent_bundle::bundle::FluentBundle<FluentResource, IntlLangMemoizer>;
48 #[cfg(parallel_compiler)]
49 fn new_bundle(locales: Vec<LanguageIdentifier>) -> FluentBundle {
50 FluentBundle::new_concurrent(locales)
53 #[cfg(not(parallel_compiler))]
54 fn new_bundle(locales: Vec<LanguageIdentifier>) -> FluentBundle {
55 FluentBundle::new(locales)
59 pub enum TranslationBundleError {
60 /// Failed to read from `.ftl` file.
62 /// Failed to parse contents of `.ftl` file.
63 ParseFtl(ParserError),
64 /// Failed to add `FluentResource` to `FluentBundle`.
65 AddResource(FluentError),
66 /// `$sysroot/share/locale/$locale` does not exist.
68 /// Cannot read directory entries of `$sysroot/share/locale/$locale`.
69 ReadLocalesDir(io::Error),
70 /// Cannot read directory entry of `$sysroot/share/locale/$locale`.
71 ReadLocalesDirEntry(io::Error),
72 /// `$sysroot/share/locale/$locale` is not a directory.
76 impl fmt::Display for TranslationBundleError {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 TranslationBundleError::ReadFtl(e) => write!(f, "could not read ftl file: {}", e),
80 TranslationBundleError::ParseFtl(e) => {
81 write!(f, "could not parse ftl file: {}", e)
83 TranslationBundleError::AddResource(e) => write!(f, "failed to add resource: {}", e),
84 TranslationBundleError::MissingLocale => write!(f, "missing locale directory"),
85 TranslationBundleError::ReadLocalesDir(e) => {
86 write!(f, "could not read locales dir: {}", e)
88 TranslationBundleError::ReadLocalesDirEntry(e) => {
89 write!(f, "could not read locales dir entry: {}", e)
91 TranslationBundleError::LocaleIsNotDir => {
92 write!(f, "`$sysroot/share/locales/$locale` is not a directory")
98 impl Error for TranslationBundleError {
99 fn source(&self) -> Option<&(dyn Error + 'static)> {
101 TranslationBundleError::ReadFtl(e) => Some(e),
102 TranslationBundleError::ParseFtl(e) => Some(e),
103 TranslationBundleError::AddResource(e) => Some(e),
104 TranslationBundleError::MissingLocale => None,
105 TranslationBundleError::ReadLocalesDir(e) => Some(e),
106 TranslationBundleError::ReadLocalesDirEntry(e) => Some(e),
107 TranslationBundleError::LocaleIsNotDir => None,
112 impl From<(FluentResource, Vec<ParserError>)> for TranslationBundleError {
113 fn from((_, mut errs): (FluentResource, Vec<ParserError>)) -> Self {
114 TranslationBundleError::ParseFtl(errs.pop().expect("failed ftl parse with no errors"))
118 impl From<Vec<FluentError>> for TranslationBundleError {
119 fn from(mut errs: Vec<FluentError>) -> Self {
120 TranslationBundleError::AddResource(
121 errs.pop().expect("failed adding resource to bundle with no errors"),
126 /// Returns Fluent bundle with the user's locale resources from
127 /// `$sysroot/share/locale/$requested_locale/*.ftl`.
129 /// If `-Z additional-ftl-path` was provided, load that resource and add it to the bundle
130 /// (overriding any conflicting messages).
131 #[instrument(level = "trace")]
132 pub fn fluent_bundle(
133 mut user_provided_sysroot: Option<PathBuf>,
134 mut sysroot_candidates: Vec<PathBuf>,
135 requested_locale: Option<LanguageIdentifier>,
136 additional_ftl_path: Option<&Path>,
137 with_directionality_markers: bool,
138 ) -> Result<Option<Lrc<FluentBundle>>, TranslationBundleError> {
139 if requested_locale.is_none() && additional_ftl_path.is_none() {
143 let fallback_locale = langid!("en-US");
144 let requested_fallback_locale = requested_locale.as_ref() == Some(&fallback_locale);
146 // If there is only `-Z additional-ftl-path`, assume locale is "en-US", otherwise use user
148 let locale = requested_locale.clone().unwrap_or(fallback_locale);
150 let mut bundle = new_bundle(vec![locale]);
152 // Fluent diagnostics can insert directionality isolation markers around interpolated variables
153 // indicating that there may be a shift from right-to-left to left-to-right text (or
154 // vice-versa). These are disabled because they are sometimes visible in the error output, but
155 // may be worth investigating in future (for example: if type names are left-to-right and the
156 // surrounding diagnostic messages are right-to-left, then these might be helpful).
157 bundle.set_use_isolating(with_directionality_markers);
159 // If the user requests the default locale then don't try to load anything.
160 if !requested_fallback_locale && let Some(requested_locale) = requested_locale {
161 let mut found_resources = false;
162 for sysroot in user_provided_sysroot.iter_mut().chain(sysroot_candidates.iter_mut()) {
163 sysroot.push("share");
164 sysroot.push("locale");
165 sysroot.push(requested_locale.to_string());
168 if !sysroot.exists() {
173 if !sysroot.is_dir() {
174 return Err(TranslationBundleError::LocaleIsNotDir);
177 for entry in sysroot.read_dir().map_err(TranslationBundleError::ReadLocalesDir)? {
178 let entry = entry.map_err(TranslationBundleError::ReadLocalesDirEntry)?;
179 let path = entry.path();
181 if path.extension().and_then(|s| s.to_str()) != Some("ftl") {
187 fs::read_to_string(path).map_err(TranslationBundleError::ReadFtl)?;
189 FluentResource::try_new(resource_str).map_err(TranslationBundleError::from)?;
191 bundle.add_resource(resource).map_err(TranslationBundleError::from)?;
192 found_resources = true;
196 if !found_resources {
197 return Err(TranslationBundleError::MissingLocale);
201 if let Some(additional_ftl_path) = additional_ftl_path {
203 fs::read_to_string(additional_ftl_path).map_err(TranslationBundleError::ReadFtl)?;
205 FluentResource::try_new(resource_str).map_err(TranslationBundleError::from)?;
207 bundle.add_resource_overriding(resource);
210 let bundle = Lrc::new(bundle);
214 /// Type alias for the result of `fallback_fluent_bundle` - a reference-counted pointer to a lazily
215 /// evaluated fluent bundle.
216 pub type LazyFallbackBundle = Lrc<Lazy<FluentBundle, impl FnOnce() -> FluentBundle>>;
218 /// Return the default `FluentBundle` with standard "en-US" diagnostic messages.
219 #[instrument(level = "trace")]
220 pub fn fallback_fluent_bundle(
221 resources: &'static [&'static str],
222 with_directionality_markers: bool,
223 ) -> LazyFallbackBundle {
224 Lrc::new(Lazy::new(move || {
225 let mut fallback_bundle = new_bundle(vec![langid!("en-US")]);
226 // See comment in `fluent_bundle`.
227 fallback_bundle.set_use_isolating(with_directionality_markers);
229 for resource in resources {
230 let resource = FluentResource::try_new(resource.to_string())
231 .expect("failed to parse fallback fluent resource");
233 fallback_bundle.add_resource_overriding(resource);
240 /// Identifier for the Fluent message/attribute corresponding to a diagnostic message.
241 type FluentId = Cow<'static, str>;
243 /// Abstraction over a message in a subdiagnostic (i.e. label, note, help, etc) to support both
244 /// translatable and non-translatable diagnostic messages.
246 /// Translatable messages for subdiagnostics are typically attributes attached to a larger Fluent
247 /// message so messages of this type must be combined with a `DiagnosticMessage` (using
248 /// `DiagnosticMessage::with_subdiagnostic_message`) before rendering. However, subdiagnostics from
249 /// the `SessionSubdiagnostic` derive refer to Fluent identifiers directly.
250 #[rustc_diagnostic_item = "SubdiagnosticMessage"]
251 pub enum SubdiagnosticMessage {
252 /// Non-translatable diagnostic message.
253 // FIXME(davidtwco): can a `Cow<'static, str>` be used here?
255 /// Identifier of a Fluent message. Instances of this variant are generated by the
256 /// `SessionSubdiagnostic` derive.
257 FluentIdentifier(FluentId),
258 /// Attribute of a Fluent message. Needs to be combined with a Fluent identifier to produce an
259 /// actual translated message. Instances of this variant are generated by the `fluent_messages`
262 /// <https://projectfluent.org/fluent/guide/attributes.html>
263 FluentAttr(FluentId),
266 /// `From` impl that enables existing diagnostic calls to functions which now take
267 /// `impl Into<SubdiagnosticMessage>` to continue to work as before.
268 impl<S: Into<String>> From<S> for SubdiagnosticMessage {
269 fn from(s: S) -> Self {
270 SubdiagnosticMessage::Str(s.into())
274 /// Abstraction over a message in a diagnostic to support both translatable and non-translatable
275 /// diagnostic messages.
277 /// Intended to be removed once diagnostics are entirely translatable.
278 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
279 #[rustc_diagnostic_item = "DiagnosticMessage"]
280 pub enum DiagnosticMessage {
281 /// Non-translatable diagnostic message.
282 // FIXME(davidtwco): can a `Cow<'static, str>` be used here?
284 /// Identifier for a Fluent message (with optional attribute) corresponding to the diagnostic
287 /// <https://projectfluent.org/fluent/guide/hello.html>
288 /// <https://projectfluent.org/fluent/guide/attributes.html>
289 FluentIdentifier(FluentId, Option<FluentId>),
292 impl DiagnosticMessage {
293 /// Given a `SubdiagnosticMessage` which may contain a Fluent attribute, create a new
294 /// `DiagnosticMessage` that combines that attribute with the Fluent identifier of `self`.
296 /// - If the `SubdiagnosticMessage` is non-translatable then return the message as a
297 /// `DiagnosticMessage`.
298 /// - If `self` is non-translatable then return `self`'s message.
299 pub fn with_subdiagnostic_message(&self, sub: SubdiagnosticMessage) -> Self {
300 let attr = match sub {
301 SubdiagnosticMessage::Str(s) => return DiagnosticMessage::Str(s.clone()),
302 SubdiagnosticMessage::FluentIdentifier(id) => {
303 return DiagnosticMessage::FluentIdentifier(id, None);
305 SubdiagnosticMessage::FluentAttr(attr) => attr,
309 DiagnosticMessage::Str(s) => DiagnosticMessage::Str(s.clone()),
310 DiagnosticMessage::FluentIdentifier(id, _) => {
311 DiagnosticMessage::FluentIdentifier(id.clone(), Some(attr))
316 /// Returns the `String` contained within the `DiagnosticMessage::Str` variant, assuming that
317 /// this diagnostic message is of the legacy, non-translatable variety. Panics if this
318 /// assumption does not hold.
320 /// Don't use this - it exists to support some places that do comparison with diagnostic
322 pub fn expect_str(&self) -> &str {
324 DiagnosticMessage::Str(s) => s,
325 _ => panic!("expected non-translatable diagnostic message"),
330 /// `From` impl that enables existing diagnostic calls to functions which now take
331 /// `impl Into<DiagnosticMessage>` to continue to work as before.
332 impl<S: Into<String>> From<S> for DiagnosticMessage {
333 fn from(s: S) -> Self {
334 DiagnosticMessage::Str(s.into())
338 /// Translating *into* a subdiagnostic message from a diagnostic message is a little strange - but
339 /// the subdiagnostic functions (e.g. `span_label`) take a `SubdiagnosticMessage` and the
340 /// subdiagnostic derive refers to typed identifiers that are `DiagnosticMessage`s, so need to be
341 /// able to convert between these, as much as they'll be converted back into `DiagnosticMessage`
342 /// using `with_subdiagnostic_message` eventually. Don't use this other than for the derive.
343 impl Into<SubdiagnosticMessage> for DiagnosticMessage {
344 fn into(self) -> SubdiagnosticMessage {
346 DiagnosticMessage::Str(s) => SubdiagnosticMessage::Str(s),
347 DiagnosticMessage::FluentIdentifier(id, None) => {
348 SubdiagnosticMessage::FluentIdentifier(id)
350 // There isn't really a sensible behaviour for this because it loses information but
351 // this is the most sensible of the behaviours.
352 DiagnosticMessage::FluentIdentifier(_, Some(attr)) => {
353 SubdiagnosticMessage::FluentAttr(attr)
359 /// A span together with some additional data.
360 #[derive(Clone, Debug)]
361 pub struct SpanLabel {
362 /// The span we are going to include in the final snippet.
365 /// Is this a primary span? This is the "locus" of the message,
366 /// and is indicated with a `^^^^` underline, versus `----`.
367 pub is_primary: bool,
369 /// What label should we attach to this span (if any)?
370 pub label: Option<DiagnosticMessage>,
373 /// A collection of `Span`s.
375 /// Spans have two orthogonal attributes:
377 /// - They can be *primary spans*. In this case they are the locus of
378 /// the error, and would be rendered with `^^^`.
379 /// - They can have a *label*. In this case, the label is written next
380 /// to the mark in the snippet when we render.
381 #[derive(Clone, Debug, Hash, PartialEq, Eq, Encodable, Decodable)]
382 pub struct MultiSpan {
383 primary_spans: Vec<Span>,
384 span_labels: Vec<(Span, DiagnosticMessage)>,
389 pub fn new() -> MultiSpan {
390 MultiSpan { primary_spans: vec![], span_labels: vec![] }
393 pub fn from_span(primary_span: Span) -> MultiSpan {
394 MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
397 pub fn from_spans(mut vec: Vec<Span>) -> MultiSpan {
399 MultiSpan { primary_spans: vec, span_labels: vec![] }
402 pub fn push_span_label(&mut self, span: Span, label: impl Into<DiagnosticMessage>) {
403 self.span_labels.push((span, label.into()));
406 /// Selects the first primary span (if any).
407 pub fn primary_span(&self) -> Option<Span> {
408 self.primary_spans.first().cloned()
411 /// Returns all primary spans.
412 pub fn primary_spans(&self) -> &[Span] {
416 /// Returns `true` if any of the primary spans are displayable.
417 pub fn has_primary_spans(&self) -> bool {
421 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
422 pub fn is_dummy(&self) -> bool {
423 self.primary_spans.iter().all(|sp| sp.is_dummy())
426 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
427 /// display well (like std macros). Returns whether replacements occurred.
428 pub fn replace(&mut self, before: Span, after: Span) -> bool {
429 let mut replacements_occurred = false;
430 for primary_span in &mut self.primary_spans {
431 if *primary_span == before {
432 *primary_span = after;
433 replacements_occurred = true;
436 for span_label in &mut self.span_labels {
437 if span_label.0 == before {
438 span_label.0 = after;
439 replacements_occurred = true;
442 replacements_occurred
445 /// Returns the strings to highlight. We always ensure that there
446 /// is an entry for each of the primary spans -- for each primary
447 /// span `P`, if there is at least one label with span `P`, we return
448 /// those labels (marked as primary). But otherwise we return
449 /// `SpanLabel` instances with empty labels.
450 pub fn span_labels(&self) -> Vec<SpanLabel> {
451 let is_primary = |span| self.primary_spans.contains(&span);
453 let mut span_labels = self
456 .map(|&(span, ref label)| SpanLabel {
458 is_primary: is_primary(span),
459 label: Some(label.clone()),
461 .collect::<Vec<_>>();
463 for &span in &self.primary_spans {
464 if !span_labels.iter().any(|sl| sl.span == span) {
465 span_labels.push(SpanLabel { span, is_primary: true, label: None });
472 /// Returns `true` if any of the span labels is displayable.
473 pub fn has_span_labels(&self) -> bool {
474 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
478 impl From<Span> for MultiSpan {
479 fn from(span: Span) -> MultiSpan {
480 MultiSpan::from_span(span)
484 impl From<Vec<Span>> for MultiSpan {
485 fn from(spans: Vec<Span>) -> MultiSpan {
486 MultiSpan::from_spans(spans)