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)]
11 use fluent_bundle::FluentResource;
12 use fluent_syntax::parser::ParserError;
13 use rustc_data_structures::sync::Lrc;
14 use rustc_macros::{fluent_messages, Decodable, Encodable};
17 use std::error::Error;
21 use std::path::{Path, PathBuf};
23 #[cfg(not(parallel_compiler))]
24 use std::cell::LazyCell as Lazy;
25 #[cfg(parallel_compiler)]
26 use std::sync::LazyLock as Lazy;
28 #[cfg(parallel_compiler)]
29 use intl_memoizer::concurrent::IntlLangMemoizer;
30 #[cfg(not(parallel_compiler))]
31 use intl_memoizer::IntlLangMemoizer;
33 pub use fluent_bundle::{FluentArgs, FluentError, FluentValue};
34 pub use unic_langid::{langid, LanguageIdentifier};
36 // Generates `DEFAULT_LOCALE_RESOURCES` static and `fluent_generated` module.
38 ast_lowering => "../locales/en-US/ast_lowering.ftl",
39 ast_passes => "../locales/en-US/ast_passes.ftl",
40 attr => "../locales/en-US/attr.ftl",
41 borrowck => "../locales/en-US/borrowck.ftl",
42 builtin_macros => "../locales/en-US/builtin_macros.ftl",
43 compiletest => "../locales/en-US/compiletest.ftl",
44 const_eval => "../locales/en-US/const_eval.ftl",
45 codegen_gcc => "../locales/en-US/codegen_gcc.ftl",
46 driver => "../locales/en-US/driver.ftl",
47 expand => "../locales/en-US/expand.ftl",
48 hir_analysis => "../locales/en-US/hir_analysis.ftl",
49 infer => "../locales/en-US/infer.ftl",
50 interface => "../locales/en-US/interface.ftl",
51 lint => "../locales/en-US/lint.ftl",
52 metadata => "../locales/en-US/metadata.ftl",
53 middle => "../locales/en-US/middle.ftl",
54 mir_dataflow => "../locales/en-US/mir_dataflow.ftl",
55 monomorphize => "../locales/en-US/monomorphize.ftl",
56 parser => "../locales/en-US/parser.ftl",
57 passes => "../locales/en-US/passes.ftl",
58 plugin_impl => "../locales/en-US/plugin_impl.ftl",
59 privacy => "../locales/en-US/privacy.ftl",
60 query_system => "../locales/en-US/query_system.ftl",
61 save_analysis => "../locales/en-US/save_analysis.ftl",
62 session => "../locales/en-US/session.ftl",
63 symbol_mangling => "../locales/en-US/symbol_mangling.ftl",
64 trait_selection => "../locales/en-US/trait_selection.ftl",
65 ty_utils => "../locales/en-US/ty_utils.ftl",
68 pub use fluent_generated::{self as fluent, DEFAULT_LOCALE_RESOURCES};
70 pub type FluentBundle = fluent_bundle::bundle::FluentBundle<FluentResource, IntlLangMemoizer>;
72 #[cfg(parallel_compiler)]
73 fn new_bundle(locales: Vec<LanguageIdentifier>) -> FluentBundle {
74 FluentBundle::new_concurrent(locales)
77 #[cfg(not(parallel_compiler))]
78 fn new_bundle(locales: Vec<LanguageIdentifier>) -> FluentBundle {
79 FluentBundle::new(locales)
83 pub enum TranslationBundleError {
84 /// Failed to read from `.ftl` file.
86 /// Failed to parse contents of `.ftl` file.
87 ParseFtl(ParserError),
88 /// Failed to add `FluentResource` to `FluentBundle`.
89 AddResource(FluentError),
90 /// `$sysroot/share/locale/$locale` does not exist.
92 /// Cannot read directory entries of `$sysroot/share/locale/$locale`.
93 ReadLocalesDir(io::Error),
94 /// Cannot read directory entry of `$sysroot/share/locale/$locale`.
95 ReadLocalesDirEntry(io::Error),
96 /// `$sysroot/share/locale/$locale` is not a directory.
100 impl fmt::Display for TranslationBundleError {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 TranslationBundleError::ReadFtl(e) => write!(f, "could not read ftl file: {}", e),
104 TranslationBundleError::ParseFtl(e) => {
105 write!(f, "could not parse ftl file: {}", e)
107 TranslationBundleError::AddResource(e) => write!(f, "failed to add resource: {}", e),
108 TranslationBundleError::MissingLocale => write!(f, "missing locale directory"),
109 TranslationBundleError::ReadLocalesDir(e) => {
110 write!(f, "could not read locales dir: {}", e)
112 TranslationBundleError::ReadLocalesDirEntry(e) => {
113 write!(f, "could not read locales dir entry: {}", e)
115 TranslationBundleError::LocaleIsNotDir => {
116 write!(f, "`$sysroot/share/locales/$locale` is not a directory")
122 impl Error for TranslationBundleError {
123 fn source(&self) -> Option<&(dyn Error + 'static)> {
125 TranslationBundleError::ReadFtl(e) => Some(e),
126 TranslationBundleError::ParseFtl(e) => Some(e),
127 TranslationBundleError::AddResource(e) => Some(e),
128 TranslationBundleError::MissingLocale => None,
129 TranslationBundleError::ReadLocalesDir(e) => Some(e),
130 TranslationBundleError::ReadLocalesDirEntry(e) => Some(e),
131 TranslationBundleError::LocaleIsNotDir => None,
136 impl From<(FluentResource, Vec<ParserError>)> for TranslationBundleError {
137 fn from((_, mut errs): (FluentResource, Vec<ParserError>)) -> Self {
138 TranslationBundleError::ParseFtl(errs.pop().expect("failed ftl parse with no errors"))
142 impl From<Vec<FluentError>> for TranslationBundleError {
143 fn from(mut errs: Vec<FluentError>) -> Self {
144 TranslationBundleError::AddResource(
145 errs.pop().expect("failed adding resource to bundle with no errors"),
150 /// Returns Fluent bundle with the user's locale resources from
151 /// `$sysroot/share/locale/$requested_locale/*.ftl`.
153 /// If `-Z additional-ftl-path` was provided, load that resource and add it to the bundle
154 /// (overriding any conflicting messages).
155 #[instrument(level = "trace")]
156 pub fn fluent_bundle(
157 mut user_provided_sysroot: Option<PathBuf>,
158 mut sysroot_candidates: Vec<PathBuf>,
159 requested_locale: Option<LanguageIdentifier>,
160 additional_ftl_path: Option<&Path>,
161 with_directionality_markers: bool,
162 ) -> Result<Option<Lrc<FluentBundle>>, TranslationBundleError> {
163 if requested_locale.is_none() && additional_ftl_path.is_none() {
167 let fallback_locale = langid!("en-US");
168 let requested_fallback_locale = requested_locale.as_ref() == Some(&fallback_locale);
170 // If there is only `-Z additional-ftl-path`, assume locale is "en-US", otherwise use user
172 let locale = requested_locale.clone().unwrap_or(fallback_locale);
174 let mut bundle = new_bundle(vec![locale]);
176 // Fluent diagnostics can insert directionality isolation markers around interpolated variables
177 // indicating that there may be a shift from right-to-left to left-to-right text (or
178 // vice-versa). These are disabled because they are sometimes visible in the error output, but
179 // may be worth investigating in future (for example: if type names are left-to-right and the
180 // surrounding diagnostic messages are right-to-left, then these might be helpful).
181 bundle.set_use_isolating(with_directionality_markers);
183 // If the user requests the default locale then don't try to load anything.
184 if !requested_fallback_locale && let Some(requested_locale) = requested_locale {
185 let mut found_resources = false;
186 for sysroot in user_provided_sysroot.iter_mut().chain(sysroot_candidates.iter_mut()) {
187 sysroot.push("share");
188 sysroot.push("locale");
189 sysroot.push(requested_locale.to_string());
192 if !sysroot.exists() {
197 if !sysroot.is_dir() {
198 return Err(TranslationBundleError::LocaleIsNotDir);
201 for entry in sysroot.read_dir().map_err(TranslationBundleError::ReadLocalesDir)? {
202 let entry = entry.map_err(TranslationBundleError::ReadLocalesDirEntry)?;
203 let path = entry.path();
205 if path.extension().and_then(|s| s.to_str()) != Some("ftl") {
211 fs::read_to_string(path).map_err(TranslationBundleError::ReadFtl)?;
213 FluentResource::try_new(resource_str).map_err(TranslationBundleError::from)?;
215 bundle.add_resource(resource).map_err(TranslationBundleError::from)?;
216 found_resources = true;
220 if !found_resources {
221 return Err(TranslationBundleError::MissingLocale);
225 if let Some(additional_ftl_path) = additional_ftl_path {
227 fs::read_to_string(additional_ftl_path).map_err(TranslationBundleError::ReadFtl)?;
229 FluentResource::try_new(resource_str).map_err(TranslationBundleError::from)?;
231 bundle.add_resource_overriding(resource);
234 let bundle = Lrc::new(bundle);
238 /// Type alias for the result of `fallback_fluent_bundle` - a reference-counted pointer to a lazily
239 /// evaluated fluent bundle.
240 pub type LazyFallbackBundle = Lrc<Lazy<FluentBundle, impl FnOnce() -> FluentBundle>>;
242 /// Return the default `FluentBundle` with standard "en-US" diagnostic messages.
243 #[instrument(level = "trace")]
244 pub fn fallback_fluent_bundle(
245 resources: &'static [&'static str],
246 with_directionality_markers: bool,
247 ) -> LazyFallbackBundle {
248 Lrc::new(Lazy::new(move || {
249 let mut fallback_bundle = new_bundle(vec![langid!("en-US")]);
250 // See comment in `fluent_bundle`.
251 fallback_bundle.set_use_isolating(with_directionality_markers);
253 for resource in resources {
254 let resource = FluentResource::try_new(resource.to_string())
255 .expect("failed to parse fallback fluent resource");
257 fallback_bundle.add_resource_overriding(resource);
264 /// Identifier for the Fluent message/attribute corresponding to a diagnostic message.
265 type FluentId = Cow<'static, str>;
267 /// Abstraction over a message in a subdiagnostic (i.e. label, note, help, etc) to support both
268 /// translatable and non-translatable diagnostic messages.
270 /// Translatable messages for subdiagnostics are typically attributes attached to a larger Fluent
271 /// message so messages of this type must be combined with a `DiagnosticMessage` (using
272 /// `DiagnosticMessage::with_subdiagnostic_message`) before rendering. However, subdiagnostics from
273 /// the `Subdiagnostic` derive refer to Fluent identifiers directly.
274 #[rustc_diagnostic_item = "SubdiagnosticMessage"]
275 pub enum SubdiagnosticMessage {
276 /// Non-translatable diagnostic message.
277 // FIXME(davidtwco): can a `Cow<'static, str>` be used here?
279 /// Identifier of a Fluent message. Instances of this variant are generated by the
280 /// `Subdiagnostic` derive.
281 FluentIdentifier(FluentId),
282 /// Attribute of a Fluent message. Needs to be combined with a Fluent identifier to produce an
283 /// actual translated message. Instances of this variant are generated by the `fluent_messages`
286 /// <https://projectfluent.org/fluent/guide/attributes.html>
287 FluentAttr(FluentId),
290 /// `From` impl that enables existing diagnostic calls to functions which now take
291 /// `impl Into<SubdiagnosticMessage>` to continue to work as before.
292 impl<S: Into<String>> From<S> for SubdiagnosticMessage {
293 fn from(s: S) -> Self {
294 SubdiagnosticMessage::Str(s.into())
298 /// Abstraction over a message in a diagnostic to support both translatable and non-translatable
299 /// diagnostic messages.
301 /// Intended to be removed once diagnostics are entirely translatable.
302 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
303 #[rustc_diagnostic_item = "DiagnosticMessage"]
304 pub enum DiagnosticMessage {
305 /// Non-translatable diagnostic message.
306 // FIXME(davidtwco): can a `Cow<'static, str>` be used here?
308 /// Identifier for a Fluent message (with optional attribute) corresponding to the diagnostic
311 /// <https://projectfluent.org/fluent/guide/hello.html>
312 /// <https://projectfluent.org/fluent/guide/attributes.html>
313 FluentIdentifier(FluentId, Option<FluentId>),
316 impl DiagnosticMessage {
317 /// Given a `SubdiagnosticMessage` which may contain a Fluent attribute, create a new
318 /// `DiagnosticMessage` that combines that attribute with the Fluent identifier of `self`.
320 /// - If the `SubdiagnosticMessage` is non-translatable then return the message as a
321 /// `DiagnosticMessage`.
322 /// - If `self` is non-translatable then return `self`'s message.
323 pub fn with_subdiagnostic_message(&self, sub: SubdiagnosticMessage) -> Self {
324 let attr = match sub {
325 SubdiagnosticMessage::Str(s) => return DiagnosticMessage::Str(s),
326 SubdiagnosticMessage::FluentIdentifier(id) => {
327 return DiagnosticMessage::FluentIdentifier(id, None);
329 SubdiagnosticMessage::FluentAttr(attr) => attr,
333 DiagnosticMessage::Str(s) => DiagnosticMessage::Str(s.clone()),
334 DiagnosticMessage::FluentIdentifier(id, _) => {
335 DiagnosticMessage::FluentIdentifier(id.clone(), Some(attr))
341 /// `From` impl that enables existing diagnostic calls to functions which now take
342 /// `impl Into<DiagnosticMessage>` to continue to work as before.
343 impl<S: Into<String>> From<S> for DiagnosticMessage {
344 fn from(s: S) -> Self {
345 DiagnosticMessage::Str(s.into())
349 /// A workaround for "good path" ICEs when formatting types in disables lints.
351 /// Delays formatting until `.into(): DiagnosticMessage` is used.
352 pub struct DelayDm<F>(pub F);
354 impl<F: FnOnce() -> String> From<DelayDm<F>> for DiagnosticMessage {
355 fn from(DelayDm(f): DelayDm<F>) -> Self {
356 DiagnosticMessage::from(f())
360 /// Translating *into* a subdiagnostic message from a diagnostic message is a little strange - but
361 /// the subdiagnostic functions (e.g. `span_label`) take a `SubdiagnosticMessage` and the
362 /// subdiagnostic derive refers to typed identifiers that are `DiagnosticMessage`s, so need to be
363 /// able to convert between these, as much as they'll be converted back into `DiagnosticMessage`
364 /// using `with_subdiagnostic_message` eventually. Don't use this other than for the derive.
365 impl Into<SubdiagnosticMessage> for DiagnosticMessage {
366 fn into(self) -> SubdiagnosticMessage {
368 DiagnosticMessage::Str(s) => SubdiagnosticMessage::Str(s),
369 DiagnosticMessage::FluentIdentifier(id, None) => {
370 SubdiagnosticMessage::FluentIdentifier(id)
372 // There isn't really a sensible behaviour for this because it loses information but
373 // this is the most sensible of the behaviours.
374 DiagnosticMessage::FluentIdentifier(_, Some(attr)) => {
375 SubdiagnosticMessage::FluentAttr(attr)
381 /// A span together with some additional data.
382 #[derive(Clone, Debug)]
383 pub struct SpanLabel {
384 /// The span we are going to include in the final snippet.
387 /// Is this a primary span? This is the "locus" of the message,
388 /// and is indicated with a `^^^^` underline, versus `----`.
389 pub is_primary: bool,
391 /// What label should we attach to this span (if any)?
392 pub label: Option<DiagnosticMessage>,
395 /// A collection of `Span`s.
397 /// Spans have two orthogonal attributes:
399 /// - They can be *primary spans*. In this case they are the locus of
400 /// the error, and would be rendered with `^^^`.
401 /// - They can have a *label*. In this case, the label is written next
402 /// to the mark in the snippet when we render.
403 #[derive(Clone, Debug, Hash, PartialEq, Eq, Encodable, Decodable)]
404 pub struct MultiSpan {
405 primary_spans: Vec<Span>,
406 span_labels: Vec<(Span, DiagnosticMessage)>,
411 pub fn new() -> MultiSpan {
412 MultiSpan { primary_spans: vec![], span_labels: vec![] }
415 pub fn from_span(primary_span: Span) -> MultiSpan {
416 MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
419 pub fn from_spans(mut vec: Vec<Span>) -> MultiSpan {
421 MultiSpan { primary_spans: vec, span_labels: vec![] }
424 pub fn push_span_label(&mut self, span: Span, label: impl Into<DiagnosticMessage>) {
425 self.span_labels.push((span, label.into()));
428 /// Selects the first primary span (if any).
429 pub fn primary_span(&self) -> Option<Span> {
430 self.primary_spans.first().cloned()
433 /// Returns all primary spans.
434 pub fn primary_spans(&self) -> &[Span] {
438 /// Returns `true` if any of the primary spans are displayable.
439 pub fn has_primary_spans(&self) -> bool {
443 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
444 pub fn is_dummy(&self) -> bool {
445 self.primary_spans.iter().all(|sp| sp.is_dummy())
448 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
449 /// display well (like std macros). Returns whether replacements occurred.
450 pub fn replace(&mut self, before: Span, after: Span) -> bool {
451 let mut replacements_occurred = false;
452 for primary_span in &mut self.primary_spans {
453 if *primary_span == before {
454 *primary_span = after;
455 replacements_occurred = true;
458 for span_label in &mut self.span_labels {
459 if span_label.0 == before {
460 span_label.0 = after;
461 replacements_occurred = true;
464 replacements_occurred
467 /// Returns the strings to highlight. We always ensure that there
468 /// is an entry for each of the primary spans -- for each primary
469 /// span `P`, if there is at least one label with span `P`, we return
470 /// those labels (marked as primary). But otherwise we return
471 /// `SpanLabel` instances with empty labels.
472 pub fn span_labels(&self) -> Vec<SpanLabel> {
473 let is_primary = |span| self.primary_spans.contains(&span);
475 let mut span_labels = self
478 .map(|&(span, ref label)| SpanLabel {
480 is_primary: is_primary(span),
481 label: Some(label.clone()),
483 .collect::<Vec<_>>();
485 for &span in &self.primary_spans {
486 if !span_labels.iter().any(|sl| sl.span == span) {
487 span_labels.push(SpanLabel { span, is_primary: true, label: None });
494 /// Returns `true` if any of the span labels is displayable.
495 pub fn has_span_labels(&self) -> bool {
496 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
500 impl From<Span> for MultiSpan {
501 fn from(span: Span) -> MultiSpan {
502 MultiSpan::from_span(span)
506 impl From<Vec<Span>> for MultiSpan {
507 fn from(spans: Vec<Span>) -> MultiSpan {
508 MultiSpan::from_spans(spans)