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