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