1 #![feature(let_chains)]
3 #![feature(rustc_attrs)]
4 #![feature(type_alias_impl_trait)]
5 #![deny(rustc::untranslatable_diagnostic)]
6 #![deny(rustc::diagnostic_outside_of_impl)]
8 use fluent_bundle::FluentResource;
9 use fluent_syntax::parser::ParserError;
10 use rustc_data_structures::sync::Lrc;
11 use rustc_macros::{fluent_messages, Decodable, Encodable};
14 use std::error::Error;
18 use std::path::{Path, PathBuf};
19 use tracing::{instrument, trace};
21 #[cfg(not(parallel_compiler))]
22 use std::cell::LazyCell as Lazy;
23 #[cfg(parallel_compiler)]
24 use std::sync::LazyLock as Lazy;
26 #[cfg(parallel_compiler)]
27 use intl_memoizer::concurrent::IntlLangMemoizer;
28 #[cfg(not(parallel_compiler))]
29 use intl_memoizer::IntlLangMemoizer;
31 pub use fluent_bundle::{FluentArgs, FluentError, FluentValue};
32 pub use unic_langid::{langid, LanguageIdentifier};
34 // Generates `DEFAULT_LOCALE_RESOURCES` static and `fluent_generated` module.
36 ast_lowering => "../locales/en-US/ast_lowering.ftl",
37 ast_passes => "../locales/en-US/ast_passes.ftl",
38 attr => "../locales/en-US/attr.ftl",
39 borrowck => "../locales/en-US/borrowck.ftl",
40 builtin_macros => "../locales/en-US/builtin_macros.ftl",
41 const_eval => "../locales/en-US/const_eval.ftl",
42 driver => "../locales/en-US/driver.ftl",
43 expand => "../locales/en-US/expand.ftl",
44 session => "../locales/en-US/session.ftl",
45 interface => "../locales/en-US/interface.ftl",
46 infer => "../locales/en-US/infer.ftl",
47 lint => "../locales/en-US/lint.ftl",
48 monomorphize => "../locales/en-US/monomorphize.ftl",
49 metadata => "../locales/en-US/metadata.ftl",
50 parser => "../locales/en-US/parser.ftl",
51 passes => "../locales/en-US/passes.ftl",
52 plugin_impl => "../locales/en-US/plugin_impl.ftl",
53 privacy => "../locales/en-US/privacy.ftl",
54 save_analysis => "../locales/en-US/save_analysis.ftl",
55 ty_utils => "../locales/en-US/ty_utils.ftl",
56 typeck => "../locales/en-US/typeck.ftl",
57 mir_dataflow => "../locales/en-US/mir_dataflow.ftl",
58 symbol_mangling => "../locales/en-US/symbol_mangling.ftl",
61 pub use fluent_generated::{self as fluent, DEFAULT_LOCALE_RESOURCES};
63 pub type FluentBundle = fluent_bundle::bundle::FluentBundle<FluentResource, IntlLangMemoizer>;
65 #[cfg(parallel_compiler)]
66 fn new_bundle(locales: Vec<LanguageIdentifier>) -> FluentBundle {
67 FluentBundle::new_concurrent(locales)
70 #[cfg(not(parallel_compiler))]
71 fn new_bundle(locales: Vec<LanguageIdentifier>) -> FluentBundle {
72 FluentBundle::new(locales)
76 pub enum TranslationBundleError {
77 /// Failed to read from `.ftl` file.
79 /// Failed to parse contents of `.ftl` file.
80 ParseFtl(ParserError),
81 /// Failed to add `FluentResource` to `FluentBundle`.
82 AddResource(FluentError),
83 /// `$sysroot/share/locale/$locale` does not exist.
85 /// Cannot read directory entries of `$sysroot/share/locale/$locale`.
86 ReadLocalesDir(io::Error),
87 /// Cannot read directory entry of `$sysroot/share/locale/$locale`.
88 ReadLocalesDirEntry(io::Error),
89 /// `$sysroot/share/locale/$locale` is not a directory.
93 impl fmt::Display for TranslationBundleError {
94 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96 TranslationBundleError::ReadFtl(e) => write!(f, "could not read ftl file: {}", e),
97 TranslationBundleError::ParseFtl(e) => {
98 write!(f, "could not parse ftl file: {}", e)
100 TranslationBundleError::AddResource(e) => write!(f, "failed to add resource: {}", e),
101 TranslationBundleError::MissingLocale => write!(f, "missing locale directory"),
102 TranslationBundleError::ReadLocalesDir(e) => {
103 write!(f, "could not read locales dir: {}", e)
105 TranslationBundleError::ReadLocalesDirEntry(e) => {
106 write!(f, "could not read locales dir entry: {}", e)
108 TranslationBundleError::LocaleIsNotDir => {
109 write!(f, "`$sysroot/share/locales/$locale` is not a directory")
115 impl Error for TranslationBundleError {
116 fn source(&self) -> Option<&(dyn Error + 'static)> {
118 TranslationBundleError::ReadFtl(e) => Some(e),
119 TranslationBundleError::ParseFtl(e) => Some(e),
120 TranslationBundleError::AddResource(e) => Some(e),
121 TranslationBundleError::MissingLocale => None,
122 TranslationBundleError::ReadLocalesDir(e) => Some(e),
123 TranslationBundleError::ReadLocalesDirEntry(e) => Some(e),
124 TranslationBundleError::LocaleIsNotDir => None,
129 impl From<(FluentResource, Vec<ParserError>)> for TranslationBundleError {
130 fn from((_, mut errs): (FluentResource, Vec<ParserError>)) -> Self {
131 TranslationBundleError::ParseFtl(errs.pop().expect("failed ftl parse with no errors"))
135 impl From<Vec<FluentError>> for TranslationBundleError {
136 fn from(mut errs: Vec<FluentError>) -> Self {
137 TranslationBundleError::AddResource(
138 errs.pop().expect("failed adding resource to bundle with no errors"),
143 /// Returns Fluent bundle with the user's locale resources from
144 /// `$sysroot/share/locale/$requested_locale/*.ftl`.
146 /// If `-Z additional-ftl-path` was provided, load that resource and add it to the bundle
147 /// (overriding any conflicting messages).
148 #[instrument(level = "trace")]
149 pub fn fluent_bundle(
150 mut user_provided_sysroot: Option<PathBuf>,
151 mut sysroot_candidates: Vec<PathBuf>,
152 requested_locale: Option<LanguageIdentifier>,
153 additional_ftl_path: Option<&Path>,
154 with_directionality_markers: bool,
155 ) -> Result<Option<Lrc<FluentBundle>>, TranslationBundleError> {
156 if requested_locale.is_none() && additional_ftl_path.is_none() {
160 let fallback_locale = langid!("en-US");
161 let requested_fallback_locale = requested_locale.as_ref() == Some(&fallback_locale);
163 // If there is only `-Z additional-ftl-path`, assume locale is "en-US", otherwise use user
165 let locale = requested_locale.clone().unwrap_or(fallback_locale);
167 let mut bundle = new_bundle(vec![locale]);
169 // Fluent diagnostics can insert directionality isolation markers around interpolated variables
170 // indicating that there may be a shift from right-to-left to left-to-right text (or
171 // vice-versa). These are disabled because they are sometimes visible in the error output, but
172 // may be worth investigating in future (for example: if type names are left-to-right and the
173 // surrounding diagnostic messages are right-to-left, then these might be helpful).
174 bundle.set_use_isolating(with_directionality_markers);
176 // If the user requests the default locale then don't try to load anything.
177 if !requested_fallback_locale && let Some(requested_locale) = requested_locale {
178 let mut found_resources = false;
179 for sysroot in user_provided_sysroot.iter_mut().chain(sysroot_candidates.iter_mut()) {
180 sysroot.push("share");
181 sysroot.push("locale");
182 sysroot.push(requested_locale.to_string());
185 if !sysroot.exists() {
190 if !sysroot.is_dir() {
191 return Err(TranslationBundleError::LocaleIsNotDir);
194 for entry in sysroot.read_dir().map_err(TranslationBundleError::ReadLocalesDir)? {
195 let entry = entry.map_err(TranslationBundleError::ReadLocalesDirEntry)?;
196 let path = entry.path();
198 if path.extension().and_then(|s| s.to_str()) != Some("ftl") {
204 fs::read_to_string(path).map_err(TranslationBundleError::ReadFtl)?;
206 FluentResource::try_new(resource_str).map_err(TranslationBundleError::from)?;
208 bundle.add_resource(resource).map_err(TranslationBundleError::from)?;
209 found_resources = true;
213 if !found_resources {
214 return Err(TranslationBundleError::MissingLocale);
218 if let Some(additional_ftl_path) = additional_ftl_path {
220 fs::read_to_string(additional_ftl_path).map_err(TranslationBundleError::ReadFtl)?;
222 FluentResource::try_new(resource_str).map_err(TranslationBundleError::from)?;
224 bundle.add_resource_overriding(resource);
227 let bundle = Lrc::new(bundle);
231 /// Type alias for the result of `fallback_fluent_bundle` - a reference-counted pointer to a lazily
232 /// evaluated fluent bundle.
233 pub type LazyFallbackBundle = Lrc<Lazy<FluentBundle, impl FnOnce() -> FluentBundle>>;
235 /// Return the default `FluentBundle` with standard "en-US" diagnostic messages.
236 #[instrument(level = "trace")]
237 pub fn fallback_fluent_bundle(
238 resources: &'static [&'static str],
239 with_directionality_markers: bool,
240 ) -> LazyFallbackBundle {
241 Lrc::new(Lazy::new(move || {
242 let mut fallback_bundle = new_bundle(vec![langid!("en-US")]);
243 // See comment in `fluent_bundle`.
244 fallback_bundle.set_use_isolating(with_directionality_markers);
246 for resource in resources {
247 let resource = FluentResource::try_new(resource.to_string())
248 .expect("failed to parse fallback fluent resource");
250 fallback_bundle.add_resource_overriding(resource);
257 /// Identifier for the Fluent message/attribute corresponding to a diagnostic message.
258 type FluentId = Cow<'static, str>;
260 /// Abstraction over a message in a subdiagnostic (i.e. label, note, help, etc) to support both
261 /// translatable and non-translatable diagnostic messages.
263 /// Translatable messages for subdiagnostics are typically attributes attached to a larger Fluent
264 /// message so messages of this type must be combined with a `DiagnosticMessage` (using
265 /// `DiagnosticMessage::with_subdiagnostic_message`) before rendering. However, subdiagnostics from
266 /// the `SessionSubdiagnostic` derive refer to Fluent identifiers directly.
267 #[rustc_diagnostic_item = "SubdiagnosticMessage"]
268 pub enum SubdiagnosticMessage {
269 /// Non-translatable diagnostic message.
270 // FIXME(davidtwco): can a `Cow<'static, str>` be used here?
272 /// Identifier of a Fluent message. Instances of this variant are generated by the
273 /// `SessionSubdiagnostic` derive.
274 FluentIdentifier(FluentId),
275 /// Attribute of a Fluent message. Needs to be combined with a Fluent identifier to produce an
276 /// actual translated message. Instances of this variant are generated by the `fluent_messages`
279 /// <https://projectfluent.org/fluent/guide/attributes.html>
280 FluentAttr(FluentId),
283 /// `From` impl that enables existing diagnostic calls to functions which now take
284 /// `impl Into<SubdiagnosticMessage>` to continue to work as before.
285 impl<S: Into<String>> From<S> for SubdiagnosticMessage {
286 fn from(s: S) -> Self {
287 SubdiagnosticMessage::Str(s.into())
291 /// Abstraction over a message in a diagnostic to support both translatable and non-translatable
292 /// diagnostic messages.
294 /// Intended to be removed once diagnostics are entirely translatable.
295 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
296 #[rustc_diagnostic_item = "DiagnosticMessage"]
297 pub enum DiagnosticMessage {
298 /// Non-translatable diagnostic message.
299 // FIXME(davidtwco): can a `Cow<'static, str>` be used here?
301 /// Identifier for a Fluent message (with optional attribute) corresponding to the diagnostic
304 /// <https://projectfluent.org/fluent/guide/hello.html>
305 /// <https://projectfluent.org/fluent/guide/attributes.html>
306 FluentIdentifier(FluentId, Option<FluentId>),
309 impl DiagnosticMessage {
310 /// Given a `SubdiagnosticMessage` which may contain a Fluent attribute, create a new
311 /// `DiagnosticMessage` that combines that attribute with the Fluent identifier of `self`.
313 /// - If the `SubdiagnosticMessage` is non-translatable then return the message as a
314 /// `DiagnosticMessage`.
315 /// - If `self` is non-translatable then return `self`'s message.
316 pub fn with_subdiagnostic_message(&self, sub: SubdiagnosticMessage) -> Self {
317 let attr = match sub {
318 SubdiagnosticMessage::Str(s) => return DiagnosticMessage::Str(s),
319 SubdiagnosticMessage::FluentIdentifier(id) => {
320 return DiagnosticMessage::FluentIdentifier(id, None);
322 SubdiagnosticMessage::FluentAttr(attr) => attr,
326 DiagnosticMessage::Str(s) => DiagnosticMessage::Str(s.clone()),
327 DiagnosticMessage::FluentIdentifier(id, _) => {
328 DiagnosticMessage::FluentIdentifier(id.clone(), Some(attr))
333 /// Returns the `String` contained within the `DiagnosticMessage::Str` variant, assuming that
334 /// this diagnostic message is of the legacy, non-translatable variety. Panics if this
335 /// assumption does not hold.
337 /// Don't use this - it exists to support some places that do comparison with diagnostic
339 pub fn expect_str(&self) -> &str {
341 DiagnosticMessage::Str(s) => s,
342 _ => panic!("expected non-translatable diagnostic message"),
347 /// `From` impl that enables existing diagnostic calls to functions which now take
348 /// `impl Into<DiagnosticMessage>` to continue to work as before.
349 impl<S: Into<String>> From<S> for DiagnosticMessage {
350 fn from(s: S) -> Self {
351 DiagnosticMessage::Str(s.into())
355 /// Translating *into* a subdiagnostic message from a diagnostic message is a little strange - but
356 /// the subdiagnostic functions (e.g. `span_label`) take a `SubdiagnosticMessage` and the
357 /// subdiagnostic derive refers to typed identifiers that are `DiagnosticMessage`s, so need to be
358 /// able to convert between these, as much as they'll be converted back into `DiagnosticMessage`
359 /// using `with_subdiagnostic_message` eventually. Don't use this other than for the derive.
360 impl Into<SubdiagnosticMessage> for DiagnosticMessage {
361 fn into(self) -> SubdiagnosticMessage {
363 DiagnosticMessage::Str(s) => SubdiagnosticMessage::Str(s),
364 DiagnosticMessage::FluentIdentifier(id, None) => {
365 SubdiagnosticMessage::FluentIdentifier(id)
367 // There isn't really a sensible behaviour for this because it loses information but
368 // this is the most sensible of the behaviours.
369 DiagnosticMessage::FluentIdentifier(_, Some(attr)) => {
370 SubdiagnosticMessage::FluentAttr(attr)
376 /// A span together with some additional data.
377 #[derive(Clone, Debug)]
378 pub struct SpanLabel {
379 /// The span we are going to include in the final snippet.
382 /// Is this a primary span? This is the "locus" of the message,
383 /// and is indicated with a `^^^^` underline, versus `----`.
384 pub is_primary: bool,
386 /// What label should we attach to this span (if any)?
387 pub label: Option<DiagnosticMessage>,
390 /// A collection of `Span`s.
392 /// Spans have two orthogonal attributes:
394 /// - They can be *primary spans*. In this case they are the locus of
395 /// the error, and would be rendered with `^^^`.
396 /// - They can have a *label*. In this case, the label is written next
397 /// to the mark in the snippet when we render.
398 #[derive(Clone, Debug, Hash, PartialEq, Eq, Encodable, Decodable)]
399 pub struct MultiSpan {
400 primary_spans: Vec<Span>,
401 span_labels: Vec<(Span, DiagnosticMessage)>,
406 pub fn new() -> MultiSpan {
407 MultiSpan { primary_spans: vec![], span_labels: vec![] }
410 pub fn from_span(primary_span: Span) -> MultiSpan {
411 MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
414 pub fn from_spans(mut vec: Vec<Span>) -> MultiSpan {
416 MultiSpan { primary_spans: vec, span_labels: vec![] }
419 pub fn push_span_label(&mut self, span: Span, label: impl Into<DiagnosticMessage>) {
420 self.span_labels.push((span, label.into()));
423 /// Selects the first primary span (if any).
424 pub fn primary_span(&self) -> Option<Span> {
425 self.primary_spans.first().cloned()
428 /// Returns all primary spans.
429 pub fn primary_spans(&self) -> &[Span] {
433 /// Returns `true` if any of the primary spans are displayable.
434 pub fn has_primary_spans(&self) -> bool {
438 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
439 pub fn is_dummy(&self) -> bool {
440 self.primary_spans.iter().all(|sp| sp.is_dummy())
443 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
444 /// display well (like std macros). Returns whether replacements occurred.
445 pub fn replace(&mut self, before: Span, after: Span) -> bool {
446 let mut replacements_occurred = false;
447 for primary_span in &mut self.primary_spans {
448 if *primary_span == before {
449 *primary_span = after;
450 replacements_occurred = true;
453 for span_label in &mut self.span_labels {
454 if span_label.0 == before {
455 span_label.0 = after;
456 replacements_occurred = true;
459 replacements_occurred
462 /// Returns the strings to highlight. We always ensure that there
463 /// is an entry for each of the primary spans -- for each primary
464 /// span `P`, if there is at least one label with span `P`, we return
465 /// those labels (marked as primary). But otherwise we return
466 /// `SpanLabel` instances with empty labels.
467 pub fn span_labels(&self) -> Vec<SpanLabel> {
468 let is_primary = |span| self.primary_spans.contains(&span);
470 let mut span_labels = self
473 .map(|&(span, ref label)| SpanLabel {
475 is_primary: is_primary(span),
476 label: Some(label.clone()),
478 .collect::<Vec<_>>();
480 for &span in &self.primary_spans {
481 if !span_labels.iter().any(|sl| sl.span == span) {
482 span_labels.push(SpanLabel { span, is_primary: true, label: None });
489 /// Returns `true` if any of the span labels is displayable.
490 pub fn has_span_labels(&self) -> bool {
491 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
495 impl From<Span> for MultiSpan {
496 fn from(span: Span) -> MultiSpan {
497 MultiSpan::from_span(span)
501 impl From<Vec<Span>> for MultiSpan {
502 fn from(spans: Vec<Span>) -> MultiSpan {
503 MultiSpan::from_spans(spans)