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