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