]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_messages/src/lib.rs
Porting 'compiler/rustc_trait_selection' to translatable diagnostics - Part 1
[rust.git] / compiler / rustc_error_messages / src / lib.rs
1 #![feature(let_chains)]
2 #![feature(once_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 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};
12 use rustc_span::Span;
13 use std::borrow::Cow;
14 use std::error::Error;
15 use std::fmt;
16 use std::fs;
17 use std::io;
18 use std::path::{Path, PathBuf};
19 use tracing::{instrument, trace};
20
21 #[cfg(not(parallel_compiler))]
22 use std::cell::LazyCell as Lazy;
23 #[cfg(parallel_compiler)]
24 use std::sync::LazyLock as Lazy;
25
26 #[cfg(parallel_compiler)]
27 use intl_memoizer::concurrent::IntlLangMemoizer;
28 #[cfg(not(parallel_compiler))]
29 use intl_memoizer::IntlLangMemoizer;
30
31 pub use fluent_bundle::{FluentArgs, FluentError, FluentValue};
32 pub use unic_langid::{langid, LanguageIdentifier};
33
34 // Generates `DEFAULT_LOCALE_RESOURCES` static and `fluent_generated` module.
35 fluent_messages! {
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     parser => "../locales/en-US/parser.ftl",
50     passes => "../locales/en-US/passes.ftl",
51     plugin_impl => "../locales/en-US/plugin_impl.ftl",
52     privacy => "../locales/en-US/privacy.ftl",
53     query_system => "../locales/en-US/query_system.ftl",
54     trait_selection => "../locales/en-US/trait_selection.ftl",
55     save_analysis => "../locales/en-US/save_analysis.ftl",
56     ty_utils => "../locales/en-US/ty_utils.ftl",
57     typeck => "../locales/en-US/typeck.ftl",
58     mir_dataflow => "../locales/en-US/mir_dataflow.ftl",
59     symbol_mangling => "../locales/en-US/symbol_mangling.ftl",
60 }
61
62 pub use fluent_generated::{self as fluent, DEFAULT_LOCALE_RESOURCES};
63
64 pub type FluentBundle = fluent_bundle::bundle::FluentBundle<FluentResource, IntlLangMemoizer>;
65
66 #[cfg(parallel_compiler)]
67 fn new_bundle(locales: Vec<LanguageIdentifier>) -> FluentBundle {
68     FluentBundle::new_concurrent(locales)
69 }
70
71 #[cfg(not(parallel_compiler))]
72 fn new_bundle(locales: Vec<LanguageIdentifier>) -> FluentBundle {
73     FluentBundle::new(locales)
74 }
75
76 #[derive(Debug)]
77 pub enum TranslationBundleError {
78     /// Failed to read from `.ftl` file.
79     ReadFtl(io::Error),
80     /// Failed to parse contents of `.ftl` file.
81     ParseFtl(ParserError),
82     /// Failed to add `FluentResource` to `FluentBundle`.
83     AddResource(FluentError),
84     /// `$sysroot/share/locale/$locale` does not exist.
85     MissingLocale,
86     /// Cannot read directory entries of `$sysroot/share/locale/$locale`.
87     ReadLocalesDir(io::Error),
88     /// Cannot read directory entry of `$sysroot/share/locale/$locale`.
89     ReadLocalesDirEntry(io::Error),
90     /// `$sysroot/share/locale/$locale` is not a directory.
91     LocaleIsNotDir,
92 }
93
94 impl fmt::Display for TranslationBundleError {
95     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96         match self {
97             TranslationBundleError::ReadFtl(e) => write!(f, "could not read ftl file: {}", e),
98             TranslationBundleError::ParseFtl(e) => {
99                 write!(f, "could not parse ftl file: {}", e)
100             }
101             TranslationBundleError::AddResource(e) => write!(f, "failed to add resource: {}", e),
102             TranslationBundleError::MissingLocale => write!(f, "missing locale directory"),
103             TranslationBundleError::ReadLocalesDir(e) => {
104                 write!(f, "could not read locales dir: {}", e)
105             }
106             TranslationBundleError::ReadLocalesDirEntry(e) => {
107                 write!(f, "could not read locales dir entry: {}", e)
108             }
109             TranslationBundleError::LocaleIsNotDir => {
110                 write!(f, "`$sysroot/share/locales/$locale` is not a directory")
111             }
112         }
113     }
114 }
115
116 impl Error for TranslationBundleError {
117     fn source(&self) -> Option<&(dyn Error + 'static)> {
118         match self {
119             TranslationBundleError::ReadFtl(e) => Some(e),
120             TranslationBundleError::ParseFtl(e) => Some(e),
121             TranslationBundleError::AddResource(e) => Some(e),
122             TranslationBundleError::MissingLocale => None,
123             TranslationBundleError::ReadLocalesDir(e) => Some(e),
124             TranslationBundleError::ReadLocalesDirEntry(e) => Some(e),
125             TranslationBundleError::LocaleIsNotDir => None,
126         }
127     }
128 }
129
130 impl From<(FluentResource, Vec<ParserError>)> for TranslationBundleError {
131     fn from((_, mut errs): (FluentResource, Vec<ParserError>)) -> Self {
132         TranslationBundleError::ParseFtl(errs.pop().expect("failed ftl parse with no errors"))
133     }
134 }
135
136 impl From<Vec<FluentError>> for TranslationBundleError {
137     fn from(mut errs: Vec<FluentError>) -> Self {
138         TranslationBundleError::AddResource(
139             errs.pop().expect("failed adding resource to bundle with no errors"),
140         )
141     }
142 }
143
144 /// Returns Fluent bundle with the user's locale resources from
145 /// `$sysroot/share/locale/$requested_locale/*.ftl`.
146 ///
147 /// If `-Z additional-ftl-path` was provided, load that resource and add it  to the bundle
148 /// (overriding any conflicting messages).
149 #[instrument(level = "trace")]
150 pub fn fluent_bundle(
151     mut user_provided_sysroot: Option<PathBuf>,
152     mut sysroot_candidates: Vec<PathBuf>,
153     requested_locale: Option<LanguageIdentifier>,
154     additional_ftl_path: Option<&Path>,
155     with_directionality_markers: bool,
156 ) -> Result<Option<Lrc<FluentBundle>>, TranslationBundleError> {
157     if requested_locale.is_none() && additional_ftl_path.is_none() {
158         return Ok(None);
159     }
160
161     let fallback_locale = langid!("en-US");
162     let requested_fallback_locale = requested_locale.as_ref() == Some(&fallback_locale);
163
164     // If there is only `-Z additional-ftl-path`, assume locale is "en-US", otherwise use user
165     // provided locale.
166     let locale = requested_locale.clone().unwrap_or(fallback_locale);
167     trace!(?locale);
168     let mut bundle = new_bundle(vec![locale]);
169
170     // Fluent diagnostics can insert directionality isolation markers around interpolated variables
171     // indicating that there may be a shift from right-to-left to left-to-right text (or
172     // vice-versa). These are disabled because they are sometimes visible in the error output, but
173     // may be worth investigating in future (for example: if type names are left-to-right and the
174     // surrounding diagnostic messages are right-to-left, then these might be helpful).
175     bundle.set_use_isolating(with_directionality_markers);
176
177     // If the user requests the default locale then don't try to load anything.
178     if !requested_fallback_locale && let Some(requested_locale) = requested_locale {
179         let mut found_resources = false;
180         for sysroot in user_provided_sysroot.iter_mut().chain(sysroot_candidates.iter_mut()) {
181             sysroot.push("share");
182             sysroot.push("locale");
183             sysroot.push(requested_locale.to_string());
184             trace!(?sysroot);
185
186             if !sysroot.exists() {
187                 trace!("skipping");
188                 continue;
189             }
190
191             if !sysroot.is_dir() {
192                 return Err(TranslationBundleError::LocaleIsNotDir);
193             }
194
195             for entry in sysroot.read_dir().map_err(TranslationBundleError::ReadLocalesDir)? {
196                 let entry = entry.map_err(TranslationBundleError::ReadLocalesDirEntry)?;
197                 let path = entry.path();
198                 trace!(?path);
199                 if path.extension().and_then(|s| s.to_str()) != Some("ftl") {
200                     trace!("skipping");
201                     continue;
202                 }
203
204                 let resource_str =
205                     fs::read_to_string(path).map_err(TranslationBundleError::ReadFtl)?;
206                 let resource =
207                     FluentResource::try_new(resource_str).map_err(TranslationBundleError::from)?;
208                 trace!(?resource);
209                 bundle.add_resource(resource).map_err(TranslationBundleError::from)?;
210                 found_resources = true;
211             }
212         }
213
214         if !found_resources {
215             return Err(TranslationBundleError::MissingLocale);
216         }
217     }
218
219     if let Some(additional_ftl_path) = additional_ftl_path {
220         let resource_str =
221             fs::read_to_string(additional_ftl_path).map_err(TranslationBundleError::ReadFtl)?;
222         let resource =
223             FluentResource::try_new(resource_str).map_err(TranslationBundleError::from)?;
224         trace!(?resource);
225         bundle.add_resource_overriding(resource);
226     }
227
228     let bundle = Lrc::new(bundle);
229     Ok(Some(bundle))
230 }
231
232 /// Type alias for the result of `fallback_fluent_bundle` - a reference-counted pointer to a lazily
233 /// evaluated fluent bundle.
234 pub type LazyFallbackBundle = Lrc<Lazy<FluentBundle, impl FnOnce() -> FluentBundle>>;
235
236 /// Return the default `FluentBundle` with standard "en-US" diagnostic messages.
237 #[instrument(level = "trace")]
238 pub fn fallback_fluent_bundle(
239     resources: &'static [&'static str],
240     with_directionality_markers: bool,
241 ) -> LazyFallbackBundle {
242     Lrc::new(Lazy::new(move || {
243         let mut fallback_bundle = new_bundle(vec![langid!("en-US")]);
244         // See comment in `fluent_bundle`.
245         fallback_bundle.set_use_isolating(with_directionality_markers);
246
247         for resource in resources {
248             let resource = FluentResource::try_new(resource.to_string())
249                 .expect("failed to parse fallback fluent resource");
250             trace!(?resource);
251             fallback_bundle.add_resource_overriding(resource);
252         }
253
254         fallback_bundle
255     }))
256 }
257
258 /// Identifier for the Fluent message/attribute corresponding to a diagnostic message.
259 type FluentId = Cow<'static, str>;
260
261 /// Abstraction over a message in a subdiagnostic (i.e. label, note, help, etc) to support both
262 /// translatable and non-translatable diagnostic messages.
263 ///
264 /// Translatable messages for subdiagnostics are typically attributes attached to a larger Fluent
265 /// message so messages of this type must be combined with a `DiagnosticMessage` (using
266 /// `DiagnosticMessage::with_subdiagnostic_message`) before rendering. However, subdiagnostics from
267 /// the `SessionSubdiagnostic` derive refer to Fluent identifiers directly.
268 #[rustc_diagnostic_item = "SubdiagnosticMessage"]
269 pub enum SubdiagnosticMessage {
270     /// Non-translatable diagnostic message.
271     // FIXME(davidtwco): can a `Cow<'static, str>` be used here?
272     Str(String),
273     /// Identifier of a Fluent message. Instances of this variant are generated by the
274     /// `SessionSubdiagnostic` derive.
275     FluentIdentifier(FluentId),
276     /// Attribute of a Fluent message. Needs to be combined with a Fluent identifier to produce an
277     /// actual translated message. Instances of this variant are generated by the `fluent_messages`
278     /// macro.
279     ///
280     /// <https://projectfluent.org/fluent/guide/attributes.html>
281     FluentAttr(FluentId),
282 }
283
284 /// `From` impl that enables existing diagnostic calls to functions which now take
285 /// `impl Into<SubdiagnosticMessage>` to continue to work as before.
286 impl<S: Into<String>> From<S> for SubdiagnosticMessage {
287     fn from(s: S) -> Self {
288         SubdiagnosticMessage::Str(s.into())
289     }
290 }
291
292 /// Abstraction over a message in a diagnostic to support both translatable and non-translatable
293 /// diagnostic messages.
294 ///
295 /// Intended to be removed once diagnostics are entirely translatable.
296 #[derive(Clone, Debug, PartialEq, Eq, Hash, Encodable, Decodable)]
297 #[rustc_diagnostic_item = "DiagnosticMessage"]
298 pub enum DiagnosticMessage {
299     /// Non-translatable diagnostic message.
300     // FIXME(davidtwco): can a `Cow<'static, str>` be used here?
301     Str(String),
302     /// Identifier for a Fluent message (with optional attribute) corresponding to the diagnostic
303     /// message.
304     ///
305     /// <https://projectfluent.org/fluent/guide/hello.html>
306     /// <https://projectfluent.org/fluent/guide/attributes.html>
307     FluentIdentifier(FluentId, Option<FluentId>),
308 }
309
310 impl DiagnosticMessage {
311     /// Given a `SubdiagnosticMessage` which may contain a Fluent attribute, create a new
312     /// `DiagnosticMessage` that combines that attribute with the Fluent identifier of `self`.
313     ///
314     /// - If the `SubdiagnosticMessage` is non-translatable then return the message as a
315     /// `DiagnosticMessage`.
316     /// - If `self` is non-translatable then return `self`'s message.
317     pub fn with_subdiagnostic_message(&self, sub: SubdiagnosticMessage) -> Self {
318         let attr = match sub {
319             SubdiagnosticMessage::Str(s) => return DiagnosticMessage::Str(s),
320             SubdiagnosticMessage::FluentIdentifier(id) => {
321                 return DiagnosticMessage::FluentIdentifier(id, None);
322             }
323             SubdiagnosticMessage::FluentAttr(attr) => attr,
324         };
325
326         match self {
327             DiagnosticMessage::Str(s) => DiagnosticMessage::Str(s.clone()),
328             DiagnosticMessage::FluentIdentifier(id, _) => {
329                 DiagnosticMessage::FluentIdentifier(id.clone(), Some(attr))
330             }
331         }
332     }
333
334     /// Returns the `String` contained within the `DiagnosticMessage::Str` variant, assuming that
335     /// this diagnostic message is of the legacy, non-translatable variety. Panics if this
336     /// assumption does not hold.
337     ///
338     /// Don't use this - it exists to support some places that do comparison with diagnostic
339     /// strings.
340     pub fn expect_str(&self) -> &str {
341         match self {
342             DiagnosticMessage::Str(s) => s,
343             _ => panic!("expected non-translatable diagnostic message"),
344         }
345     }
346 }
347
348 /// `From` impl that enables existing diagnostic calls to functions which now take
349 /// `impl Into<DiagnosticMessage>` to continue to work as before.
350 impl<S: Into<String>> From<S> for DiagnosticMessage {
351     fn from(s: S) -> Self {
352         DiagnosticMessage::Str(s.into())
353     }
354 }
355
356 /// Translating *into* a subdiagnostic message from a diagnostic message is a little strange - but
357 /// the subdiagnostic functions (e.g. `span_label`) take a `SubdiagnosticMessage` and the
358 /// subdiagnostic derive refers to typed identifiers that are `DiagnosticMessage`s, so need to be
359 /// able to convert between these, as much as they'll be converted back into `DiagnosticMessage`
360 /// using `with_subdiagnostic_message` eventually. Don't use this other than for the derive.
361 impl Into<SubdiagnosticMessage> for DiagnosticMessage {
362     fn into(self) -> SubdiagnosticMessage {
363         match self {
364             DiagnosticMessage::Str(s) => SubdiagnosticMessage::Str(s),
365             DiagnosticMessage::FluentIdentifier(id, None) => {
366                 SubdiagnosticMessage::FluentIdentifier(id)
367             }
368             // There isn't really a sensible behaviour for this because it loses information but
369             // this is the most sensible of the behaviours.
370             DiagnosticMessage::FluentIdentifier(_, Some(attr)) => {
371                 SubdiagnosticMessage::FluentAttr(attr)
372             }
373         }
374     }
375 }
376
377 /// A span together with some additional data.
378 #[derive(Clone, Debug)]
379 pub struct SpanLabel {
380     /// The span we are going to include in the final snippet.
381     pub span: Span,
382
383     /// Is this a primary span? This is the "locus" of the message,
384     /// and is indicated with a `^^^^` underline, versus `----`.
385     pub is_primary: bool,
386
387     /// What label should we attach to this span (if any)?
388     pub label: Option<DiagnosticMessage>,
389 }
390
391 /// A collection of `Span`s.
392 ///
393 /// Spans have two orthogonal attributes:
394 ///
395 /// - They can be *primary spans*. In this case they are the locus of
396 ///   the error, and would be rendered with `^^^`.
397 /// - They can have a *label*. In this case, the label is written next
398 ///   to the mark in the snippet when we render.
399 #[derive(Clone, Debug, Hash, PartialEq, Eq, Encodable, Decodable)]
400 pub struct MultiSpan {
401     primary_spans: Vec<Span>,
402     span_labels: Vec<(Span, DiagnosticMessage)>,
403 }
404
405 impl MultiSpan {
406     #[inline]
407     pub fn new() -> MultiSpan {
408         MultiSpan { primary_spans: vec![], span_labels: vec![] }
409     }
410
411     pub fn from_span(primary_span: Span) -> MultiSpan {
412         MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] }
413     }
414
415     pub fn from_spans(mut vec: Vec<Span>) -> MultiSpan {
416         vec.sort();
417         MultiSpan { primary_spans: vec, span_labels: vec![] }
418     }
419
420     pub fn push_span_label(&mut self, span: Span, label: impl Into<DiagnosticMessage>) {
421         self.span_labels.push((span, label.into()));
422     }
423
424     /// Selects the first primary span (if any).
425     pub fn primary_span(&self) -> Option<Span> {
426         self.primary_spans.first().cloned()
427     }
428
429     /// Returns all primary spans.
430     pub fn primary_spans(&self) -> &[Span] {
431         &self.primary_spans
432     }
433
434     /// Returns `true` if any of the primary spans are displayable.
435     pub fn has_primary_spans(&self) -> bool {
436         !self.is_dummy()
437     }
438
439     /// Returns `true` if this contains only a dummy primary span with any hygienic context.
440     pub fn is_dummy(&self) -> bool {
441         self.primary_spans.iter().all(|sp| sp.is_dummy())
442     }
443
444     /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't
445     /// display well (like std macros). Returns whether replacements occurred.
446     pub fn replace(&mut self, before: Span, after: Span) -> bool {
447         let mut replacements_occurred = false;
448         for primary_span in &mut self.primary_spans {
449             if *primary_span == before {
450                 *primary_span = after;
451                 replacements_occurred = true;
452             }
453         }
454         for span_label in &mut self.span_labels {
455             if span_label.0 == before {
456                 span_label.0 = after;
457                 replacements_occurred = true;
458             }
459         }
460         replacements_occurred
461     }
462
463     /// Returns the strings to highlight. We always ensure that there
464     /// is an entry for each of the primary spans -- for each primary
465     /// span `P`, if there is at least one label with span `P`, we return
466     /// those labels (marked as primary). But otherwise we return
467     /// `SpanLabel` instances with empty labels.
468     pub fn span_labels(&self) -> Vec<SpanLabel> {
469         let is_primary = |span| self.primary_spans.contains(&span);
470
471         let mut span_labels = self
472             .span_labels
473             .iter()
474             .map(|&(span, ref label)| SpanLabel {
475                 span,
476                 is_primary: is_primary(span),
477                 label: Some(label.clone()),
478             })
479             .collect::<Vec<_>>();
480
481         for &span in &self.primary_spans {
482             if !span_labels.iter().any(|sl| sl.span == span) {
483                 span_labels.push(SpanLabel { span, is_primary: true, label: None });
484             }
485         }
486
487         span_labels
488     }
489
490     /// Returns `true` if any of the span labels is displayable.
491     pub fn has_span_labels(&self) -> bool {
492         self.span_labels.iter().any(|(sp, _)| !sp.is_dummy())
493     }
494 }
495
496 impl From<Span> for MultiSpan {
497     fn from(span: Span) -> MultiSpan {
498         MultiSpan::from_span(span)
499     }
500 }
501
502 impl From<Vec<Span>> for MultiSpan {
503     fn from(spans: Vec<Span>) -> MultiSpan {
504         MultiSpan::from_spans(spans)
505     }
506 }