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 const_eval => "../locales/en-US/const_eval.ftl",
44 driver => "../locales/en-US/driver.ftl",
45 expand => "../locales/en-US/expand.ftl",
46 session => "../locales/en-US/session.ftl",
47 interface => "../locales/en-US/interface.ftl",
48 infer => "../locales/en-US/infer.ftl",
49 lint => "../locales/en-US/lint.ftl",
50 monomorphize => "../locales/en-US/monomorphize.ftl",
51 metadata => "../locales/en-US/metadata.ftl",
52 parser => "../locales/en-US/parser.ftl",
53 passes => "../locales/en-US/passes.ftl",
54 plugin_impl => "../locales/en-US/plugin_impl.ftl",
55 privacy => "../locales/en-US/privacy.ftl",
56 query_system => "../locales/en-US/query_system.ftl",
57 trait_selection => "../locales/en-US/trait_selection.ftl",
58 save_analysis => "../locales/en-US/save_analysis.ftl",
59 ty_utils => "../locales/en-US/ty_utils.ftl",
60 typeck => "../locales/en-US/typeck.ftl",
61 mir_dataflow => "../locales/en-US/mir_dataflow.ftl",
62 symbol_mangling => "../locales/en-US/symbol_mangling.ftl",
65 pub use fluent_generated::{self as fluent, DEFAULT_LOCALE_RESOURCES};
67 pub type FluentBundle = fluent_bundle::bundle::FluentBundle<FluentResource, IntlLangMemoizer>;
69 #[cfg(parallel_compiler)]
70 fn new_bundle(locales: Vec<LanguageIdentifier>) -> FluentBundle {
71 FluentBundle::new_concurrent(locales)
74 #[cfg(not(parallel_compiler))]
75 fn new_bundle(locales: Vec<LanguageIdentifier>) -> FluentBundle {
76 FluentBundle::new(locales)
80 pub enum TranslationBundleError {
81 /// Failed to read from `.ftl` file.
83 /// Failed to parse contents of `.ftl` file.
84 ParseFtl(ParserError),
85 /// Failed to add `FluentResource` to `FluentBundle`.
86 AddResource(FluentError),
87 /// `$sysroot/share/locale/$locale` does not exist.
89 /// Cannot read directory entries of `$sysroot/share/locale/$locale`.
90 ReadLocalesDir(io::Error),
91 /// Cannot read directory entry of `$sysroot/share/locale/$locale`.
92 ReadLocalesDirEntry(io::Error),
93 /// `$sysroot/share/locale/$locale` is not a directory.
97 impl fmt::Display for TranslationBundleError {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 TranslationBundleError::ReadFtl(e) => write!(f, "could not read ftl file: {}", e),
101 TranslationBundleError::ParseFtl(e) => {
102 write!(f, "could not parse ftl file: {}", e)
104 TranslationBundleError::AddResource(e) => write!(f, "failed to add resource: {}", e),
105 TranslationBundleError::MissingLocale => write!(f, "missing locale directory"),
106 TranslationBundleError::ReadLocalesDir(e) => {
107 write!(f, "could not read locales dir: {}", e)
109 TranslationBundleError::ReadLocalesDirEntry(e) => {
110 write!(f, "could not read locales dir entry: {}", e)
112 TranslationBundleError::LocaleIsNotDir => {
113 write!(f, "`$sysroot/share/locales/$locale` is not a directory")
119 impl Error for TranslationBundleError {
120 fn source(&self) -> Option<&(dyn Error + 'static)> {
122 TranslationBundleError::ReadFtl(e) => Some(e),
123 TranslationBundleError::ParseFtl(e) => Some(e),
124 TranslationBundleError::AddResource(e) => Some(e),
125 TranslationBundleError::MissingLocale => None,
126 TranslationBundleError::ReadLocalesDir(e) => Some(e),
127 TranslationBundleError::ReadLocalesDirEntry(e) => Some(e),
128 TranslationBundleError::LocaleIsNotDir => None,
133 impl From<(FluentResource, Vec<ParserError>)> for TranslationBundleError {
134 fn from((_, mut errs): (FluentResource, Vec<ParserError>)) -> Self {
135 TranslationBundleError::ParseFtl(errs.pop().expect("failed ftl parse with no errors"))
139 impl From<Vec<FluentError>> for TranslationBundleError {
140 fn from(mut errs: Vec<FluentError>) -> Self {
141 TranslationBundleError::AddResource(
142 errs.pop().expect("failed adding resource to bundle with no errors"),
147 /// Returns Fluent bundle with the user's locale resources from
148 /// `$sysroot/share/locale/$requested_locale/*.ftl`.
150 /// If `-Z additional-ftl-path` was provided, load that resource and add it to the bundle
151 /// (overriding any conflicting messages).
152 #[instrument(level = "trace")]
153 pub fn fluent_bundle(
154 mut user_provided_sysroot: Option<PathBuf>,
155 mut sysroot_candidates: Vec<PathBuf>,
156 requested_locale: Option<LanguageIdentifier>,
157 additional_ftl_path: Option<&Path>,
158 with_directionality_markers: bool,
159 ) -> Result<Option<Lrc<FluentBundle>>, TranslationBundleError> {
160 if requested_locale.is_none() && additional_ftl_path.is_none() {
164 let fallback_locale = langid!("en-US");
165 let requested_fallback_locale = requested_locale.as_ref() == Some(&fallback_locale);
167 // If there is only `-Z additional-ftl-path`, assume locale is "en-US", otherwise use user
169 let locale = requested_locale.clone().unwrap_or(fallback_locale);
171 let mut bundle = new_bundle(vec![locale]);
173 // Fluent diagnostics can insert directionality isolation markers around interpolated variables
174 // indicating that there may be a shift from right-to-left to left-to-right text (or
175 // vice-versa). These are disabled because they are sometimes visible in the error output, but
176 // may be worth investigating in future (for example: if type names are left-to-right and the
177 // surrounding diagnostic messages are right-to-left, then these might be helpful).
178 bundle.set_use_isolating(with_directionality_markers);
180 // If the user requests the default locale then don't try to load anything.
181 if !requested_fallback_locale && let Some(requested_locale) = requested_locale {
182 let mut found_resources = false;
183 for sysroot in user_provided_sysroot.iter_mut().chain(sysroot_candidates.iter_mut()) {
184 sysroot.push("share");
185 sysroot.push("locale");
186 sysroot.push(requested_locale.to_string());
189 if !sysroot.exists() {
194 if !sysroot.is_dir() {
195 return Err(TranslationBundleError::LocaleIsNotDir);
198 for entry in sysroot.read_dir().map_err(TranslationBundleError::ReadLocalesDir)? {
199 let entry = entry.map_err(TranslationBundleError::ReadLocalesDirEntry)?;
200 let path = entry.path();
202 if path.extension().and_then(|s| s.to_str()) != Some("ftl") {
208 fs::read_to_string(path).map_err(TranslationBundleError::ReadFtl)?;
210 FluentResource::try_new(resource_str).map_err(TranslationBundleError::from)?;
212 bundle.add_resource(resource).map_err(TranslationBundleError::from)?;
213 found_resources = true;
217 if !found_resources {
218 return Err(TranslationBundleError::MissingLocale);
222 if let Some(additional_ftl_path) = additional_ftl_path {
224 fs::read_to_string(additional_ftl_path).map_err(TranslationBundleError::ReadFtl)?;
226 FluentResource::try_new(resource_str).map_err(TranslationBundleError::from)?;
228 bundle.add_resource_overriding(resource);
231 let bundle = Lrc::new(bundle);
235 /// Type alias for the result of `fallback_fluent_bundle` - a reference-counted pointer to a lazily
236 /// evaluated fluent bundle.
237 pub type LazyFallbackBundle = Lrc<Lazy<FluentBundle, impl FnOnce() -> FluentBundle>>;
239 /// Return the default `FluentBundle` with standard "en-US" diagnostic messages.
240 #[instrument(level = "trace")]
241 pub fn fallback_fluent_bundle(
242 resources: &'static [&'static str],
243 with_directionality_markers: bool,
244 ) -> LazyFallbackBundle {
245 Lrc::new(Lazy::new(move || {
246 let mut fallback_bundle = new_bundle(vec![langid!("en-US")]);
247 // See comment in `fluent_bundle`.
248 fallback_bundle.set_use_isolating(with_directionality_markers);
250 for resource in resources {
251 let resource = FluentResource::try_new(resource.to_string())
252 .expect("failed to parse fallback fluent resource");
254 fallback_bundle.add_resource_overriding(resource);
261 /// Identifier for the Fluent message/attribute corresponding to a diagnostic message.
262 type FluentId = Cow<'static, str>;
264 /// Abstraction over a message in a subdiagnostic (i.e. label, note, help, etc) to support both
265 /// translatable and non-translatable diagnostic messages.
267 /// Translatable messages for subdiagnostics are typically attributes attached to a larger Fluent
268 /// message so messages of this type must be combined with a `DiagnosticMessage` (using
269 /// `DiagnosticMessage::with_subdiagnostic_message`) before rendering. However, subdiagnostics from
270 /// the `SessionSubdiagnostic` derive refer to Fluent identifiers directly.
271 #[rustc_diagnostic_item = "SubdiagnosticMessage"]
272 pub enum SubdiagnosticMessage {
273 /// Non-translatable diagnostic message.
274 // FIXME(davidtwco): can a `Cow<'static, str>` be used here?
276 /// Identifier of a Fluent message. Instances of this variant are generated by the
277 /// `SessionSubdiagnostic` derive.
278 FluentIdentifier(FluentId),
279 /// Attribute of a Fluent message. Needs to be combined with a Fluent identifier to produce an
280 /// actual translated message. Instances of this variant are generated by the `fluent_messages`
283 /// <https://projectfluent.org/fluent/guide/attributes.html>
284 FluentAttr(FluentId),
287 /// `From` impl that enables existing diagnostic calls to functions which now take
288 /// `impl Into<SubdiagnosticMessage>` to continue to work as before.
289 impl<S: Into<String>> From<S> for SubdiagnosticMessage {
290 fn from(s: S) -> Self {
291 SubdiagnosticMessage::Str(s.into())
295 /// Abstraction over a message in a diagnostic to support both translatable and non-translatable
296 /// diagnostic messages.
298 /// Intended to be removed once diagnostics are entirely translatable.
299 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
300 #[rustc_diagnostic_item = "DiagnosticMessage"]
301 pub enum DiagnosticMessage {
302 /// Non-translatable diagnostic message.
303 // FIXME(davidtwco): can a `Cow<'static, str>` be used here?
305 /// Identifier for a Fluent message (with optional attribute) corresponding to the diagnostic
308 /// <https://projectfluent.org/fluent/guide/hello.html>
309 /// <https://projectfluent.org/fluent/guide/attributes.html>
310 FluentIdentifier(FluentId, Option<FluentId>),
313 impl DiagnosticMessage {
314 /// Given a `SubdiagnosticMessage` which may contain a Fluent attribute, create a new
315 /// `DiagnosticMessage` that combines that attribute with the Fluent identifier of `self`.
317 /// - If the `SubdiagnosticMessage` is non-translatable then return the message as a
318 /// `DiagnosticMessage`.
319 /// - If `self` is non-translatable then return `self`'s message.
320 pub fn with_subdiagnostic_message(&self, sub: SubdiagnosticMessage) -> Self {
321 let attr = match sub {
322 SubdiagnosticMessage::Str(s) => return DiagnosticMessage::Str(s),
323 SubdiagnosticMessage::FluentIdentifier(id) => {
324 return DiagnosticMessage::FluentIdentifier(id, None);
326 SubdiagnosticMessage::FluentAttr(attr) => attr,
330 DiagnosticMessage::Str(s) => DiagnosticMessage::Str(s.clone()),
331 DiagnosticMessage::FluentIdentifier(id, _) => {
332 DiagnosticMessage::FluentIdentifier(id.clone(), Some(attr))
337 /// Returns the `String` contained within the `DiagnosticMessage::Str` variant, assuming that
338 /// this diagnostic message is of the legacy, non-translatable variety. Panics if this
339 /// assumption does not hold.
341 /// Don't use this - it exists to support some places that do comparison with diagnostic
343 pub fn expect_str(&self) -> &str {
345 DiagnosticMessage::Str(s) => s,
346 _ => panic!("expected non-translatable diagnostic message"),
351 /// `From` impl that enables existing diagnostic calls to functions which now take
352 /// `impl Into<DiagnosticMessage>` to continue to work as before.
353 impl<S: Into<String>> From<S> for DiagnosticMessage {
354 fn from(s: S) -> Self {
355 DiagnosticMessage::Str(s.into())
359 /// Translating *into* a subdiagnostic message from a diagnostic message is a little strange - but
360 /// the subdiagnostic functions (e.g. `span_label`) take a `SubdiagnosticMessage` and the
361 /// subdiagnostic derive refers to typed identifiers that are `DiagnosticMessage`s, so need to be
362 /// able to convert between these, as much as they'll be converted back into `DiagnosticMessage`
363 /// using `with_subdiagnostic_message` eventually. Don't use this other than for the derive.
364 impl Into<SubdiagnosticMessage> for DiagnosticMessage {
365 fn into(self) -> SubdiagnosticMessage {
367 DiagnosticMessage::Str(s) => SubdiagnosticMessage::Str(s),
368 DiagnosticMessage::FluentIdentifier(id, None) => {
369 SubdiagnosticMessage::FluentIdentifier(id)
371 // There isn't really a sensible behaviour for this because it loses information but
372 // this is the most sensible of the behaviours.
373 DiagnosticMessage::FluentIdentifier(_, Some(attr)) => {
374 SubdiagnosticMessage::FluentAttr(attr)
380 /// A span together with some additional data.
381 #[derive(Clone, Debug)]
382 pub struct SpanLabel {
383 /// The span we are going to include in the final snippet.
386 /// Is this a primary span? This is the "locus" of the message,
387 /// and is indicated with a `^^^^` underline, versus `----`.
388 pub is_primary: bool,
390 /// What label should we attach to this span (if any)?
391 pub label: Option<DiagnosticMessage>,
394 /// A collection of `Span`s.
396 /// Spans have two orthogonal attributes:
398 /// - They can be *primary spans*. In this case they are the locus of
399 /// the error, and would be rendered with `^^^`.
400 /// - They can have a *label*. In this case, the label is written next
401 /// to the mark in the snippet when we render.
402 #[derive(Clone, Debug, Hash, PartialEq, Eq, Encodable, Decodable)]
403 pub struct MultiSpan {
404 primary_spans: Vec<Span>,
405 span_labels: Vec<(Span, DiagnosticMessage)>,
410 pub fn new() -> MultiSpan {
411 MultiSpan { primary_spans: vec![], span_labels: vec![] }
414 pub fn from_span(primary_span: Span) -> MultiSpan {
415 MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
418 pub fn from_spans(mut vec: Vec<Span>) -> MultiSpan {
420 MultiSpan { primary_spans: vec, span_labels: vec![] }
423 pub fn push_span_label(&mut self, span: Span, label: impl Into<DiagnosticMessage>) {
424 self.span_labels.push((span, label.into()));
427 /// Selects the first primary span (if any).
428 pub fn primary_span(&self) -> Option<Span> {
429 self.primary_spans.first().cloned()
432 /// Returns all primary spans.
433 pub fn primary_spans(&self) -> &[Span] {
437 /// Returns `true` if any of the primary spans are displayable.
438 pub fn has_primary_spans(&self) -> bool {
442 /// Returns `true` if this contains only a dummy primary span with any hygienic context.
443 pub fn is_dummy(&self) -> bool {
444 self.primary_spans.iter().all(|sp| sp.is_dummy())
447 /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
448 /// display well (like std macros). Returns whether replacements occurred.
449 pub fn replace(&mut self, before: Span, after: Span) -> bool {
450 let mut replacements_occurred = false;
451 for primary_span in &mut self.primary_spans {
452 if *primary_span == before {
453 *primary_span = after;
454 replacements_occurred = true;
457 for span_label in &mut self.span_labels {
458 if span_label.0 == before {
459 span_label.0 = after;
460 replacements_occurred = true;
463 replacements_occurred
466 /// Returns the strings to highlight. We always ensure that there
467 /// is an entry for each of the primary spans -- for each primary
468 /// span `P`, if there is at least one label with span `P`, we return
469 /// those labels (marked as primary). But otherwise we return
470 /// `SpanLabel` instances with empty labels.
471 pub fn span_labels(&self) -> Vec<SpanLabel> {
472 let is_primary = |span| self.primary_spans.contains(&span);
474 let mut span_labels = self
477 .map(|&(span, ref label)| SpanLabel {
479 is_primary: is_primary(span),
480 label: Some(label.clone()),
482 .collect::<Vec<_>>();
484 for &span in &self.primary_spans {
485 if !span_labels.iter().any(|sl| sl.span == span) {
486 span_labels.push(SpanLabel { span, is_primary: true, label: None });
493 /// Returns `true` if any of the span labels is displayable.
494 pub fn has_span_labels(&self) -> bool {
495 self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
499 impl From<Span> for MultiSpan {
500 fn from(span: Span) -> MultiSpan {
501 MultiSpan::from_span(span)
505 impl From<Vec<Span>> for MultiSpan {
506 fn from(spans: Vec<Span>) -> MultiSpan {
507 MultiSpan::from_spans(spans)