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