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