Skip to content

Commit

Permalink
Add colonsAdd colon assignment syntax for tr!, similar to struct fiel…
Browse files Browse the repository at this point in the history
…d assignment

For example: tr!("Hello, %{name}", name: "world");
  • Loading branch information
varphone committed Jan 20, 2024
1 parent 9037613 commit be265e8
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
4 changes: 3 additions & 1 deletion crates/macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,9 @@ pub fn vakey(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
/// // => "Hello, Foo and Bar" (Key `tr_3eULVGYoyiBuaM27F93Mo7` for "Hello, %{name} and %{other}")
///
/// // With locale and variables
/// tr!("Hallo, %{name}", locale = "de", name = "Jason");
/// tr!("Hallo, %{name}", locale = "de", name => "Jason"); // Arrow style
/// tr!("Hallo, %{name}", locale = "de", name = "Jason"); // Asignment style
/// tr!("Hallo, %{name}", locale = "de", name : "Jason"); // Colon style
/// // => "Hallo, Jason" (Key `tr_4Cct6Q289b12SkvF47dXIx` for "Hallo, %{name}")
/// # }
/// ```
Expand Down
11 changes: 9 additions & 2 deletions crates/macro/src/tr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,15 @@ impl syn::parse::Parse for Argument {
.map(|v| v.to_string())
.or_else(|_| input.parse::<LitStr>().map(|v| v.value()))
.map_err(|_| input.error("Expected a `string` literal or an identifier"))?;
let _ = input.parse::<Token![=]>()?;
let _ = input.parse::<Option<Token![>]>>()?;
if input.peek(Token![=>]) {
let _ = input.parse::<Token![=>]>()?;
} else if input.peek(Token![=]) {
let _ = input.parse::<Token![=]>()?;
} else if input.peek(Token![:]) {
let _ = input.parse::<Token![:]>()?;
} else {
return Err(input.error("Expected `=>`, `=` or `:`"));
}
let value = input.parse::<Expr>()?;
Ok(Self { name, value })
}
Expand Down
4 changes: 4 additions & 0 deletions tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,11 @@ mod tests {
);

rust_i18n::set_locale("zh-CN");
assert_eq!(tr!("Hello, %{name}!", name => "world"), "你好,world!");
assert_eq!(tr!("Hello, %{name}!", name = "world"), "你好,world!");
assert_eq!(tr!("Hello, %{name}!", name : "world"), "你好,world!");
assert_eq!(tr!("Hello, %{name}!", name: "world"), "你好,world!");
assert_eq!(tr!("Hello, %{name}!", name:"world"), "你好,world!");

rust_i18n::set_locale("en");
assert_eq!(tr!("Hello, %{name}!", name = "world"), "Hello, world!");
Expand Down

0 comments on commit be265e8

Please sign in to comment.