i18n_embed_fl/lib.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 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 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
use fluent::{FluentAttribute, FluentMessage};
use fluent_syntax::ast::{CallArguments, Expression, InlineExpression, Pattern, PatternElement};
use i18n_embed::{fluent::FluentLanguageLoader, FileSystemAssets, LanguageLoader};
use proc_macro::TokenStream;
use proc_macro_error2::{abort, emit_error, proc_macro_error};
use quote::quote;
use std::{
collections::{HashMap, HashSet},
path::Path,
};
use syn::{parse::Parse, parse_macro_input, spanned::Spanned};
use unic_langid::LanguageIdentifier;
#[cfg(doctest)]
#[macro_use]
extern crate doc_comment;
#[cfg(doctest)]
doctest!("../README.md");
#[derive(Debug)]
enum FlAttr {
/// An attribute ID got provided.
Attr(syn::Lit),
/// No attribute ID got provided.
None,
}
impl Parse for FlAttr {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
if !input.is_empty() {
let fork = input.fork();
fork.parse::<syn::Token![,]>()?;
if fork.parse::<syn::Lit>().is_ok()
&& (fork.parse::<syn::Token![,]>().is_ok() || fork.is_empty())
{
input.parse::<syn::Token![,]>()?;
let literal = input.parse::<syn::Lit>()?;
Ok(Self::Attr(literal))
} else {
Ok(Self::None)
}
} else {
Ok(Self::None)
}
}
}
#[derive(Debug)]
enum FlArgs {
/// `fl!(LOADER, "message", "optional-attribute", args)` where `args` is a
/// `HashMap<&'a str, FluentValue<'a>>`.
HashMap(syn::Expr),
/// ```ignore
/// fl!(LOADER, "message", "optional-attribute",
/// arg1 = "value",
/// arg2 = value2,
/// arg3 = calc_value());
/// ```
KeyValuePairs {
specified_args: HashMap<syn::LitStr, Box<syn::Expr>>,
},
/// `fl!(LOADER, "message", "optional-attribute")` no arguments after the message id and optional attribute id.
None,
}
impl Parse for FlArgs {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
if !input.is_empty() {
input.parse::<syn::Token![,]>()?;
let lookahead = input.fork();
if lookahead.parse::<syn::ExprAssign>().is_err() {
let hash_map = input.parse()?;
return Ok(FlArgs::HashMap(hash_map));
}
let mut args_map: HashMap<syn::LitStr, Box<syn::Expr>> = HashMap::new();
while let Ok(expr) = input.parse::<syn::ExprAssign>() {
let argument_name_ident_opt = match &*expr.left {
syn::Expr::Path(path) => path.path.get_ident(),
_ => None,
};
let argument_name_ident = match argument_name_ident_opt {
Some(ident) => ident,
None => {
return Err(syn::Error::new(
expr.left.span(),
"fl!() unable to parse argument identifier",
))
}
}
.clone();
let argument_name_string = argument_name_ident.to_string();
let argument_name_lit_str =
syn::LitStr::new(&argument_name_string, argument_name_ident.span());
let argument_value = expr.right;
if let Some(_duplicate) = args_map.insert(argument_name_lit_str, argument_value) {
// There's no Clone implementation by default.
let argument_name_lit_str =
syn::LitStr::new(&argument_name_string, argument_name_ident.span());
return Err(syn::Error::new(
argument_name_lit_str.span(),
format!(
"fl!() macro contains a duplicate argument `{}`",
argument_name_lit_str.value()
),
));
}
// parse the next comma if there is one
let _result = input.parse::<syn::Token![,]>();
}
if args_map.is_empty() {
let span = match input.fork().parse::<syn::Expr>() {
Ok(expr) => expr.span(),
Err(_) => input.span(),
};
Err(syn::Error::new(span, "fl!() unable to parse args input"))
} else {
Ok(FlArgs::KeyValuePairs {
specified_args: args_map,
})
}
} else {
Ok(FlArgs::None)
}
}
}
/// Input for the [fl()] macro.
struct FlMacroInput {
fluent_loader: syn::Expr,
message_id: syn::Lit,
attr: FlAttr,
args: FlArgs,
}
impl Parse for FlMacroInput {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
let fluent_loader = input.parse()?;
input.parse::<syn::Token![,]>()?;
let message_id = input.parse()?;
let attr = input.parse()?;
let args = input.parse()?;
Ok(Self {
fluent_loader,
message_id,
attr,
args,
})
}
}
struct DomainSpecificData {
loader: FluentLanguageLoader,
_assets: FileSystemAssets,
}
lazy_static::lazy_static! {
/// Cached data specific to each localization domain, to improve
/// performance of subsequent macro invocations.
static ref DOMAINS: dashmap::DashMap<String, DomainSpecificData> =
dashmap::DashMap::new();
}
/// A macro to obtain localized messages and optionally their attributes, and check the `message_id`, `attribute_id`
/// and arguments at compile time.
///
/// Compile time checks are performed using the `fallback_language`
/// specified in the current crate's `i18n.toml` confiration file.
///
/// This macro supports three different calling syntaxes which are
/// explained in the following sections.
///
/// ## No Arguments
///
/// ```ignore
/// fl!(loader: FluentLanguageLoader, "message_id")
/// ```
///
/// This is the simplest form of the `fl!()` macro, just obtaining a
/// message with no arguments. The `message_id` should be specified as
/// a literal string, and is checked at compile time.
///
/// ### Example
///
/// ```
/// use i18n_embed::{
/// fluent::{fluent_language_loader, FluentLanguageLoader},
/// LanguageLoader,
/// };
/// use i18n_embed_fl::fl;
/// use rust_embed::RustEmbed;
///
/// #[derive(RustEmbed)]
/// #[folder = "i18n/"]
/// struct Localizations;
///
/// let loader: FluentLanguageLoader = fluent_language_loader!();
/// loader
/// .load_languages(&Localizations, &[loader.fallback_language().clone()])
/// .unwrap();
///
/// // Invoke the fl!() macro to obtain the translated message, and
/// // check the message id compile time.
/// assert_eq!("Hello World!", fl!(loader, "hello-world"));
/// ```
///
/// ## Individual Arguments
///
/// ```ignore
/// fl!(
/// loader: FluentLanguageLoader,
/// "message_id",
/// arg1 = value,
/// arg2 = "value",
/// arg3 = function(),
/// ...
/// )
/// ```
///
/// This form of the `fl!()` macro allows individual arguments to be
/// specified in the form `key = value` after the `message_id`. `key`
/// needs to be a valid literal argument name, and `value` can be any
/// expression that resolves to a type that implements
/// `Into<FluentValue>`. The `key`s will be checked at compile time to
/// ensure that they match the arguments specified in original fluent
/// message.
///
/// ### Example
///
/// ```
/// # use i18n_embed::{
/// # fluent::{fluent_language_loader, FluentLanguageLoader},
/// # LanguageLoader,
/// # };
/// # use i18n_embed_fl::fl;
/// # use rust_embed::RustEmbed;
/// # #[derive(RustEmbed)]
/// # #[folder = "i18n/"]
/// # struct Localizations;
/// # let loader: FluentLanguageLoader = fluent_language_loader!();
/// # loader
/// # .load_languages(&Localizations, &[loader.fallback_language().clone()])
/// # .unwrap();
/// let calc_james = || "James".to_string();
/// pretty_assertions::assert_eq!(
/// "Hello \u{2068}Bob\u{2069} and \u{2068}James\u{2069}!",
/// // Invoke the fl!() macro to obtain the translated message, and
/// // check the message id, and arguments at compile time.
/// fl!(loader, "hello-arg-2", name1 = "Bob", name2 = calc_james())
/// );
/// ```
///
/// ## Arguments Hashmap
///
/// ```ignore
/// fl!(
/// loader: FluentLanguageLoader,
/// "message_id",
/// args: HashMap<
/// S where S: Into<Cow<'a, str>> + Clone,
/// T where T: Into<FluentValue>> + Clone>
/// )
/// ```
///
/// With this form of the `fl!()` macro, arguments can be specified at
/// runtime using a [HashMap](std::collections::HashMap), using the
/// same signature as in
/// [FluentLanguageLoader::get_args()](i18n_embed::fluent::FluentLanguageLoader::get_args()).
/// When using this method of specifying argments, they are not
/// checked at compile time.
///
/// ### Example
///
/// ```
/// # use i18n_embed::{
/// # fluent::{fluent_language_loader, FluentLanguageLoader},
/// # LanguageLoader,
/// # };
/// # use i18n_embed_fl::fl;
/// # use rust_embed::RustEmbed;
/// # #[derive(RustEmbed)]
/// # #[folder = "i18n/"]
/// # struct Localizations;
/// # let loader: FluentLanguageLoader = fluent_language_loader!();
/// # loader
/// # .load_languages(&Localizations, &[loader.fallback_language().clone()])
/// # .unwrap();
/// use std::collections::HashMap;
///
/// let mut args: HashMap<&str, &str> = HashMap::new();
/// args.insert("name", "Bob");
///
/// assert_eq!("Hello \u{2068}Bob\u{2069}!", fl!(loader, "hello-arg", args));
/// ```
///
/// ## Attributes
///
/// In all of the above patterns you can optionally include an `attribute_id`
/// after the `message_id`, in which case `fl!` will attempt retrieving the specified
/// attribute belonging to the specified message, optionally formatted with the provided arguments.
///
/// ### Example
///
/// ```
/// # use i18n_embed::{
/// # fluent::{fluent_language_loader, FluentLanguageLoader},
/// # LanguageLoader,
/// # };
/// # use i18n_embed_fl::fl;
/// # use rust_embed::RustEmbed;
/// # #[derive(RustEmbed)]
/// # #[folder = "i18n/"]
/// # struct Localizations;
/// # let loader: FluentLanguageLoader = fluent_language_loader!();
/// # loader
/// # .load_languages(&Localizations, &[loader.fallback_language().clone()])
/// # .unwrap();
/// use std::collections::HashMap;
///
/// let mut args: HashMap<&str, &str> = HashMap::new();
/// args.insert("name", "Bob");
///
/// assert_eq!("Hello \u{2068}Bob\u{2069}'s attribute!", fl!(loader, "hello-arg", "attr", args));
/// ```
#[proc_macro]
#[proc_macro_error]
pub fn fl(input: TokenStream) -> TokenStream {
let input: FlMacroInput = parse_macro_input!(input as FlMacroInput);
let fluent_loader = input.fluent_loader;
let message_id = input.message_id;
let domain = {
let manifest = find_crate::Manifest::new().expect("Error reading Cargo.toml");
manifest.crate_package().map(|pkg| pkg.name).unwrap_or(
std::env::var("CARGO_PKG_NAME").expect("Error fetching `CARGO_PKG_NAME` env"),
)
};
let domain_data = if let Some(domain_data) = DOMAINS.get(&domain) {
domain_data
} else {
let crate_paths = i18n_config::locate_crate_paths()
.unwrap_or_else(|error| panic!("fl!() is unable to locate crate paths: {}", error));
let config_file_path = &crate_paths.i18n_config_file;
let config = i18n_config::I18nConfig::from_file(config_file_path).unwrap_or_else(|err| {
abort! {
proc_macro2::Span::call_site(),
format!(
"fl!() had a problem reading i18n config file {config_file_path:?}: {err}"
);
help = "Try creating the `i18n.toml` configuration file.";
}
});
let fluent_config = config.fluent.unwrap_or_else(|| {
abort! {
proc_macro2::Span::call_site(),
format!(
"fl!() had a problem parsing i18n config file {config_file_path:?}: \
there is no `[fluent]` subsection."
);
help = "Add the `[fluent]` subsection to `i18n.toml`, \
along with its required `assets_dir`.";
}
});
// Use the domain override in the configuration.
let domain = fluent_config.domain.unwrap_or(domain);
let assets_dir = Path::new(&crate_paths.crate_dir).join(fluent_config.assets_dir);
let assets = FileSystemAssets::try_new(assets_dir).unwrap();
let fallback_language: LanguageIdentifier = config.fallback_language;
let loader = FluentLanguageLoader::new(&domain, fallback_language.clone());
loader
.load_languages(&assets, &[fallback_language.clone()])
.unwrap_or_else(|err| match err {
i18n_embed::I18nEmbedError::LanguageNotAvailable(file, language_id) => {
if fallback_language != language_id {
panic!(
"fl!() encountered an unexpected problem, \
the language being loaded (\"{0}\") is not the \
`fallback_language` (\"{1}\")",
language_id, fallback_language
)
}
abort! {
proc_macro2::Span::call_site(),
format!(
"fl!() was unable to load the localization \
file for the `fallback_language` \
(\"{fallback_language}\"): {file}"
);
help = "Try creating the required fluent localization file.";
}
}
_ => panic!(
"fl!() had an unexpected problem while \
loading language \"{0}\": {1}",
fallback_language, err
),
});
let data = DomainSpecificData {
loader,
_assets: assets,
};
DOMAINS.entry(domain.clone()).or_insert(data).downgrade()
};
let message_id_string = match &message_id {
syn::Lit::Str(message_id_str) => {
let message_id_str = message_id_str.value();
Some(message_id_str)
}
unexpected_lit => {
emit_error! {
unexpected_lit,
"fl!() `message_id` should be a literal rust string"
};
None
}
};
let attr = input.attr;
let attr_str;
let attr_lit = match &attr {
FlAttr::Attr(literal) => match literal {
syn::Lit::Str(string_lit) => {
attr_str = Some(string_lit.value());
Some(literal)
}
unexpected_lit => {
attr_str = None;
emit_error! {
unexpected_lit,
"fl!() `message_id` should be a literal rust string"
};
None
}
},
FlAttr::None => {
attr_str = None;
None
}
};
// If we have already confirmed that the loader has the message.
// `false` if we haven't checked, or we have checked but no
// message was found.
let mut checked_loader_has_message = false;
// Same procedure for attributes
let mut checked_message_has_attribute = false;
let gen = match input.args {
FlArgs::HashMap(args_hash_map) => {
if attr_lit.is_none() {
quote! {
(#fluent_loader).get_args(#message_id, #args_hash_map)
}
} else {
quote! {
(#fluent_loader).get_attr_args(#message_id, #attr_lit, #args_hash_map)
}
}
}
FlArgs::None => {
if attr_lit.is_none() {
quote! {
(#fluent_loader).get(#message_id)
}
} else {
quote! {
(#fluent_loader).get_attr(#message_id, #attr_lit)
}
}
}
FlArgs::KeyValuePairs { specified_args } => {
let mut arg_assignments = proc_macro2::TokenStream::default();
for (key, value) in &specified_args {
arg_assignments = quote! {
#arg_assignments
args.insert(#key, #value.into());
}
}
if attr_lit.is_none() {
if let Some(message_id_str) = &message_id_string {
checked_loader_has_message = domain_data
.loader
.with_fluent_message(message_id_str, |message: FluentMessage<'_>| {
check_message_args(message, &specified_args);
})
.is_some();
}
let gen = quote! {
(#fluent_loader).get_args_concrete(
#message_id,
{
let mut args = std::collections::HashMap::new();
#arg_assignments
args
})
};
gen
} else {
if let Some(message_id_str) = &message_id_string {
if let Some(attr_id_str) = &attr_str {
let attr_res = domain_data.loader.with_fluent_message(
message_id_str,
|message: FluentMessage<'_>| match message.get_attribute(attr_id_str) {
Some(attr) => {
check_attribute_args(attr, &specified_args);
true
}
None => false,
},
);
checked_loader_has_message = attr_res.is_some();
checked_message_has_attribute = attr_res.unwrap_or(false);
}
}
let gen = quote! {
(#fluent_loader).get_attr_args_concrete(
#message_id,
#attr_lit,
{
let mut args = std::collections::HashMap::new();
#arg_assignments
args
})
};
gen
}
}
};
if let Some(message_id_str) = &message_id_string {
if !checked_loader_has_message && !domain_data.loader.has(message_id_str) {
let suggestions =
fuzzy_message_suggestions(&domain_data.loader, message_id_str, 5).join("\n");
let hint = format!(
"Perhaps you are looking for one of the following messages?\n\n\
{suggestions}"
);
emit_error! {
message_id,
format!(
"fl!() `message_id` validation failed. `message_id` \
of \"{0}\" does not exist in the `fallback_language` (\"{1}\")",
message_id_str,
domain_data.loader.current_language(),
);
help = "Enter the correct `message_id` or create \
the message in the localization file if the \
intended message does not yet exist.";
hint = hint;
};
} else if let Some(attr_id_str) = &attr_str {
if !checked_message_has_attribute
&& !&domain_data.loader.has_attr(message_id_str, attr_id_str)
{
let suggestions = &domain_data
.loader
.with_fluent_message(message_id_str, |message| {
fuzzy_attribute_suggestions(&message, attr_id_str, 5).join("\n")
})
.unwrap();
let hint = format!(
"Perhaps you are looking for one of the following attributes?\n\n\
{suggestions}"
);
emit_error! {
attr_lit,
format!(
"fl!() `attribute_id` validation failed. `attribute_id` \
of \"{0}\" does not exist in the `fallback_language` (\"{1}\")",
attr_id_str,
domain_data.loader.current_language(),
);
help = "Enter the correct `attribute_id` or create \
the attribute associated with the message in the localization file if the \
intended attribute does not yet exist.";
hint = hint;
};
}
}
}
gen.into()
}
fn fuzzy_message_suggestions(
loader: &FluentLanguageLoader,
message_id_str: &str,
n_suggestions: usize,
) -> Vec<String> {
let mut scored_messages: Vec<(String, usize)> =
loader.with_message_iter(loader.fallback_language(), |message_iter| {
message_iter
.map(|message| {
(
message.id.name.to_string(),
strsim::levenshtein(message_id_str, message.id.name),
)
})
.collect()
});
scored_messages.sort_by_key(|(_message, score)| *score);
scored_messages.truncate(n_suggestions);
scored_messages
.into_iter()
.map(|(message, _score)| message)
.collect()
}
fn fuzzy_attribute_suggestions(
message: &FluentMessage<'_>,
attribute_id_str: &str,
n_suggestions: usize,
) -> Vec<String> {
let mut scored_attributes: Vec<(String, usize)> = message
.attributes()
.map(|attribute| {
(
attribute.id().to_string(),
strsim::levenshtein(attribute_id_str, attribute.id()),
)
})
.collect();
scored_attributes.sort_by_key(|(_attr, score)| *score);
scored_attributes.truncate(n_suggestions);
scored_attributes
.into_iter()
.map(|(attribute, _score)| attribute)
.collect()
}
fn check_message_args(
message: FluentMessage<'_>,
specified_args: &HashMap<syn::LitStr, Box<syn::Expr>>,
) {
if let Some(pattern) = message.value() {
let mut args = Vec::new();
args_from_pattern(pattern, &mut args);
let args_set: HashSet<&str> = args.into_iter().collect();
let key_args: Vec<String> = specified_args
.keys()
.map(|key| {
let arg = key.value();
if !args_set.contains(arg.as_str()) {
let available_args: String = args_set
.iter()
.map(|arg| format!("`{arg}`"))
.collect::<Vec<String>>()
.join(", ");
emit_error! {
key,
format!(
"fl!() argument `{0}` does not exist in the \
fluent message. Available arguments: {1}.",
&arg, available_args
);
help = "Enter the correct arguments, or fix the message \
in the fluent localization file so that the arguments \
match this macro invocation.";
};
}
arg
})
.collect();
let key_args_set: HashSet<&str> = key_args.iter().map(|v| v.as_str()).collect();
let unspecified_args: Vec<String> = args_set
.iter()
.filter_map(|arg| {
if !key_args_set.contains(arg) {
Some(format!("`{arg}`"))
} else {
None
}
})
.collect();
if !unspecified_args.is_empty() {
emit_error! {
proc_macro2::Span::call_site(),
format!(
"fl!() the following arguments have not been specified: {}",
unspecified_args.join(", ")
);
help = "Enter the correct arguments, or fix the message \
in the fluent localization file so that the arguments \
match this macro invocation.";
};
}
}
}
fn check_attribute_args(
attr: FluentAttribute<'_>,
specified_args: &HashMap<syn::LitStr, Box<syn::Expr>>,
) {
let pattern = attr.value();
let mut args = Vec::new();
args_from_pattern(pattern, &mut args);
let args_set: HashSet<&str> = args.into_iter().collect();
let key_args: Vec<String> = specified_args
.keys()
.map(|key| {
let arg = key.value();
if !args_set.contains(arg.as_str()) {
let available_args: String = args_set
.iter()
.map(|arg| format!("`{arg}`"))
.collect::<Vec<String>>()
.join(", ");
emit_error! {
key,
format!(
"fl!() argument `{0}` does not exist in the \
fluent attribute. Available arguments: {1}.",
&arg, available_args
);
help = "Enter the correct arguments, or fix the attribute \
in the fluent localization file so that the arguments \
match this macro invocation.";
};
}
arg
})
.collect();
let key_args_set: HashSet<&str> = key_args.iter().map(|v| v.as_str()).collect();
let unspecified_args: Vec<String> = args_set
.iter()
.filter_map(|arg| {
if !key_args_set.contains(arg) {
Some(format!("`{arg}`"))
} else {
None
}
})
.collect();
if !unspecified_args.is_empty() {
emit_error! {
proc_macro2::Span::call_site(),
format!(
"fl!() the following arguments have not been specified: {}",
unspecified_args.join(", ")
);
help = "Enter the correct arguments, or fix the attribute \
in the fluent localization file so that the arguments \
match this macro invocation.";
};
}
}
fn args_from_pattern<S: Copy>(pattern: &Pattern<S>, args: &mut Vec<S>) {
pattern.elements.iter().for_each(|element| {
if let PatternElement::Placeable { expression } = element {
args_from_expression(expression, args)
}
});
}
fn args_from_expression<S: Copy>(expr: &Expression<S>, args: &mut Vec<S>) {
match expr {
Expression::Inline(inline_expr) => {
args_from_inline_expression(inline_expr, args);
}
Expression::Select { selector, variants } => {
args_from_inline_expression(selector, args);
variants.iter().for_each(|variant| {
args_from_pattern(&variant.value, args);
})
}
}
}
fn args_from_inline_expression<S: Copy>(inline_expr: &InlineExpression<S>, args: &mut Vec<S>) {
match inline_expr {
InlineExpression::FunctionReference {
id: _,
arguments: call_args,
} => {
args_from_call_arguments(call_args, args);
}
InlineExpression::TermReference {
id: _,
attribute: _,
arguments: Some(call_args),
} => {
args_from_call_arguments(call_args, args);
}
InlineExpression::VariableReference { id } => args.push(id.name),
InlineExpression::Placeable { expression } => args_from_expression(expression, args),
_ => {}
}
}
fn args_from_call_arguments<S: Copy>(call_args: &CallArguments<S>, args: &mut Vec<S>) {
call_args.positional.iter().for_each(|expr| {
args_from_inline_expression(expr, args);
});
call_args.named.iter().for_each(|named_arg| {
args_from_inline_expression(&named_arg.value, args);
})
}