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