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