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