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