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