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