icu_provider_source/list/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

use crate::cldr_serde;
use crate::IterableDataProviderCached;
use crate::SourceDataProvider;
use icu::list::provider::*;
use icu::locale::subtags::language;
use icu_provider::prelude::*;
use std::borrow::Cow;
use std::collections::HashSet;
use std::sync::OnceLock;

fn load<M: DataMarker<DataStruct = ListFormatterPatternsV2<'static>>>(
    selff: &SourceDataProvider,
    req: DataRequest,
) -> Result<DataResponse<M>, DataError> {
    let resource: &cldr_serde::list_patterns::Resource = selff
        .cldr()?
        .misc()
        .read_and_parse(req.id.locale, "listPatterns.json")?;

    let data = &resource.main.value.list_patterns;

    let patterns = if M::INFO == AndListV2Marker::INFO {
        match req.id.marker_attributes.as_str() {
            ListFormatterPatternsV2::SHORT_STR => &data.standard_short,
            ListFormatterPatternsV2::NARROW_STR => &data.standard_narrow,
            ListFormatterPatternsV2::WIDE_STR => &data.standard,
            _ => return Err(DataErrorKind::IdentifierNotFound.with_req(M::INFO, req)),
        }
    } else if M::INFO == OrListV2Marker::INFO {
        match req.id.marker_attributes.as_str() {
            ListFormatterPatternsV2::SHORT_STR => &data.or_short,
            ListFormatterPatternsV2::NARROW_STR => &data.or_narrow,
            ListFormatterPatternsV2::WIDE_STR => &data.or,
            _ => return Err(DataErrorKind::IdentifierNotFound.with_req(M::INFO, req)),
        }
    } else if M::INFO == UnitListV2Marker::INFO {
        match req.id.marker_attributes.as_str() {
            ListFormatterPatternsV2::SHORT_STR => &data.unit_short,
            ListFormatterPatternsV2::NARROW_STR => &data.unit_narrow,
            ListFormatterPatternsV2::WIDE_STR => &data.unit,
            _ => return Err(DataErrorKind::IdentifierNotFound.with_req(M::INFO, req)),
        }
    } else {
        return Err(DataError::custom(
            "Unknown marker for ListFormatterPatternsV2",
        ));
    };

    let mut patterns = ListFormatterPatternsV2::try_new(
        &patterns.start,
        &patterns.middle,
        &patterns.end,
        &patterns.pair,
    )?;

    if req.id.locale.language == language!("es") {
        if M::INFO == AndListV2Marker::INFO || M::INFO == UnitListV2Marker::INFO {
            // Replace " y " with " e " before /i/ sounds.
            // https://unicode.org/reports/tr35/tr35-general.html#:~:text=important.%20For%20example%3A-,Spanish,AND,-Use%20%E2%80%98e%E2%80%99%20instead

            static I_SOUND_BECOMES_E: OnceLock<SpecialCasePattern<'static>> = OnceLock::new();
            let i_sound_becomes_e = I_SOUND_BECOMES_E.get_or_init(|| {
                SpecialCasePattern {
                    // Starts with i or (hi but not hia/hie)
                    condition: SerdeDFA::new(Cow::Borrowed("^[iI]|(?:[hH][iI](?:[^aeAE]|$))"))
                        .expect("Valid regex"),
                    pattern: ListJoinerPattern::try_from_str("{0} e {1}", false, false)
                        .expect("Valid pattern"),
                }
            });

            let default =
                ListJoinerPattern::try_from_str("{0} y {1}", false, false).expect("valid pattern");

            if patterns.end.default == default {
                patterns.end.special_case = Some(i_sound_becomes_e.clone());
            }
            if let Some(pair) = patterns.pair.as_mut() {
                if pair.default == default {
                    pair.special_case = Some(i_sound_becomes_e.clone());
                }
            }
        } else if M::INFO == OrListV2Marker::INFO {
            // Replace " o " with " u " before /o/ sound.
            // https://unicode.org/reports/tr35/tr35-general.html#:~:text=agua%20e%20hielo-,OR,-Use%20%E2%80%98u%E2%80%99%20instead

            static O_SOUND_BECOMES_U: OnceLock<SpecialCasePattern<'static>> = OnceLock::new();
            let o_sound_becomes_u = O_SOUND_BECOMES_U.get_or_init(|| {
                SpecialCasePattern {
                    // Starts with o, ho, 8 (including 80, 800, ...), or 11 either alone or followed
                    // by thousand groups and/or decimals (excluding e.g. 110, 1100, ...)
                    condition: SerdeDFA::new(Cow::Borrowed(
                        r"^[oO]|[hH][oO]|8|(?:11(?:[\.  ]?[0-9]{3})*(?:,[0-9]*)?(?:[^\.,[0-9]]|$))",
                    ))
                    .expect("Valid regex"),
                    pattern: ListJoinerPattern::try_from_str("{0} u {1}", false, false)
                        .expect("valid pattern"),
                }
            });

            let default =
                ListJoinerPattern::try_from_str("{0} o {1}", false, false).expect("valid pattern");

            if patterns.end.default == default {
                patterns.end.special_case = Some(o_sound_becomes_u.clone());
            }
            if let Some(pair) = patterns.pair.as_mut() {
                if pair.default == default {
                    pair.special_case = Some(o_sound_becomes_u.clone());
                }
            }
        }
    }

    if req.id.locale.language == language!("he") {
        // Add dashes between ו and non-Hebrew characters
        // https://unicode.org/reports/tr35/tr35-general.html#:~:text=is%20not%20mute.-,Hebrew,AND,-Use%20%E2%80%98%2D%D7%95%E2%80%99%20instead

        // Cannot cache this because it depends on `selff`. However we don't expect many Hebrew locales.
        let dashes_in_front_of_non_hebrew = SpecialCasePattern {
            condition: SerdeDFA::new(Cow::Owned(format!(
                "^[^{}]",
                icu::properties::CodePointMapData::<icu::properties::props::Script>::try_new_unstable(selff)
                    .map_err(|e| DataError::custom("data for CodePointTrie of Script")
                        .with_display_context(&e))?
                    .as_borrowed()
                    .get_set_for_value(icu::properties::props::Script::Hebrew)
                    .as_borrowed()
                    .iter_ranges()
                    .map(|range| format!(r#"\u{:04x}-\u{:04x}"#, range.start(), range.end()))
                    .fold(String::new(), |a, b| a + &b)
            )))
            .expect("valid regex"),
            pattern: ListJoinerPattern::try_from_str("{0} \u{05D5}‑{1}", false, false).unwrap(), // ״{0} ו‑{1}״
        };

        let default = ListJoinerPattern::try_from_str("{0} \u{05D5}{1}", false, false)
            .expect("valid pattern"); // ״{0} ו{1}״

        if patterns.end.default == default {
            patterns.end.special_case = Some(dashes_in_front_of_non_hebrew.clone());
        }
        if let Some(pair) = patterns.pair.as_mut() {
            if pair.default == default {
                pair.special_case = Some(dashes_in_front_of_non_hebrew.clone());
            }
        }
    }

    let metadata = DataResponseMetadata::default();
    Ok(DataResponse {
        metadata,
        payload: DataPayload::from_owned(patterns),
    })
}

macro_rules! implement {
    ($marker:ident) => {
        impl DataProvider<$marker> for SourceDataProvider {
            fn load(&self, req: DataRequest) -> Result<DataResponse<$marker>, DataError> {
                self.check_req::<$marker>(req)?;
                load(self, req)
            }
        }

        impl IterableDataProviderCached<$marker> for SourceDataProvider {
            fn iter_ids_cached(&self) -> Result<HashSet<DataIdentifierCow<'static>>, DataError> {
                Ok(self
                    .cldr()?
                    .misc()
                    .list_locales()?
                    .flat_map(|l| {
                        [
                            ListFormatterPatternsV2::SHORT,
                            ListFormatterPatternsV2::NARROW,
                            ListFormatterPatternsV2::WIDE,
                        ]
                        .into_iter()
                        .map(move |a| DataIdentifierCow::from_borrowed_and_owned(a, l.clone()))
                    })
                    .collect())
            }
        }
    };
}

implement!(AndListV2Marker);
implement!(OrListV2Marker);
implement!(UnitListV2Marker);