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