| 1 |
use fluent_bundle::{FluentArgs, FluentBundle, FluentResource, FluentValue}; |
| 2 |
use fluent_syntax::ast; |
| 3 |
use unic_langid::{langid, LanguageIdentifier}; |
| 4 |
|
| 5 |
const LANG_EN: LanguageIdentifier = langid!("en"); |
| 6 |
|
| 7 |
fn add_functions<R>(name: &'static str, bundle: &mut FluentBundle<R>) { |
| 8 |
match name { |
| 9 |
"preferences" => { |
| 10 |
bundle |
| 11 |
.add_function("PLATFORM", |_args, _named_args| { |
| 12 |
return "linux".into(); |
| 13 |
}) |
| 14 |
.expect("Failed to add a function to the bundle."); |
| 15 |
} |
| 16 |
_ => {} |
| 17 |
} |
| 18 |
} |
| 19 |
|
| 20 |
fn get_args(name: &str) -> Option<FluentArgs> { |
| 21 |
match name { |
| 22 |
"preferences" => { |
| 23 |
let mut prefs_args = FluentArgs::new(); |
| 24 |
prefs_args.set("name", FluentValue::from("John")); |
| 25 |
prefs_args.set("tabCount", FluentValue::from(5)); |
| 26 |
prefs_args.set("count", FluentValue::from(3)); |
| 27 |
prefs_args.set("version", FluentValue::from("65.0")); |
| 28 |
prefs_args.set("path", FluentValue::from("/tmp")); |
| 29 |
prefs_args.set("num", FluentValue::from(4)); |
| 30 |
prefs_args.set("email", FluentValue::from("[email protected]")); |
| 31 |
prefs_args.set("value", FluentValue::from(4.5)); |
| 32 |
prefs_args.set("unit", FluentValue::from("mb")); |
| 33 |
prefs_args.set("service-name", FluentValue::from("Mozilla Disk")); |
| 34 |
Some(prefs_args) |
| 35 |
} |
| 36 |
_ => None, |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
fn get_ids(res: &FluentResource) -> Vec<String> { |
| 41 |
res.entries() |
| 42 |
.filter_map(|entry| match entry { |
| 43 |
ast::Entry::Message(ast::Message { id, .. }) => Some(id.name.to_owned()), |
| 44 |
_ => None, |
| 45 |
}) |
| 46 |
.collect() |
| 47 |
} |
| 48 |
|
| 49 |
fn iai_resolve_preferences() { |
| 50 |
let files = &[include_str!("preferences.ftl")]; |
| 51 |
for source in files { |
| 52 |
let res = FluentResource::try_new(source.to_string()).expect("failed to parse FTL."); |
| 53 |
let ids = get_ids(&res); |
| 54 |
let mut bundle = FluentBundle::new(vec![LANG_EN]); |
| 55 |
bundle.add_resource(res).expect("Failed to add a resource."); |
| 56 |
add_functions("preferences", &mut bundle); |
| 57 |
let args = get_args("preferences"); |
| 58 |
let mut s = String::new(); |
| 59 |
for id in &ids { |
| 60 |
let msg = bundle.get_message(id).expect("Message found"); |
| 61 |
let mut errors = vec![]; |
| 62 |
if let Some(value) = msg.value() { |
| 63 |
bundle |
| 64 |
.write_pattern(&mut s, value, args.as_ref(), &mut errors) |
| 65 |
.expect("Failed to write a pattern."); |
| 66 |
s.clear(); |
| 67 |
} |
| 68 |
for attr in msg.attributes() { |
| 69 |
bundle |
| 70 |
.write_pattern(&mut s, attr.value(), args.as_ref(), &mut errors) |
| 71 |
.expect("Failed to write a pattern."); |
| 72 |
s.clear(); |
| 73 |
} |
| 74 |
assert!(errors.len() == 0, "Resolver errors: {:#?}", errors); |
| 75 |
} |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
iai::main!(iai_resolve_preferences); |