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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
// 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 ).

//! Traits for managing data needed by [`TypedDateTimeFormatter`](crate::TypedDateTimeFormatter).

use crate::fields;
#[cfg(feature = "experimental")]
use crate::fields::Field;
use crate::input;
use crate::options::{length, preferences, DateTimeFormatterOptions};
use crate::pattern::PatternError;
use crate::pattern::{hour_cycle, runtime::PatternPlurals};
use crate::provider;
use crate::provider::calendar::patterns::PatternPluralsV1;
use crate::provider::calendar::{months, DateLengthsV1, TimeLengthsV1};
use crate::provider::calendar::{
    patterns::GenericPatternV1Marker, patterns::PatternPluralsFromPatternsV1Marker,
    ErasedDateLengthsV1Marker, TimeLengthsV1Marker,
};
#[cfg(feature = "experimental")]
use crate::provider::neo::SimpleSubstitutionPattern;
#[cfg(feature = "experimental")]
use crate::{options::components, provider::calendar::DateSkeletonPatternsV1Marker};
use icu_calendar::types::Era;
use icu_calendar::types::MonthCode;
use icu_locid::extensions::unicode::Value;
use icu_provider::prelude::*;

pub(crate) enum GetSymbolForMonthError {
    Missing,
    #[cfg(feature = "experimental")]
    MissingNames(Field),
}
pub(crate) enum GetSymbolForWeekdayError {
    Missing,
    #[cfg(feature = "experimental")]
    MissingNames(Field),
}

pub(crate) enum GetSymbolForEraError {
    Missing,
    #[cfg(feature = "experimental")]
    MissingNames(Field),
}

pub(crate) enum GetSymbolForDayPeriodError {
    #[cfg(feature = "experimental")]
    MissingNames(Field),
}

#[cfg(feature = "experimental")]
pub(crate) enum UnsupportedOptionsOrDataError {
    UnsupportedOptions,
    Data(DataError),
}

#[cfg(feature = "experimental")]
pub(crate) enum UnsupportedOptionsOrDataOrPatternError {
    UnsupportedOptions,
    Data(DataError),
    Pattern(PatternError),
}

fn pattern_for_time_length_inner<'data>(
    data: TimeLengthsV1<'data>,
    length: length::Time,
    preferences: &Option<preferences::Bag>,
) -> PatternPlurals<'data> {
    // Determine the coarse hour cycle patterns to use from either the preference bag,
    // or the preferred hour cycle for the locale.
    let time = if let Some(preferences::Bag {
        hour_cycle: Some(hour_cycle_pref),
    }) = preferences
    {
        match hour_cycle_pref {
            preferences::HourCycle::H11 | preferences::HourCycle::H12 => data.time_h11_h12,
            preferences::HourCycle::H23 | preferences::HourCycle::H24 => data.time_h23_h24,
        }
    } else {
        match data.preferred_hour_cycle {
            crate::pattern::CoarseHourCycle::H11H12 => data.time_h11_h12,
            crate::pattern::CoarseHourCycle::H23H24 => data.time_h23_h24,
        }
    };

    let mut pattern = match length {
        length::Time::Full => time.full,
        length::Time::Long => time.long,
        length::Time::Medium => time.medium,
        length::Time::Short => time.short,
    };

    hour_cycle::naively_apply_preferences(&mut pattern, preferences);
    PatternPlurals::from(pattern)
}

fn pattern_for_date_length_inner(data: DateLengthsV1, length: length::Date) -> PatternPlurals {
    let pattern = match length {
        length::Date::Full => data.date.full,
        length::Date::Long => data.date.long,
        length::Date::Medium => data.date.medium,
        length::Date::Short => data.date.short,
    };
    PatternPlurals::from(pattern)
}

/// Determine the appropriate `Pattern` for a given `options::length::Time` bag.
/// If a preference for an hour cycle is set, it will look look up a pattern in the `time_h11_12` or
/// `time_h23_h24` provider data, and then manually modify the symbol in the pattern if needed.
pub(crate) fn pattern_for_time_length<'a, D>(
    data_provider: &'a D,
    locale: &'a DataLocale,
    length: length::Time,
    preferences: Option<preferences::Bag>,
) -> Result<DataPayload<PatternPluralsFromPatternsV1Marker>, DataError>
where
    D: DataProvider<TimeLengthsV1Marker> + ?Sized,
{
    Ok(data_provider
        .load(DataRequest {
            locale,
            metadata: Default::default(),
        })?
        .take_payload()?
        .map_project(|data, _| pattern_for_time_length_inner(data, length, &preferences).into()))
}

/// Determine the appropriate `Pattern` for a given `options::length::Date` bag.
pub(crate) fn pattern_for_date_length(
    length: length::Date,
    patterns_data: DataPayload<ErasedDateLengthsV1Marker>,
) -> DataPayload<PatternPluralsFromPatternsV1Marker> {
    patterns_data.map_project(|data, _| pattern_for_date_length_inner(data, length).into())
}

/// Determine the appropriate `Pattern` for a given `options::length::Date` bag.
pub(crate) fn generic_pattern_for_date_length(
    length: length::Date,
    patterns_data: DataPayload<ErasedDateLengthsV1Marker>,
) -> DataPayload<GenericPatternV1Marker> {
    patterns_data.map_project(|data, _| {
        match length {
            length::Date::Full => data.length_combinations.full,
            length::Date::Long => data.length_combinations.long,
            length::Date::Medium => data.length_combinations.medium,
            length::Date::Short => data.length_combinations.short,
        }
        .into()
    })
}

/// <div class="stab unstable">
/// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
/// including in SemVer minor releases. While the serde representation of data structs is guaranteed
/// to be stable, their Rust representation might not be. Use with caution.
/// </div>
#[derive(Clone)]
pub struct PatternSelector<'a, D: ?Sized> {
    data_provider: &'a D,
    date_patterns_data: DataPayload<ErasedDateLengthsV1Marker>,
    locale: &'a DataLocale,
    #[allow(dead_code)] // non-experimental mode
    cal_val: Option<&'a Value>,
}

pub(crate) enum PatternForLengthError {
    Pattern(PatternError),
    Data(DataError),
}

impl<D> PatternSelector<'_, D>
where
    D: DataProvider<TimeLengthsV1Marker> + ?Sized,
{
    pub(crate) fn for_options<'a>(
        data_provider: &'a D,
        date_patterns_data: DataPayload<ErasedDateLengthsV1Marker>,
        locale: &'a DataLocale,
        options: &DateTimeFormatterOptions,
    ) -> Result<DataPayload<PatternPluralsFromPatternsV1Marker>, PatternForLengthError> {
        let selector = PatternSelector {
            data_provider,
            date_patterns_data,
            locale,
            cal_val: None,
        };
        match options {
            DateTimeFormatterOptions::Length(bag) => selector
                .pattern_for_length_bag(bag, Some(preferences::Bag::from_data_locale(locale))),
            #[cfg(any(feature = "datagen", feature = "experimental"))]
            #[allow(clippy::panic)] // explicit panic in experimental mode
            _ => panic!("Non-experimental constructor cannot handle experimental options"),
        }
    }

    /// Determine the appropriate `Pattern` for a given `options::Length` bag.
    fn pattern_for_length_bag(
        self,
        length: &length::Bag,
        preferences: Option<preferences::Bag>,
    ) -> Result<DataPayload<PatternPluralsFromPatternsV1Marker>, PatternForLengthError> {
        match (length.date, length.time) {
            (None, None) => Ok(DataPayload::from_owned(PatternPluralsV1(
                PatternPlurals::default(),
            ))),
            (None, Some(time_length)) => {
                pattern_for_time_length(self.data_provider, self.locale, time_length, preferences)
                    .map_err(PatternForLengthError::Data)
            }
            (Some(date_length), None) => Ok(pattern_for_date_length(
                date_length,
                self.date_patterns_data,
            )),
            (Some(date_length), Some(time_length)) => {
                self.pattern_for_datetime_length(date_length, time_length, preferences)
            }
        }
    }

    /// Determine the appropriate `Pattern` for a given `options::length::Date` and
    /// `options::length::Time` bag.
    fn pattern_for_datetime_length(
        self,
        date_length: length::Date,
        time_length: length::Time,
        preferences: Option<preferences::Bag>,
    ) -> Result<DataPayload<PatternPluralsFromPatternsV1Marker>, PatternForLengthError> {
        let time_patterns_data = self
            .data_provider
            .load(DataRequest {
                locale: self.locale,
                metadata: Default::default(),
            })
            .and_then(DataResponse::take_payload)
            .map_err(PatternForLengthError::Data)?;

        self.date_patterns_data.try_map_project(|data, _| {
            // TODO (#1131) - We may be able to remove the clone here.
            let date = pattern_for_date_length_inner(data.clone(), date_length)
                .expect_pattern("Lengths are single patterns");

            let pattern = match date_length {
                length::Date::Full => data.length_combinations.full,
                length::Date::Long => data.length_combinations.long,
                length::Date::Medium => data.length_combinations.medium,
                length::Date::Short => data.length_combinations.short,
            };

            // TODO (#1131) - We may be able to remove the clone here.
            let time = pattern_for_time_length_inner(
                time_patterns_data.get().clone(),
                time_length,
                &preferences,
            )
            .expect_pattern("Lengths are single patterns");
            Ok(PatternPlurals::from(
                pattern
                    .combined(date, time)
                    .map_err(PatternForLengthError::Pattern)?,
            )
            .into())
        })
    }
}

#[cfg(feature = "experimental")]
impl<D> PatternSelector<'_, D>
where
    D: DataProvider<TimeLengthsV1Marker> + DataProvider<DateSkeletonPatternsV1Marker> + ?Sized,
{
    pub(crate) fn for_options_experimental<'a>(
        data_provider: &'a D,
        date_patterns_data: DataPayload<ErasedDateLengthsV1Marker>,
        locale: &'a DataLocale,
        cal_val: &'a Value,
        options: &DateTimeFormatterOptions,
    ) -> Result<
        DataPayload<PatternPluralsFromPatternsV1Marker>,
        UnsupportedOptionsOrDataOrPatternError,
    > {
        let selector = PatternSelector {
            data_provider,
            date_patterns_data,
            locale,
            cal_val: Some(cal_val),
        };
        match options {
            DateTimeFormatterOptions::Length(bag) => selector
                .pattern_for_length_bag(bag, Some(preferences::Bag::from_data_locale(locale)))
                .map_err(|e| match e {
                    PatternForLengthError::Data(e) => {
                        UnsupportedOptionsOrDataOrPatternError::Data(e)
                    }
                    PatternForLengthError::Pattern(e) => {
                        UnsupportedOptionsOrDataOrPatternError::Pattern(e)
                    }
                }),
            DateTimeFormatterOptions::Components(bag) => selector
                .patterns_for_components_bag(bag)
                .map_err(|e| match e {
                    UnsupportedOptionsOrDataError::Data(e) => {
                        UnsupportedOptionsOrDataOrPatternError::Data(e)
                    }
                    UnsupportedOptionsOrDataError::UnsupportedOptions => {
                        UnsupportedOptionsOrDataOrPatternError::UnsupportedOptions
                    }
                }),
        }
    }

    /// Determine the appropriate `PatternPlurals` for a given `options::components::Bag`.
    fn patterns_for_components_bag(
        self,
        components: &components::Bag,
    ) -> Result<DataPayload<PatternPluralsFromPatternsV1Marker>, UnsupportedOptionsOrDataError>
    {
        use crate::skeleton;
        let skeletons_data = self
            .skeleton_data_payload()
            .map_err(UnsupportedOptionsOrDataError::Data)?;
        // Not all skeletons are currently supported.
        // TODO(#594) - This should default should be the locale default, which is
        // region-based (h12 for US, h23 for GB, etc). This is in CLDR, but we need
        // to load it as well as think about the best architecture for where that
        // data loading code should reside.
        let requested_fields = components.to_vec_fields(preferences::HourCycle::H23);
        let patterns = match skeleton::create_best_pattern_for_fields(
            skeletons_data.get(),
            &self.date_patterns_data.get().length_combinations,
            &requested_fields,
            components,
            false, // Prefer the requested fields over the matched pattern.
        ) {
            skeleton::BestSkeleton::AllFieldsMatch(pattern)
            | skeleton::BestSkeleton::MissingOrExtraFields(pattern) => Ok(pattern),
            skeleton::BestSkeleton::NoMatch => {
                Err(UnsupportedOptionsOrDataError::UnsupportedOptions)
            }
        }?;
        Ok(DataPayload::from_owned(PatternPluralsV1(
            patterns.into_owned(),
        )))
    }

    fn skeleton_data_payload(
        &self,
    ) -> Result<DataPayload<DateSkeletonPatternsV1Marker>, DataError> {
        use icu_locid::extensions::unicode::{key, value};
        use tinystr::tinystr;
        let mut locale = self.locale.clone();
        #[allow(clippy::expect_used)] // experimental
        let cal_val = self.cal_val.expect("should be present for components bag");
        // Skeleton data for ethioaa is stored under ethiopic
        if cal_val == &value!("ethioaa") {
            locale.set_unicode_ext(key!("ca"), value!("ethiopic"));
        } else if cal_val == &value!("islamic")
            || cal_val == &value!("islamicc")
            || cal_val.as_tinystr_slice().first() == Some(&tinystr!(8, "islamic"))
        {
            // All islamic calendars store skeleton data under islamic, not their individual extension keys
            locale.set_unicode_ext(key!("ca"), value!("islamic"));
        } else {
            locale.set_unicode_ext(key!("ca"), cal_val.clone());
        };

        self.data_provider
            .load(DataRequest {
                locale: &locale,
                metadata: Default::default(),
            })
            .and_then(DataResponse::take_payload)
    }
}

/// Internal enum to represent the kinds of month symbols for interpolation
pub(crate) enum MonthPlaceholderValue<'a> {
    PlainString(&'a str),
    StringNeedingLeapPrefix(&'a str),
    #[cfg(feature = "experimental")]
    Numeric,
    #[cfg(feature = "experimental")]
    NumericPattern(&'a SimpleSubstitutionPattern<'a>),
}

pub(crate) trait DateSymbols<'data> {
    fn get_symbol_for_month(
        &self,
        month: fields::Month,
        length: fields::FieldLength,
        code: MonthCode,
    ) -> Result<MonthPlaceholderValue, GetSymbolForMonthError>;

    fn get_symbol_for_weekday(
        &self,
        weekday: fields::Weekday,
        length: fields::FieldLength,
        day: input::IsoWeekday,
    ) -> Result<&str, GetSymbolForWeekdayError>;

    /// Gets the era symbol, or `None` if data is loaded but symbol isn't found.
    ///
    /// `None` should fall back to the era code directly, if, for example,
    /// a japanext datetime is formatted with a `DateTimeFormat<Japanese>`
    fn get_symbol_for_era<'a>(
        &'a self,
        length: fields::FieldLength,
        era_code: &'a Era,
    ) -> Result<&str, GetSymbolForEraError>;
}

impl<'data> provider::calendar::DateSymbolsV1<'data> {
    fn get_symbols_map_for_month(
        &self,
        month: fields::Month,
        length: fields::FieldLength,
    ) -> Result<&months::SymbolsV1<'data>, core::convert::Infallible> {
        let widths = match month {
            fields::Month::Format => &self.months.format,
            fields::Month::StandAlone => {
                if let Some(ref widths) = self.months.stand_alone {
                    let symbols = match length {
                        fields::FieldLength::Wide => widths.wide.as_ref(),
                        fields::FieldLength::Narrow => widths.narrow.as_ref(),
                        _ => widths.abbreviated.as_ref(),
                    };
                    if let Some(symbols) = symbols {
                        return Ok(symbols);
                    } else {
                        return self.get_symbols_map_for_month(fields::Month::Format, length);
                    }
                } else {
                    return self.get_symbols_map_for_month(fields::Month::Format, length);
                }
            }
        };
        let symbols = match length {
            fields::FieldLength::Wide => &widths.wide,
            fields::FieldLength::Narrow => &widths.narrow,
            _ => &widths.abbreviated,
        };
        Ok(symbols)
    }
}

impl<'data> DateSymbols<'data> for provider::calendar::DateSymbolsV1<'data> {
    fn get_symbol_for_weekday(
        &self,
        weekday: fields::Weekday,
        length: fields::FieldLength,
        day: input::IsoWeekday,
    ) -> Result<&str, GetSymbolForWeekdayError> {
        let widths = match weekday {
            fields::Weekday::Format => &self.weekdays.format,
            fields::Weekday::StandAlone => {
                if let Some(ref widths) = self.weekdays.stand_alone {
                    let symbols = match length {
                        fields::FieldLength::Wide => widths.wide.as_ref(),
                        fields::FieldLength::Narrow => widths.narrow.as_ref(),
                        fields::FieldLength::Six => {
                            widths.short.as_ref().or(widths.abbreviated.as_ref())
                        }
                        _ => widths.abbreviated.as_ref(),
                    };
                    if let Some(symbols) = symbols {
                        let idx = (day as usize) % 7;
                        return symbols
                            .0
                            .get(idx)
                            .map(|x| &**x)
                            .ok_or(GetSymbolForWeekdayError::Missing);
                    } else {
                        return self.get_symbol_for_weekday(fields::Weekday::Format, length, day);
                    }
                } else {
                    return self.get_symbol_for_weekday(fields::Weekday::Format, length, day);
                }
            }
            fields::Weekday::Local => unimplemented!(),
        };
        let symbols = match length {
            fields::FieldLength::Wide => &widths.wide,
            fields::FieldLength::Narrow => &widths.narrow,
            fields::FieldLength::Six => widths.short.as_ref().unwrap_or(&widths.abbreviated),
            _ => &widths.abbreviated,
        };
        let idx = (day as usize) % 7;
        symbols
            .0
            .get(idx)
            .map(|x| &**x)
            .ok_or(GetSymbolForWeekdayError::Missing)
    }

    fn get_symbol_for_month(
        &self,
        month: fields::Month,
        length: fields::FieldLength,
        code: MonthCode,
    ) -> Result<MonthPlaceholderValue, GetSymbolForMonthError> {
        let symbols_map = self.get_symbols_map_for_month(month, length).unwrap();
        let mut symbol_option = symbols_map.get(code);
        let mut fallback = false;
        if symbol_option.is_none() {
            if let Some(code) = code.get_normal_if_leap() {
                let symbols_map = self.get_symbols_map_for_month(month, length).unwrap();
                symbol_option = symbols_map.get(code);
                fallback = true;
            }
        }
        let symbol = symbol_option.ok_or(GetSymbolForMonthError::Missing)?;
        Ok(if fallback {
            MonthPlaceholderValue::StringNeedingLeapPrefix(symbol)
        } else {
            MonthPlaceholderValue::PlainString(symbol)
        })
    }

    fn get_symbol_for_era<'a>(
        &'a self,
        length: fields::FieldLength,
        era_code: &'a Era,
    ) -> Result<&str, GetSymbolForEraError> {
        let symbols = match length {
            fields::FieldLength::Wide => &self.eras.names,
            fields::FieldLength::Narrow => &self.eras.narrow,
            _ => &self.eras.abbr,
        };
        symbols
            .get(era_code.0.as_str().into())
            .ok_or(GetSymbolForEraError::Missing)
    }
}

pub(crate) trait TimeSymbols {
    /// Gets the day period symbol.
    ///
    /// Internally, 'noon' and 'midnight' should fall back to 'am' and 'pm'.
    fn get_symbol_for_day_period(
        &self,
        day_period: fields::DayPeriod,
        length: fields::FieldLength,
        hour: input::IsoHour,
        is_top_of_hour: bool,
    ) -> Result<&str, GetSymbolForDayPeriodError>;
}

impl<'data> TimeSymbols for provider::calendar::TimeSymbolsV1<'data> {
    fn get_symbol_for_day_period(
        &self,
        day_period: fields::DayPeriod,
        length: fields::FieldLength,
        hour: input::IsoHour,
        is_top_of_hour: bool,
    ) -> Result<&str, GetSymbolForDayPeriodError> {
        use fields::{DayPeriod::NoonMidnight, FieldLength};
        let widths = &self.day_periods.format;
        let symbols = match length {
            FieldLength::Wide => &widths.wide,
            FieldLength::Narrow => &widths.narrow,
            _ => &widths.abbreviated,
        };
        Ok(match (day_period, u8::from(hour), is_top_of_hour) {
            (NoonMidnight, 00, true) => symbols.midnight.as_ref().unwrap_or(&symbols.am),
            (NoonMidnight, 12, true) => symbols.noon.as_ref().unwrap_or(&symbols.pm),
            (_, hour, _) if hour < 12 => &symbols.am,
            _ => &symbols.pm,
        })
    }
}