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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
// 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 ).

//! This API provides necessary functionality for building user preferences structs.
//!
//! It includes the ability to merge information between the struct and a [`Locale`],
//! facilitating the resolution of attributes against default values.
//!
//! Preferences struct serve as a composable argument to `ICU4X` constructors, allowing
//! for ergonomic merging between information encoded in multiple sets of user inputs:
//! Locale, application preferences and operating system preferences.
//!
//! The crate is intended primarily to be used by components constructors to normalize the format
//! of ingesting preferences across all of `ICU4X`.
//!
//! # Preferences vs Options
//!
//! ICU4X introduces a separation between two classes of parameters that are used
//! to adjust the behavior of a component.
//!
//! `Preferences` represent the user-driven preferences on how the given user wants the internationalization
//! to behave. Those are items like language, script, calendar and numbering systems etc.
//!
//! `Options` represent the developer-driven adjustments that affect how given information is presented
//! based on the requirements of the application like available space or intended tone.
//!
//! # Options Division
//!
//! The `Options` themselves are also divided into options that are affecting data slicing, and ones that don't.
//! This is necessary to allow for DCE and FFI to produce minimal outputs avoiding loading unnecessary data that
//! is never to be used by a given component.
//! The result is that some option keys affect specialized constructors such as `try_new_short`, `try_new_long`, which
//! result in data provider loading only data necessary to format short or long values respectively.
//! For options that are not affecting data slicing, an `Options` struct is provided that the developer
//! can fill with selected key values, or use the defaults.
//!
//! # Preferences Merging
//!
//! In traditional internatonalization APIs, the argument passed to constructors is a locale.
//! ICU4X changes this paradigm by accepting a `Preferences`, which can be extracted from a [`Locale`] and combined with
//! other `Preferences`s provided by the environment.
//!
//! This approach makes it easy for developers to write code that takes just a locale, as in other systems,
//! as well as handle more sophisticated cases where the application may receive, for example, a locale,
//! a set of internationalization preferences specified within the application,
//! and a third set extracted from the operating system's preferences.
//!
//! # ECMA-402 vs ICU4X
//!
//! The result of the two paradigm shifts presented above is that the way constructors work is different.
//!
//! ## ECMA-402
//! ```ignore
//! let locale = new Locale("en-US-u-hc-h12");
//! let options = {
//!   hourCycle: "h24", // user preference
//!   timeStyle: "long", // developer option
//! };
//!
//! let dtf = new DateTimeFormat(locale, options);
//! ```
//!
//! ## ICU4X
//! ```ignore
//! let loc = locale!("en-US-u-hc-h12");
//! let prefs = DateTimeFormatterPreferences {
//!     hour_cycle: HourCycle::H24,
//! };
//! let options = DateTimeFormatterOptions {
//!     time_style: TimeStyle::Long,
//! };
//!
//! let mut combined_prefs = DateTimeFormatterPreferences::from(loc);
//! combined_prefs.extend(prefs);
//!
//! let dtf = DateTimeFormatter::try_new(combined_prefs, options);
//! ```
//!
//! This architecture allows for flexible composition of user and developer settings
//! sourced from different locations in custom ways based on the needs of each deployment.
//!
//! Below are some examples of how the `Preferences` model can be used in different setups.
//!
//! # Examples
//!
//! ```
//! use icu::locale::preferences::{
//!   define_preferences,
//!   extensions::unicode::keywords::HourCycle,
//! };
//! use icu::locale::locale;
//!
//! # fn get_data_locale_from_prefs(input: ExampleComponentPreferences) -> () { () }
//! # fn load_data(locale: ()) -> MyData { MyData {} }
//! # struct MyData {}
//! define_preferences!(
//!     /// Name of the preferences struct
//!     [Copy]
//!     ExampleComponentPreferences,
//!     {
//!         /// A preference relevant to the component
//!         hour_cycle: HourCycle
//!     }
//! );
//!
//! pub struct ExampleComponent {
//!     data: MyData,
//! }
//!
//! impl ExampleComponent {
//!     pub fn new(prefs: ExampleComponentPreferences) -> Self {
//!         let locale = get_data_locale_from_prefs(prefs);
//!         let data = load_data(locale);
//!
//!         Self { data }
//!     }
//! }
//! ```
//!
//! Now we can use that component in multiple different ways,
//!
//! ## Scenario 1: Use Locale as the only input
//! ```
//! # use icu::locale::preferences::{
//! #   define_preferences,
//! #   extensions::unicode::keywords::HourCycle,
//! # };
//! # use icu::locale::locale;
//! # fn get_data_locale_from_prefs(input: ExampleComponentPreferences) -> () { () }
//! # fn load_data(locale: ()) -> MyData { MyData {} }
//! # struct MyData {}
//! # define_preferences!(
//! #     /// Name of the preferences struct
//! #     [Copy]
//! #     ExampleComponentPreferences,
//! #     {
//! #         /// A preference relevant to the component
//! #         hour_cycle: HourCycle
//! #     }
//! # );
//! #
//! # pub struct ExampleComponent {
//! #     data: MyData,
//! # }
//! # impl ExampleComponent {
//! #     pub fn new(prefs: ExampleComponentPreferences) -> Self {
//! #         let locale = get_data_locale_from_prefs(prefs);
//! #         let data = load_data(locale);
//! #
//! #         Self { data }
//! #     }
//! # }
//! let loc = locale!("en-US-u-hc-h23");
//! let tf = ExampleComponent::new(loc.into());
//! ```
//!
//! ## Scenario 2: Compose Preferences and Locale
//! ```
//! # use icu::locale::preferences::{
//! #   define_preferences,
//! #   extensions::unicode::keywords::HourCycle,
//! # };
//! # use icu::locale::locale;
//! # fn get_data_locale_from_prefs(input: ExampleComponentPreferences) -> () { () }
//! # fn load_data(locale: ()) -> MyData { MyData {} }
//! # struct MyData {}
//! # define_preferences!(
//! #     /// Name of the preferences struct
//! #     [Copy]
//! #     ExampleComponentPreferences,
//! #     {
//! #         /// A preference relevant to the component
//! #         hour_cycle: HourCycle
//! #     }
//! # );
//! #
//! # pub struct ExampleComponent {
//! #     data: MyData,
//! # }
//! # impl ExampleComponent {
//! #     pub fn new(prefs: ExampleComponentPreferences) -> Self {
//! #         let locale = get_data_locale_from_prefs(prefs);
//! #         let data = load_data(locale);
//! #
//! #         Self { data }
//! #     }
//! # }
//! let loc = locale!("en-US-u-hc-h23");
//! let app_prefs = ExampleComponentPreferences {
//!     hour_cycle: Some(HourCycle::H12),
//!     ..Default::default()
//! };
//!
//! let mut combined_prefs = ExampleComponentPreferences::from(loc);
//! combined_prefs.extend(app_prefs);
//!
//! // HourCycle is set from the prefs bag and override the value from the locale
//! assert_eq!(combined_prefs.hour_cycle, Some(HourCycle::H12));
//!
//! let tf = ExampleComponent::new(combined_prefs);
//! ```
//!
//! ## Scenario 3: Merge Preferences from Locale, OS, and Application
//! ```
//! # use icu::locale::preferences::{
//! #   define_preferences,
//! #   extensions::unicode::keywords::HourCycle,
//! # };
//! # use icu::locale::locale;
//! # fn get_data_locale_from_prefs(input: ExampleComponentPreferences) -> () { () }
//! # fn load_data(locale: ()) -> MyData { MyData {} }
//! # struct MyData {}
//! # define_preferences!(
//! #     /// Name of the preferences struct
//! #     [Copy]
//! #     ExampleComponentPreferences,
//! #     {
//! #         /// A preference relevant to the component
//! #         hour_cycle: HourCycle
//! #     }
//! # );
//! #
//! # pub struct ExampleComponent {
//! #     data: MyData,
//! # }
//! # impl ExampleComponent {
//! #     pub fn new(prefs: ExampleComponentPreferences) -> Self {
//! #         let locale = get_data_locale_from_prefs(prefs);
//! #         let data = load_data(locale);
//! #
//! #         Self { data }
//! #     }
//! # }
//! let loc = locale!("en-US-u-hc-h24");
//!
//! // Simulate OS preferences
//! let os_prefs = ExampleComponentPreferences {
//!     hour_cycle: Some(HourCycle::H23),
//!     ..Default::default()
//! };
//!
//! // Application does not specify hour_cycle
//! let app_prefs = ExampleComponentPreferences {
//!     hour_cycle: Some(HourCycle::H12),
//!     ..Default::default()
//! };
//!
//! let mut combined_prefs = ExampleComponentPreferences::from(loc);
//! combined_prefs.extend(os_prefs);
//! combined_prefs.extend(app_prefs);
//!
//! // HourCycle is set from the OS preferences since the application didn't specify it
//! assert_eq!(combined_prefs.hour_cycle, Some(HourCycle::H12));
//!
//! let tf = ExampleComponent::new(combined_prefs);
//! ```
//!
//! ## Scenario 4: Neither Application nor OS specify the preference
//! ```
//! # use icu::locale::preferences::{
//! #   define_preferences,
//! #   extensions::unicode::keywords::HourCycle,
//! # };
//! # use icu::locale::locale;
//! # fn get_data_locale_from_prefs(input: ExampleComponentPreferences) -> () { () }
//! # fn load_data(locale: ()) -> MyData { MyData {} }
//! # struct MyData {}
//! # define_preferences!(
//! #     /// Name of the preferences struct
//! #     [Copy]
//! #     ExampleComponentPreferences,
//! #     {
//! #         /// A preference relevant to the component
//! #         hour_cycle: HourCycle
//! #     }
//! # );
//! #
//! # pub struct ExampleComponent {
//! #     data: MyData,
//! # }
//! # impl ExampleComponent {
//! #     pub fn new(prefs: ExampleComponentPreferences) -> Self {
//! #         let locale = get_data_locale_from_prefs(prefs);
//! #         let data = load_data(locale);
//! #
//! #         Self { data }
//! #     }
//! # }
//! let loc = locale!("en-US-u-hc-h24");
//!
//! // Simulate OS preferences
//! let os_prefs = ExampleComponentPreferences::default(); // OS does not specify hour_cycle
//! let app_prefs = ExampleComponentPreferences::default(); // Application does not specify hour_cycle
//!
//! let mut combined_prefs = ExampleComponentPreferences::from(loc);
//! combined_prefs.extend(os_prefs);
//! combined_prefs.extend(app_prefs);
//!
//! // HourCycle is taken from the locale
//! assert_eq!(combined_prefs.hour_cycle, Some(HourCycle::H24));
//!
//! let tf = ExampleComponent::new(combined_prefs);
//! ```
//!
//! [`ICU4X`]: ../icu/index.html
//! [`Locale`]: crate::Locale

pub mod extensions;
mod locale;
pub use locale::*;

/// A low-level trait implemented on each preference exposed in component preferences.
///
/// [`PreferenceKey`] has to be implemented on
/// preferences that are to be included in Formatter preferences.
/// The trait may be implemented to indicate that the given preference has
/// a unicode key corresponding to it or be a custom one.
///
/// `ICU4X` provides an implementation of [`PreferenceKey`] for all
/// Unicode Extension Keys. The only external use of this trait is to implement
/// it on custom preferences that are to be included in a component preferences bag.
///
/// The below example show cases a manual generation of an `em` (emoji) unicode extension key
/// and a custom struct to showcase the difference in their behavior. For all use purposes,
/// the [`EmojiPresentationStyle`](crate::preferences::extensions::unicode::keywords::EmojiPresentationStyle) preference exposed by this crate should be used.
///
/// # Examples
/// ```
/// use icu::locale::{
///   extensions::unicode::{key, Key, value, Value},
///   preferences::{
///     define_preferences, PreferenceKey,
///     extensions::unicode::errors::PreferencesParseError,
///   },
/// };
///
/// #[non_exhaustive]
/// #[derive(Debug, Clone, Eq, PartialEq, Copy, Hash, Default)]
/// pub enum EmojiPresentationStyle {
///     Emoji,
///     Text,
///     #[default]
///     Default,
/// }
///
/// impl PreferenceKey for EmojiPresentationStyle {
///     fn unicode_extension_key() -> Option<Key> {
///         Some(key!("em"))
///     }
///
///     fn try_from_key_value(
///         key: &Key,
///         value: &Value,
///     ) -> Result<Option<Self>, PreferencesParseError> {
///         if Self::unicode_extension_key() == Some(*key) {
///             let subtag = value.as_single_subtag()
///                               .ok_or(PreferencesParseError::InvalidKeywordValue)?;
///             match subtag.as_str() {
///                 "emoji" => Ok(Some(Self::Emoji)),
///                 "text" => Ok(Some(Self::Text)),
///                 "default" => Ok(Some(Self::Default)),
///                 _ => Err(PreferencesParseError::InvalidKeywordValue)
///             }
///         } else {
///             Ok(None)
///         }
///     }
///
///     fn unicode_extension_value(&self) -> Option<Value> {
///         Some(match self {
///             EmojiPresentationStyle::Emoji => value!("emoji"),
///             EmojiPresentationStyle::Text => value!("text"),
///             EmojiPresentationStyle::Default => value!("default"),
///         })
///     }
/// }
///
/// #[non_exhaustive]
/// #[derive(Debug, Clone, Eq, PartialEq, Hash)]
/// pub struct CustomFormat {
///     value: String
/// }
///
/// impl PreferenceKey for CustomFormat {}
///
/// define_preferences!(
///     MyFormatterPreferences,
///     {
///         emoji: EmojiPresentationStyle,
///         custom: CustomFormat
///     }
/// );
/// ```
/// [`ICU4X`]: ../icu/index.html
pub trait PreferenceKey: Sized {
    /// Optional constructor of the given preference. It takes the
    /// unicode extension key and if the key matches it attemptes to construct
    /// the preference based on the given value.
    /// If the value is not a valid value for the given key, the constructor throws.
    fn try_from_key_value(
        _key: &crate::extensions::unicode::Key,
        _value: &crate::extensions::unicode::Value,
    ) -> Result<Option<Self>, crate::preferences::extensions::unicode::errors::PreferencesParseError>
    {
        Ok(None)
    }

    /// Retrieve unicode extension key corresponding to a given preference.
    fn unicode_extension_key() -> Option<crate::extensions::unicode::Key> {
        None
    }

    /// Retrieve unicode extension value corresponding to the given instance of the preference.
    fn unicode_extension_value(&self) -> Option<crate::extensions::unicode::Value> {
        None
    }
}

/// A macro to facilitate generation of preferences struct.
///
///
/// The generated preferences struct provides methods for merging and converting between [`Locale`] and
/// the preference bag. See [`preferences`](crate::preferences) for use cases.
///
/// In the example below, the input argument is the generated preferences struct which
/// can be auto-converted from a Locale, or combined from a Locale and Preferences Bag.
///
/// # Examples
/// ```
/// use icu::locale::{
///     preferences::{
///         define_preferences,
///         extensions::unicode::keywords::HourCycle
///     },
///     locale,
/// };
///
/// define_preferences!(
///     [Copy]
///     TimeFormatterPreferences,
///     {
///         hour_cycle: HourCycle
///     }
/// );
///
/// struct TimeFormatter {}
///
/// impl TimeFormatter {
///     pub fn try_new(prefs: TimeFormatterPreferences) -> Result<Self, ()> {
///         // load data and set struct fields based on the prefs input
///         Ok(Self {})
///     }
/// }
///
/// let loc = locale!("en-US");
///
/// let tf = TimeFormatter::try_new(loc.into());
/// ```
///
/// [`Locale`]: crate::Locale
#[macro_export]
#[doc(hidden)]
macro_rules! __define_preferences {
    (
        $(#[$doc:meta])*
        $([$derive_attrs:ty])?
        $name:ident,
        {
            $(
                $(#[$key_doc:meta])*
                $key:ident: $pref:ty
            ),*
        }
     ) => (
        $(#[$doc])*
        #[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
        $(#[derive($derive_attrs)])?
        #[non_exhaustive]
        pub struct $name {
            /// Locale Preferences for the Preferences structure.
            pub locale_prefs: $crate::preferences::LocalePreferences,

            $(
                $(#[$key_doc])*
                pub $key: Option<$pref>,
            )*
        }

        impl From<$crate::Locale> for $name {
            fn from(loc: $crate::Locale) -> Self {
                $name::from(&loc)
            }
        }

        impl From<&$crate::Locale> for $name {
            fn from(loc: &$crate::Locale) -> Self {
                use $crate::preferences::PreferenceKey;

                $(
                    let mut $key = None;
                )*

                for (k, v) in loc.extensions.unicode.keywords.iter() {
                    $(
                        if let Ok(Some(r)) = <$pref>::try_from_key_value(k, v) {
                            $key = Some(r);
                            continue;
                        }
                    )*
                }

                Self {
                    locale_prefs: loc.into(),

                    $(
                        $key,
                    )*
                }
            }
        }

        impl From<$crate::LanguageIdentifier> for $name {
            fn from(lid: $crate::LanguageIdentifier) -> Self {
                $name::from(&lid)
            }
        }

        impl From<&$crate::LanguageIdentifier> for $name {
            fn from(lid: &$crate::LanguageIdentifier) -> Self {
                Self {
                    locale_prefs: lid.into(),

                    $(
                        $key: None,
                    )*
                }
            }
        }

        impl From<$name> for $crate::Locale {
            fn from(other: $name) -> Self {
                use $crate::preferences::PreferenceKey;
                let mut result = Self::from(other.locale_prefs);
                $(
                    if let Some(value) = other.$key {
                        if let Some(ue) = <$pref>::unicode_extension_key() {
                            let val = value.unicode_extension_value().unwrap();
                            result.extensions.unicode.keywords.set(ue, val);
                        }
                    }
                )*
                result
            }
        }

        impl $name {
            /// Extends the preferences with the values from another set of preferences.
            pub fn extend(&mut self, other: $name) {
                self.locale_prefs.extend(other.locale_prefs);
                $(
                    if let Some(value) = other.$key {
                        self.$key = Some(value);
                    }
                )*
            }
        }
    )
}

#[macro_export]
#[doc(hidden)]
macro_rules! __prefs_convert {
    (
        $name1:ident,
        $name2:ident
    ) => {
        impl From<&$name1> for $name2 {
            fn from(other: &$name1) -> Self {
                let mut result = Self::default();
                result.locale_prefs = other.locale_prefs;
                result
            }
        }
    };
    (
        $name1:ident,
        $name2:ident,
        {
            $(
                $key:ident
            ),*
        }
    ) => {
        impl From<&$name1> for $name2 {
            fn from(other: &$name1) -> Self {
                let mut result = Self::default();
                result.locale_prefs = other.locale_prefs;
                $(
                    result.$key = other.$key;
                )*
                result
            }
        }
    };
}

#[doc(inline)]
pub use __define_preferences as define_preferences;

#[doc(inline)]
pub use __prefs_convert as prefs_convert;