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
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use anyhow::{Context, Result};
use std::collections::BTreeMap;
use std::{ffi, fs, io, mem, str};
use tracing::error;
use {
    intl_model as model, rust_icu_common as ucommon, rust_icu_sys as usys, rust_icu_uloc as uloc,
};

/// The directory where localized resources are kept.
pub(crate) const ASSETS_DIR: &str = "/pkg/data/assets/locales";

#[repr(i8)]
#[derive(Debug, PartialEq)]
pub enum LookupStatus {
    // No error.
    OK = 0,
    /// The value requested is not available.
    Unavailable = 1,
    /// The argument passed in by the user is not valid.
    ArgumentError = 2,
    /// Some internal error happened. Consult logs for details.
    Internal = 111,
}

/// The C API supported by the Lookup module.
///
/// The C API is used for FFI interfacing with other languages that support
/// C ABI FFI.
trait CApi {
    /// Looks a message up by its unique `message_id`.  A nonzero status is
    /// returned if the message is not found.
    fn string(&self, message_id: u64) -> Result<&ffi::CStr, LookupStatus>;
}

impl From<str::Utf8Error> for LookupStatus {
    fn from(e: str::Utf8Error) -> Self {
        error!("intl: utf-8: {:?}", e);
        LookupStatus::Unavailable
    }
}

impl From<anyhow::Error> for LookupStatus {
    fn from(e: anyhow::Error) -> Self {
        error!("intl: general: {:?}", e);
        LookupStatus::Internal
    }
}

impl From<ucommon::Error> for LookupStatus {
    fn from(e: ucommon::Error) -> Self {
        error!("intl: icu: {:?}", e);
        LookupStatus::Internal
    }
}

/// Instantiates a fake Lookup instance, which is useful for tests that don't
/// want to make a full end-to-end localization setup.  
///
/// The fake is simplistic and it is the intention that it provides you with
/// some default fake behaviors.  The behaviors are as follows at the moment,
/// and more could be added if needed.
///
/// - If `locale_ids` contains the string `en-US`, the constructor function
///   in the FFI layer will return [LookupStatus::Unavailable].
/// - If the message ID pased to `Lookup::String()` is exactly 1, the fake
///   returns `Hello {person}!`, so that you can test 1-parameter formatting.
/// - Otherwise, for an even mesage ID it returns "Hello world!", or for
///   an odd message ID returns [LookupStatus::Unavailable].
///
/// The implementation of the fake itself is done in rust behind a FFI ABI,
/// see the package //src/lib/intl/lookup/rust for details.
pub struct FakeLookup {
    hello: ffi::CString,
    hello_person: ffi::CString,
}

impl FakeLookup {
    /// Create a new `FakeLookup`.
    pub fn new() -> FakeLookup {
        let hello =
            ffi::CString::new("Hello world!").expect("CString from known value should never fail");
        let hello_person = ffi::CString::new("Hello {person}!")
            .expect("CString from known value should never fail");
        FakeLookup { hello, hello_person }
    }
}

impl CApi for FakeLookup {
    /// A fake implementation of `string` for testing.
    ///
    /// Returns "Hello world" if passed an even `message_id`, and `LookupStatus::UNAVAILABLE` when
    /// passed an odd message_id. Used to test the FFI.
    fn string(&self, message_id: u64) -> Result<&ffi::CStr, LookupStatus> {
        if message_id == 1 {
            return Ok(self.hello_person.as_c_str());
        }
        match message_id % 2 == 0 {
            true => Ok(self.hello.as_c_str()),
            false => Err(LookupStatus::Unavailable),
        }
    }
}

#[allow(clippy::missing_safety_doc)] // TODO(https://fxbug.dev/42181460)
#[no_mangle]
pub unsafe extern "C" fn intl_lookup_new_fake_for_test(
    len: libc::size_t,
    array: *mut *const libc::c_char,
    status: *mut i8,
) -> *const FakeLookup {
    *status = LookupStatus::OK as i8;
    let rsize = len as usize;
    let input: Vec<*const libc::c_char> = Vec::from_raw_parts(array, rsize, rsize);
    // Do not drop the vector we don't own.
    let input = mem::ManuallyDrop::new(input);

    for raw in input.iter() {
        let cstr = ffi::CStr::from_ptr(*raw).to_str().expect("not a valid UTF-8");
        if cstr == "en-US" {
            *status = LookupStatus::Unavailable as i8;
            return std::ptr::null::<FakeLookup>();
        }
    }
    Box::into_raw(Box::new(FakeLookup::new()))
}
#[allow(clippy::missing_safety_doc)] // TODO(https://fxbug.dev/42181460)
#[no_mangle]
pub unsafe extern "C" fn intl_lookup_delete_fake_for_test(this: *mut FakeLookup) {
    generic_delete(this);
}

#[allow(clippy::missing_safety_doc)] // TODO(https://fxbug.dev/42181460)
#[no_mangle]
pub unsafe extern "C" fn intl_lookup_new(
    len: libc::size_t,
    array: *mut *const libc::c_char,
    status: *mut i8,
) -> *const Lookup {
    *status = LookupStatus::OK as i8;
    let rsize = len as usize;
    let input: Vec<*const libc::c_char> = Vec::from_raw_parts(array, rsize, rsize);
    // Do not drop the vector we don't own.
    let input = mem::ManuallyDrop::new(input);

    let mut locales = vec![];
    for raw in input.iter() {
        let cstr = ffi::CStr::from_ptr(*raw).to_str();
        match cstr {
            Err(e) => {
                error!("intl::intl_lookup_new::c_str: {:?}", &e);
                let ls: LookupStatus = e.into();
                *status = ls as i8;
                return std::ptr::null::<Lookup>();
            }
            Ok(s) => {
                locales.push(s);
            }
        }
    }
    let data = icu_data::Loader::new().expect("icu data loaded");
    let lookup_or = Lookup::new(data, &locales[..]);
    match lookup_or {
        Ok(lookup) => Box::into_raw(Box::new(lookup)),
        Err(e) => {
            error!("intl::intl_lookup_new: {:?}", &e);
            let ls: LookupStatus = e.into();
            *status = ls as i8;
            std::ptr::null::<Lookup>()
        }
    }
}

#[allow(clippy::missing_safety_doc)] // TODO(https://fxbug.dev/42181460)
#[no_mangle]
pub unsafe extern "C" fn intl_lookup_delete(instance: *mut Lookup) {
    generic_delete(instance);
}

#[allow(clippy::missing_safety_doc)] // TODO(https://fxbug.dev/42181460)
#[no_mangle]
pub unsafe extern "C" fn intl_lookup_string_fake_for_test(
    this: *const FakeLookup,
    id: u64,
    status: *mut i8,
) -> *const libc::c_char {
    generic_string(this, id, status)
}

unsafe fn generic_string<T: CApi>(this: *const T, id: u64, status: *mut i8) -> *const libc::c_char {
    *status = LookupStatus::OK as i8;
    match this.as_ref().unwrap().string(id) {
        Err(e) => {
            *status = e as i8;
            std::ptr::null()
        }
        Ok(s) => s.as_ptr() as *const libc::c_char,
    }
}

unsafe fn generic_delete<T>(instance: *mut T) {
    let _ = Box::from_raw(instance);
}

#[allow(clippy::missing_safety_doc)] // TODO(https://fxbug.dev/42181460)
#[no_mangle]
pub unsafe extern "C" fn intl_lookup_string(
    this: *const Lookup,
    id: u64,
    status: *mut i8,
) -> *const libc::c_char {
    *status = LookupStatus::OK as i8;
    match this.as_ref().unwrap().string(id) {
        Err(e) => {
            *status = e as i8;
            std::ptr::null()
        }
        Ok(s) => s.as_ptr() as *const libc::c_char,
    }
}

// Contains the message catalog ready for external consumption.  Specifically,
// provides C-style messages
pub struct Catalog {
    locale_to_message: BTreeMap<String, BTreeMap<u64, ffi::CString>>,
}

impl Catalog {
    fn new() -> Catalog {
        let locale_to_message = BTreeMap::new();
        Catalog { locale_to_message }
    }

    fn add(&mut self, model: model::Model) -> Result<()> {
        let locale_id = model.locale();
        let mut messages: BTreeMap<u64, ffi::CString> = BTreeMap::new();
        for (id, msg) in model.messages() {
            let c_msg = ffi::CString::new(msg.clone())
                .with_context(|| format!("interior NUL in  {:?}", msg))?;
            messages.insert(*id, c_msg);
        }
        self.locale_to_message.insert(locale_id.to_string(), messages);
        Ok(())
    }

    fn get(&self, locale: &str, id: u64) -> Option<&ffi::CStr> {
        self.locale_to_message
            .get(locale)
            .map(|messages| messages.get(&id))
            .flatten()
            .map(|cstring| cstring.as_c_str())
    }
}

/// Implements localized string lookup.
///
/// Requires that the ICU data loader is configured and that the ICU data are registered in the
/// program's package.  See the [rust
/// documentation](https://fuchsia.dev/fuchsia-src/development/internationalization/icu_data#rust_example)
/// for detailed instructions.
///
/// ```ignore
/// use intl_lookup::Lookup;
/// let icu_data = icu_data::Loader::new().expect("icu data loaded");
/// let l = Lookup::new(icu_data, &vec!["es"])?;
/// assert_eq!("el stringo", l.str(ftest::MessageIds::StringName as u64)?);
/// ```
pub struct Lookup {
    requested: Vec<uloc::ULoc>,
    catalog: Catalog,
    // The loader is required to ensure that the unicode locale data is kept
    // in memory while this Lookup is in use.
    #[allow(dead_code)]
    icu_data: icu_data::Loader,
}

impl Lookup {
    /// Creates a new instance of Lookup, with the default ways to look up the
    /// data.
    pub fn new(icu_data: icu_data::Loader, requested: &[&str]) -> Result<Lookup> {
        let supported_locales =
            Lookup::get_available_locales().with_context(|| "while creating Lookup")?;
        // Load all available locale maps.
        let catalog = Lookup::load_locales(&supported_locales[..])
            .with_context(|| "while loading locales")?;
        Lookup::new_internal(icu_data, requested, &supported_locales, catalog)
    }

    // Loads all supported locales from disk.
    fn load_locales(supported: &[impl AsRef<str>]) -> Result<Catalog> {
        let mut catalog = Catalog::new();

        // In the future we may decide to load only the locales we actually need.
        for locale in supported {
            // Directory names look like: ".../assets/locales/en-US".
            let mut locale_dir_path = std::path::PathBuf::from(ASSETS_DIR);
            locale_dir_path.push(locale.as_ref());

            let locale_dir = std::fs::read_dir(&locale_dir_path)
                .with_context(|| format!("while reading {:?}", &locale_dir_path))?;
            for entry in locale_dir {
                let path = entry?.path();
                let file = fs::File::open(&path)
                    .with_context(|| format!("while trying to open {:?}", &path))?;
                let file = io::BufReader::new(file);
                let model = model::Model::from_json_reader(file)
                    .with_context(|| format!("while reading {:?}", &path))?;
                catalog.add(model)?;
            }
        }
        Ok(catalog)
    }

    /// Create a new [Lookup] from parts.  Only to be used in tests.
    #[cfg(test)]
    pub fn new_from_parts(
        icu_data: icu_data::Loader,
        requested: &[&str],
        supported: &Vec<String>,
        catalog: Catalog,
    ) -> Result<Lookup> {
        Lookup::new_internal(icu_data, requested, supported, catalog)
    }

    fn new_internal(
        icu_data: icu_data::Loader,
        requested: &[&str],
        supported: &Vec<String>,
        catalog: Catalog,
    ) -> Result<Lookup> {
        let mut supported_locales = supported
            .iter()
            .map(|s: &String| uloc::ULoc::try_from(s.as_str()))
            .collect::<Result<Vec<_>, _>>()
            .with_context(|| "while determining supported locales")?;

        // Work around a locale fallback resolution bug
        // https://unicode-org.atlassian.net/browse/ICU-20931 which has been fixed in ICU 67.  This
        // has to stay in place until Fuchsia starts using ICU version 67.
        supported_locales.push(uloc::ULoc::try_from("und-und")?);
        let supported_locales = supported_locales;

        // Compute a fallback for each requested locale, and fail if none is available.
        let mut requested_locales = vec![];
        for locale in requested.iter() {
            let (maybe_accepted_locale, accept_result) = uloc::accept_language(
                vec![uloc::ULoc::try_from(*locale)
                    .with_context(|| format!("could not parse as locale: {:}", &locale))?],
                supported_locales.clone(),
            )?;
            match accept_result {
                usys::UAcceptResult::ULOC_ACCEPT_FAILED => {
                    // This may happen if the locale is not at all part of the
                    // set of supported locales.
                }
                _ => match maybe_accepted_locale {
                    None => {
                        return Err(anyhow::anyhow!(
                            "no matching locale found for: requested: {:?}, supported: {:?}",
                            &locale,
                            &supported_locales
                        ));
                    }
                    Some(loc) => {
                        requested_locales.push(loc);
                    }
                },
            }
        }
        // We failed to find locales to request from the list of supported locales.
        if requested_locales.is_empty() {
            return Err(anyhow::anyhow!(
                "no matching locale found for: requested: {:?}, supported: {:?}",
                &requested,
                &supported_locales
            ));
        }
        Ok(Lookup { requested: requested_locales, catalog, icu_data })
    }

    #[cfg(test)]
    fn get_available_locales_for_test() -> Result<Vec<String>> {
        Lookup::get_available_locales()
    }

    // Returns the list of locales for which there are resources present in
    // the locale assets directory.  Errors are returned if the locale assets
    // directory is malformed: since it is prepared at compile time, such an
    // occurrence means that the program is corrupted.
    fn get_available_locales() -> Result<Vec<String>> {
        let locale_dirs = std::fs::read_dir(ASSETS_DIR)
            .with_context(|| format!("while reading {}", ASSETS_DIR))?;
        let mut available_locales: Vec<String> = vec![];
        for entry_or in locale_dirs {
            let entry =
                entry_or.with_context(|| format!("while reading entries in {}", ASSETS_DIR))?;
            // We only ever expect directories corresponding to locale names
            // to be UTF-8 encoded, so this conversion will normally always
            // succeed for directories in `ASSETS_DIR`.
            let name = entry.file_name().into_string().map_err(|os_string| {
                anyhow::anyhow!("OS path not convertible to UTF-8: {:?}", os_string)
            })?;
            let entry_type = entry
                .file_type()
                .with_context(|| format!("while looking up file type for: {:?}", name))?;
            if entry_type.is_dir() {
                available_locales.push(name);
            }
        }
        Ok(available_locales)
    }

    /// Looks up the message by its key, a rust API version of [API::string].
    pub fn str(&self, id: u64) -> Result<&str, LookupStatus> {
        Ok(self
            .string(id)?
            .to_str()
            .with_context(|| format!("str(): while looking up id: {}", &id))?)
    }
}

impl CApi for Lookup {
    /// See the documentation for `API` for details.
    fn string(&self, id: u64) -> Result<&ffi::CStr, LookupStatus> {
        for locale in self.requested.iter() {
            if let Some(s) = self.catalog.get(&locale.to_language_tag(false)?, id) {
                return Ok(s);
            }
        }
        Err(LookupStatus::Unavailable)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use fidl_fuchsia_intl_test as ftest;
    use std::collections::HashSet;

    #[test]
    fn lookup_en() -> Result<(), LookupStatus> {
        let icu_data = icu_data::Loader::new().expect("icu data loaded");
        let l = Lookup::new(icu_data, &vec!["en"])?;
        assert_eq!("text_string", l.string(ftest::MessageIds::StringName as u64)?.to_str()?);
        assert_eq!("text_string_2", l.string(ftest::MessageIds::StringName2 as u64)?.to_str()?);
        Ok(())
    }

    #[test]
    fn lookup_fr() -> Result<(), LookupStatus> {
        let icu_data = icu_data::Loader::new().expect("icu data loaded");
        let l = Lookup::new(icu_data, &vec!["fr"])?;
        assert_eq!("le string", l.string(ftest::MessageIds::StringName as u64)?.to_str()?);
        assert_eq!("le string 2", l.string(ftest::MessageIds::StringName2 as u64)?.to_str()?);
        Ok(())
    }

    #[test]
    fn lookup_es() -> Result<(), LookupStatus> {
        let icu_data = icu_data::Loader::new().expect("icu data loaded");
        let l = Lookup::new(icu_data, &vec!["es"])?;
        assert_eq!("el stringo", l.string(ftest::MessageIds::StringName as u64)?.to_str()?);
        assert_eq!("el stringo 2", l.string(ftest::MessageIds::StringName2 as u64)?.to_str()?);
        Ok(())
    }

    // When "es" is preferred, use it.
    #[test]
    fn lookup_es_en() -> Result<(), LookupStatus> {
        let icu_data = icu_data::Loader::new().expect("icu data loaded");
        let l = Lookup::new(icu_data, &vec!["es", "en"])?;
        assert_eq!("el stringo", l.string(ftest::MessageIds::StringName as u64)?.to_str()?);
        assert_eq!("el stringo 2", l.string(ftest::MessageIds::StringName2 as u64)?.to_str()?);
        Ok(())
    }

    #[test]
    fn lookup_es_419_fallback() -> Result<(), LookupStatus> {
        let icu_data = icu_data::Loader::new().expect("icu data loaded");
        let l = Lookup::new(icu_data, &vec!["es-419-u-ca-gregorian"]).expect("locale exists");
        assert_eq!("el stringo", l.string(ftest::MessageIds::StringName as u64)?.to_str()?);
        assert_eq!("el stringo 2", l.string(ftest::MessageIds::StringName2 as u64)?.to_str()?);
        Ok(())
    }

    #[test]
    fn nonexistent_locale_rejected() -> Result<()> {
        let icu_data = icu_data::Loader::new().expect("icu data loaded");
        match Lookup::new(icu_data, &vec!["nonexistent-locale"]) {
            Ok(_) => Err(anyhow::anyhow!("unexpectedly accepted nonexistent locale")),
            Err(_) => Ok(()),
        }
    }

    #[test]
    fn locale_fallback_accounted_for() -> Result<()> {
        let icu_data = icu_data::Loader::new().expect("icu data loaded");
        // These locales are directly supported by the tests.
        Lookup::new(icu_data.clone(), &vec!["en"])?;
        Lookup::new(icu_data.clone(), &vec!["fr"])?;
        Lookup::new(icu_data.clone(), &vec!["es"])?;

        // The following languages are not directly supported.  Instead they
        // are supported via the locale fallback mechanism.

        // Falls back to "en".
        Lookup::new(icu_data.clone(), &vec!["en-US"])?;
        // Falls back to "es".
        Lookup::new(icu_data.clone(), &vec!["es-ES"])?;
        // Falls back to "es", too.
        Lookup::new(icu_data.clone(), &vec!["es-419"])?;
        Ok(())
    }

    // Exercises the fake behaviors which are part of the fake spec.  The fake
    // behaviors may evolve in the future, but this test gives out the ones that
    // currently exist.
    #[test]
    fn test_fake_lookup() -> Result<(), LookupStatus> {
        let l = FakeLookup::new();
        assert_eq!("Hello {person}!", l.string(1)?.to_str()?);
        // Fake lookups always return "Hello world!", that's a FakeLookup
        // feature.
        assert_eq!("Hello world!", l.string(10)?.to_str()?);
        assert_eq!("Hello world!", l.string(12)?.to_str()?);
        assert_eq!(LookupStatus::Unavailable, l.string(11).unwrap_err());
        assert_eq!(LookupStatus::Unavailable, l.string(41).unwrap_err());
        Ok(())
    }

    #[test]
    fn test_real_lookup() -> Result<(), LookupStatus> {
        let icu_data = icu_data::Loader::new().expect("icu data loaded");
        let l = Lookup::new(icu_data, &vec!["es"])?;
        assert_eq!("el stringo", l.str(ftest::MessageIds::StringName as u64)?);
        Ok(())
    }

    /// Locales have been made part of the resources of the test package.
    #[test]
    fn test_available_locales() -> Result<()> {
        // Iteration order is not deterministic.
        let expected: HashSet<String> = ["es", "en", "fr"].iter().map(|s| s.to_string()).collect();
        assert_eq!(expected, Lookup::get_available_locales_for_test()?.into_iter().collect());
        Ok(())
    }

    /// If an unsupported locale has been requested, ignore it in the list and
    /// fall back to something else.
    #[test]
    fn ignore_unavailable_locales() {
        let icu_data = icu_data::Loader::new().expect("icu data loaded");
        let l = Lookup::new(icu_data, &vec!["sr", "es"]).expect("Lookup::new success");
        assert_eq!(
            "el stringo",
            l.str(ftest::MessageIds::StringName as u64).expect("Lookup::str success")
        );
    }

    /// If there is nothing to fall back to, report an error.
    #[test]
    fn report_unavailable_locales_without_alternative() {
        let icu_data = icu_data::Loader::new().expect("icu data loaded");
        let l = Lookup::new(icu_data, &vec!["sr"]);
        assert!(l.is_err());
    }
}