Skip to main content

rustc_errors/
translation.rs

1use std::borrow::Cow;
2
3pub use rustc_error_messages::FluentArgs;
4use rustc_error_messages::{DiagArgMap, langid, register_functions};
5use tracing::{debug, trace};
6
7use crate::fluent_bundle::FluentResource;
8use crate::{DiagArg, DiagMessage, Style, fluent_bundle};
9
10/// Convert diagnostic arguments (a rustc internal type that exists to implement
11/// `Encodable`/`Decodable`) into `FluentArgs` which is necessary to perform translation.
12///
13/// Typically performed once for each diagnostic at the start of `emit_diagnostic` and then
14/// passed around as a reference thereafter.
15fn to_fluent_args<'iter>(iter: impl Iterator<Item = DiagArg<'iter>>) -> FluentArgs<'static> {
16    let mut args = if let Some(size) = iter.size_hint().1 {
17        FluentArgs::with_capacity(size)
18    } else {
19        FluentArgs::new()
20    };
21
22    for (k, v) in iter {
23        args.set(k.clone(), v.clone());
24    }
25
26    args
27}
28
29/// Convert `DiagMessage`s to a string
30pub fn format_diag_messages(
31    messages: &[(DiagMessage, Style)],
32    args: &DiagArgMap,
33) -> Cow<'static, str> {
34    Cow::Owned(messages.iter().map(|(m, _)| format_diag_message(m, args)).collect::<String>())
35}
36
37/// Convert a `DiagMessage` to a string
38pub fn format_diag_message<'a>(message: &'a DiagMessage, args: &DiagArgMap) -> Cow<'a, str> {
39    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_errors/src/translation.rs:39",
                        "rustc_errors::translation", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_errors/src/translation.rs"),
                        ::tracing_core::__macro_support::Option::Some(39u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_errors::translation"),
                        ::tracing_core::field::FieldSet::new(&["message", "args"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&message) as
                                            &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&args) as
                                            &dyn Value))])
            });
    } else { ; }
};trace!(?message, ?args);
40
41    match message {
42        DiagMessage::Str(msg) => Cow::Borrowed(msg),
43        // This translates an inline fluent diagnostic message
44        // It does this by creating a new `FluentBundle` with only one message,
45        // and then translating using this bundle.
46        DiagMessage::Inline(msg) => {
47            const GENERATED_MSG_ID: &str = "generated_msg";
48            let resource =
49                FluentResource::try_new(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} = {1}\n", GENERATED_MSG_ID,
                msg))
    })format!("{GENERATED_MSG_ID} = {msg}\n")).unwrap();
50            let mut bundle = fluent_bundle::FluentBundle::new(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [{
                    #[allow(dead_code)]
                    enum ProcMacroHack { Value = ("\"en-US\"", 0).1, }
                    macro_rules! proc_macro_call {
                        () =>
                        {
                            unsafe
                            {
                                $crate :: LanguageIdentifier ::
                                from_raw_parts_unchecked(unsafe
                                {
                                    $crate :: subtags :: Language ::
                                    from_raw_unchecked(28261u64)
                                }, None,
                                Some(unsafe
                                {
                                    $crate :: subtags :: Region :: from_raw_unchecked(21333u32)
                                }), None)
                            }
                        }
                    }
                    unsafe {
                        ::unic_langid_macros::LanguageIdentifier::from_raw_parts_unchecked(unsafe
                                {
                                ::unic_langid_macros::subtags::Language::from_raw_unchecked(28261u64)
                            }, None,
                            Some(unsafe {
                                    ::unic_langid_macros::subtags::Region::from_raw_unchecked(21333u32)
                                }), None)
                    }
                }]))vec![langid!("en-US")]);
51            bundle.set_use_isolating(false);
52            bundle.add_resource(resource).unwrap();
53            register_functions(&mut bundle);
54            let message = bundle.get_message(GENERATED_MSG_ID).unwrap();
55            let value = message.value().unwrap();
56            let args = to_fluent_args(args.iter());
57
58            let mut errs = ::alloc::vec::Vec::new()vec![];
59            let translated = bundle.format_pattern(value, Some(&args), &mut errs).to_string();
60            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_errors/src/translation.rs:60",
                        "rustc_errors::translation", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_errors/src/translation.rs"),
                        ::tracing_core::__macro_support::Option::Some(60u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_errors::translation"),
                        ::tracing_core::field::FieldSet::new(&["translated",
                                        "errs"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&translated)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&errs) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?translated, ?errs);
61            if errs.is_empty() {
62                Cow::Owned(translated)
63            } else {
64                {
    ::core::panicking::panic_fmt(format_args!("Fluent errors while formatting message: {0:?}",
            errs));
};panic!("Fluent errors while formatting message: {errs:?}");
65            }
66        }
67    }
68}