aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
author魏曹先生 <1992414357@qq.com>2026-06-17 00:14:14 +0800
committer魏曹先生 <1992414357@qq.com>2026-06-17 00:38:17 +0800
commit83d91396bc84a0a35b5b676ab8c2518678a1dd3f (patch)
treec3cca7c0faa6b4750993379ff9d6fee3d866ee82
Restructure workspace into subcrates0.1.0
-rw-r--r--.gitignore1
-rw-r--r--Cargo.lock178
-rw-r--r--Cargo.toml17
-rw-r--r--LICENSE-APACHE202
-rw-r--r--LICENSE-MIT9
-rw-r--r--README.md84
-rw-r--r--shakehand-test/Cargo.toml7
-rw-r--r--shakehand-test/locale/global.toml59
-rw-r--r--shakehand-test/src/lib.rs105
-rw-r--r--shakehand/Cargo.toml20
-rw-r--r--shakehand/src/analyzer.rs261
-rw-r--r--shakehand/src/lib.rs145
-rw-r--r--shakehand/src/shakehand.rs425
-rw-r--r--shakehand/test-locale/global.toml7
14 files changed, 1520 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..eb5a316
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+target
diff --git a/Cargo.lock b/Cargo.lock
new file mode 100644
index 0000000..427051d
--- /dev/null
+++ b/Cargo.lock
@@ -0,0 +1,178 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+
+[[package]]
+name = "indexmap"
+version = "2.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
+dependencies = [
+ "equivalent",
+ "hashbrown",
+]
+
+[[package]]
+name = "just_fmt"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5454cda0d57db59778608d7a47bff5b16c6705598265869fb052b657f66cf05e"
+
+[[package]]
+name = "memchr"
+version = "2.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "serde"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_spanned"
+version = "0.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "shakehand"
+version = "0.1.0"
+dependencies = [
+ "just_fmt",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "toml",
+]
+
+[[package]]
+name = "shakehand_test"
+version = "0.1.0"
+dependencies = [
+ "shakehand",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.117"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "toml"
+version = "0.8.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
+dependencies = [
+ "serde",
+ "serde_spanned",
+ "toml_datetime",
+ "toml_edit",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "0.6.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.22.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
+dependencies = [
+ "indexmap",
+ "serde",
+ "serde_spanned",
+ "toml_datetime",
+ "toml_write",
+ "winnow",
+]
+
+[[package]]
+name = "toml_write"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "winnow"
+version = "0.7.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
+dependencies = [
+ "memchr",
+]
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..026a106
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,17 @@
+[workspace]
+members = ["shakehand", "shakehand-test"]
+resolver = "2"
+
+[workspace.package]
+version = "0.1.0"
+edition = "2024"
+repository = "https://github.com/catilgrass/shakehand"
+homepage = "https://github.com/catilgrass/shakehand"
+
+[workspace.dependencies]
+shakehand = { path = "shakehand" }
+syn = "2.0.117"
+quote = "1.0.45"
+proc-macro2 = "1.0.106"
+just_fmt = "0.1.2"
+toml = "0.8"
diff --git a/LICENSE-APACHE b/LICENSE-APACHE
new file mode 100644
index 0000000..51eefef
--- /dev/null
+++ b/LICENSE-APACHE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2026 Weicao-CatilGrass
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/LICENSE-MIT b/LICENSE-MIT
new file mode 100644
index 0000000..4ff38a3
--- /dev/null
+++ b/LICENSE-MIT
@@ -0,0 +1,9 @@
+# The MIT License (MIT)
+
+Copyright © 2026 Weicao-CatilGrass
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..e4ea242
--- /dev/null
+++ b/README.md
@@ -0,0 +1,84 @@
+# "Shake Hand!"
+
+> Let different languages shake hands with each other! 🤝
+
+This is a **purely compile-time** Rust internationalization library. **All** localized strings are fully embedded into the binary at compile time, with only minimal runtime overhead.
+
+# How to Use?
+
+## 1. Add Dependency
+
+Add the following to your `Cargo.toml`:
+
+```toml
+shakehand = "0.1"
+```
+
+## 2. Write Configuration Files
+
+Create a directory under your project to serve as the root for translations, e.g. `./locale/`.
+Create any `toml` file inside this directory, e.g. `./locale/global.toml`, representing a translation file.
+
+In the file, group translations by language section. The key is the translation key, and the value is the translated text.
+Text with parameters uses `%{parameter_name}` as placeholders, where the parameter name directly maps to the generated function's parameter name:
+
+```toml
+[en]
+world = "world"
+greeting = "Hello, %{someone}!"
+
+[zh_CN]
+world = "世界"
+greeting = "你好,%{someone}!"
+```
+
+## 3. Load Translations
+
+In your Rust code, use `shakehand::locale!` to hardcode the entire directory into a module:
+
+```rust
+pub mod translation {
+ shakehand::locale!("./locale", fallback = "en");
+}
+```
+
+The generated module will contain:
+- A `Languages` enum listing all languages
+- A `set_lang` function for switching the current language
+- A unit struct `Global` (named after `global.toml`), whose associated functions are the translations for each key
+
+## 4. Call Translations
+
+Call translations just like ordinary functions, passing parameters by placeholder name:
+
+```rust
+use crate::translation::{Global, Languages, set_lang};
+
+fn main() {
+ set_lang(Languages::en);
+ let greeting = Global::greeting("World");
+ println!("{}", greeting); // Hello, World!
+
+ set_lang(Languages::zh_CN);
+ let greeting = Global::greeting("世界");
+ println!("{}", greeting); // 你好,世界!
+}
+```
+
+You can also pass the return value of another translation as a parameter, since each parameterless translation function returns a `&'static str`, completely allocation-free:
+
+```rust
+let greeting = Global::greeting(Global::world());
+```
+
+
+
+# Contributing
+
+Directly open a PR to the [repository](https://github.com/catilgrass/shakehand) and mention [@Weicao-CatilGrass](https://github.com/Weicao-CatilGrass).
+
+
+
+# License
+
+MIT or Apache 2.0
diff --git a/shakehand-test/Cargo.toml b/shakehand-test/Cargo.toml
new file mode 100644
index 0000000..3f20603
--- /dev/null
+++ b/shakehand-test/Cargo.toml
@@ -0,0 +1,7 @@
+[package]
+name = "shakehand_test"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
+shakehand.workspace = true
diff --git a/shakehand-test/locale/global.toml b/shakehand-test/locale/global.toml
new file mode 100644
index 0000000..e85227c
--- /dev/null
+++ b/shakehand-test/locale/global.toml
@@ -0,0 +1,59 @@
+[en]
+world = "world"
+greeting = "Hello, %{someone}!"
+farewell = "Goodbye, %{someone}!"
+thanks = "Thank you!"
+
+[zh_CN]
+world = "世界"
+greeting = "你好,%{someone}!"
+farewell = "再见,%{someone}!"
+thanks = "谢谢!"
+
+[ja]
+world = "世界"
+greeting = "こんにちは、%{someone}!"
+farewell = "さようなら、%{someone}!"
+thanks = "ありがとうございます!"
+
+[ko]
+world = "세계"
+greeting = "안녕하세요, %{someone}님!"
+farewell = "안녕히 가세요, %{someone}님!"
+thanks = "감사합니다!"
+
+[fr]
+world = "monde"
+greeting = "Bonjour, %{someone} !"
+farewell = "Au revoir, %{someone} !"
+thanks = "Merci !"
+
+[de]
+world = "Welt"
+greeting = "Hallo, %{someone}!"
+farewell = "Auf Wiedersehen, %{someone}!"
+thanks = "Danke!"
+
+[es]
+world = "mundo"
+greeting = "¡Hola, %{someone}!"
+farewell = "¡Adiós, %{someone}!"
+thanks = "¡Gracias!"
+
+[ru]
+world = "мир"
+greeting = "Привет, %{someone}!"
+farewell = "До свидания, %{someone}!"
+thanks = "Спасибо!"
+
+[ar]
+world = "عالم"
+greeting = "مرحبًا، %{someone}!"
+farewell = "وداعًا، %{someone}!"
+thanks = "شكرًا!"
+
+[pt]
+world = "mundo"
+greeting = "Olá, %{someone}!"
+farewell = "Tchau, %{someone}!"
+thanks = "Obrigado!"
diff --git a/shakehand-test/src/lib.rs b/shakehand-test/src/lib.rs
new file mode 100644
index 0000000..c290533
--- /dev/null
+++ b/shakehand-test/src/lib.rs
@@ -0,0 +1,105 @@
+#[cfg(test)]
+mod test {
+ use crate::locale::{Global, Languages, set_lang};
+
+ #[test]
+ fn test_english() {
+ set_lang(Languages::en);
+ assert_eq!(Global::world(), "world");
+ assert_eq!(Global::greeting("Alice"), "Hello, Alice!");
+ assert_eq!(Global::farewell("Bob"), "Goodbye, Bob!");
+ assert_eq!(Global::thanks(), "Thank you!");
+ }
+
+ #[test]
+ fn test_chinese() {
+ set_lang(Languages::zh_CN);
+ assert_eq!(Global::world(), "世界");
+ assert_eq!(Global::greeting("小明"), "你好,小明!");
+ assert_eq!(Global::farewell("小红"), "再见,小红!");
+ assert_eq!(Global::thanks(), "谢谢!");
+ }
+
+ #[test]
+ fn test_japanese() {
+ set_lang(Languages::ja);
+ assert_eq!(Global::world(), "世界");
+ assert_eq!(Global::greeting("田中"), "こんにちは、田中!");
+ assert_eq!(Global::farewell("佐藤"), "さようなら、佐藤!");
+ assert_eq!(Global::thanks(), "ありがとうございます!");
+ }
+
+ #[test]
+ fn test_korean() {
+ set_lang(Languages::ko);
+ assert_eq!(Global::world(), "세계");
+ assert_eq!(Global::greeting("철수"), "안녕하세요, 철수님!");
+ assert_eq!(Global::farewell("영희"), "안녕히 가세요, 영희님!");
+ assert_eq!(Global::thanks(), "감사합니다!");
+ }
+
+ #[test]
+ fn test_french() {
+ set_lang(Languages::fr);
+ assert_eq!(Global::world(), "monde");
+ assert_eq!(Global::greeting("Marie"), "Bonjour, Marie !");
+ assert_eq!(Global::farewell("Pierre"), "Au revoir, Pierre !");
+ assert_eq!(Global::thanks(), "Merci !");
+ }
+
+ #[test]
+ fn test_german() {
+ set_lang(Languages::de);
+ assert_eq!(Global::world(), "Welt");
+ assert_eq!(Global::greeting("Hans"), "Hallo, Hans!");
+ assert_eq!(Global::farewell("Greta"), "Auf Wiedersehen, Greta!");
+ assert_eq!(Global::thanks(), "Danke!");
+ }
+
+ #[test]
+ fn test_spanish() {
+ set_lang(Languages::es);
+ assert_eq!(Global::world(), "mundo");
+ assert_eq!(Global::greeting("Carlos"), "¡Hola, Carlos!");
+ assert_eq!(Global::farewell("Lucía"), "¡Adiós, Lucía!");
+ assert_eq!(Global::thanks(), "¡Gracias!");
+ }
+
+ #[test]
+ fn test_russian() {
+ set_lang(Languages::ru);
+ assert_eq!(Global::world(), "мир");
+ assert_eq!(Global::greeting("Анна"), "Привет, Анна!");
+ assert_eq!(Global::farewell("Иван"), "До свидания, Иван!");
+ assert_eq!(Global::thanks(), "Спасибо!");
+ }
+
+ #[test]
+ fn test_arabic() {
+ set_lang(Languages::ar);
+ assert_eq!(Global::world(), "عالم");
+ assert_eq!(Global::greeting("أحمد"), "مرحبًا، أحمد!");
+ assert_eq!(Global::farewell("فاطمة"), "وداعًا، فاطمة!");
+ assert_eq!(Global::thanks(), "شكرًا!");
+ }
+
+ #[test]
+ fn test_portuguese() {
+ set_lang(Languages::pt);
+ assert_eq!(Global::world(), "mundo");
+ assert_eq!(Global::greeting("João"), "Olá, João!");
+ assert_eq!(Global::farewell("Maria"), "Tchau, Maria!");
+ assert_eq!(Global::thanks(), "Obrigado!");
+ }
+
+ #[test]
+ fn test_parameterless_translation_as_param() {
+ set_lang(Languages::en);
+ let greeting = Global::greeting(Global::world());
+ assert_eq!(greeting, "Hello, world!");
+ }
+}
+
+mod locale {
+ shakehand::locale!("./locale");
+}
diff --git a/shakehand/Cargo.toml b/shakehand/Cargo.toml
new file mode 100644
index 0000000..2a0bb9e
--- /dev/null
+++ b/shakehand/Cargo.toml
@@ -0,0 +1,20 @@
+[package]
+name = "shakehand"
+version.workspace = true
+edition.workspace = true
+description = "A rust i18n lib - Let different languages shake hands with each other!"
+license = "MIT OR Apache-2.0"
+repository.workspace = true
+homepage.workspace = true
+keywords = ["internationalization", "i18n", "localization", "translation", "compile-time"]
+categories = ["internationalization", "localization"]
+
+[lib]
+proc-macro = true
+
+[dependencies]
+syn = { workspace = true }
+quote = { workspace = true }
+proc-macro2 = { workspace = true }
+just_fmt = { workspace = true }
+toml = { workspace = true }
diff --git a/shakehand/src/analyzer.rs b/shakehand/src/analyzer.rs
new file mode 100644
index 0000000..3007f58
--- /dev/null
+++ b/shakehand/src/analyzer.rs
@@ -0,0 +1,261 @@
+use std::collections::{BTreeMap, BTreeSet};
+use std::fs;
+use std::path::{Path, PathBuf};
+use syn::{
+ Ident, LitStr, Token,
+ parse::{Parse, ParseStream},
+};
+
+/// Macro input: `shakehand::locale!("../i18n/", fallback = "en")`
+pub struct ShakehandInput {
+ pub path: String,
+ pub fallback: String,
+}
+
+impl Parse for ShakehandInput {
+ fn parse(input: ParseStream) -> syn::Result<Self> {
+ let path_lit: LitStr = input.parse()?;
+ let path = path_lit.value();
+
+ let mut fallback = String::from("en");
+
+ if input.peek(Token![,]) {
+ let _: Token![,] = input.parse()?;
+ if input.peek(Ident) {
+ let ident: Ident = input.parse()?;
+ if ident == "fallback" {
+ let _: Token![=] = input.parse()?;
+ let fb: LitStr = input.parse()?;
+ fallback = fb.value();
+ }
+ }
+ }
+
+ Ok(ShakehandInput { path, fallback })
+ }
+}
+
+/// A translation entry
+#[derive(Clone)]
+pub struct TranslationEntry {
+ /// All keys
+ pub key: String,
+
+ /// All values
+ pub values: BTreeMap<String, String>,
+
+ /// Whether parameters exist, affects the function signature
+ pub has_params: bool,
+
+ /// Canonical parameter name list, valid when there is no conflict
+ ///
+ /// **Order**: taken from the first language that has parameters
+ pub params: Vec<String>,
+
+ /// Whether the entry has a conflict
+ ///
+ /// Conflicts arise in the following cases:
+ /// - Inconsistent parameter counts
+ /// - Inconsistent parameter names
+ pub params_conflict: bool,
+}
+
+/// The parsing result of a toml file
+#[derive(Clone)]
+pub struct TomlFile {
+ pub module_path: Vec<String>,
+ pub struct_name: String,
+ pub entries: Vec<TranslationEntry>,
+ pub all_languages: BTreeSet<String>,
+}
+
+/// Convert a key to a valid Rust identifier
+pub fn key_to_ident(key: &str) -> String {
+ let snake = just_fmt::snake_case!(key);
+ if snake.starts_with(|c: char| c.is_ascii_digit()) {
+ format!("a{}", snake)
+ } else if syn::parse_str::<Ident>(&snake).is_ok() {
+ snake
+ } else {
+ format!("a_{}", snake)
+ }
+}
+
+/// Generate a struct name (PascalCase) from a filename (without extension)
+pub fn filename_to_struct_name(filename: &str) -> String {
+ just_fmt::pascal_case!(filename)
+}
+
+/// Generate a module name (snake_case) from a path
+pub fn path_to_mod_name(filename: &str) -> String {
+ just_fmt::snake_case!(filename)
+}
+
+/// Convert a language key (e.g. `"en"`, `"zh_CN"`, `"en-US"`) to a valid enum variant name
+/// Rules: `-` → `_`, preserve case, prepend `_` if starts with a digit
+pub fn lang_to_variant(lang: &str) -> String {
+ let raw = lang.replace('-', "_");
+ if raw.starts_with(|c: char| c.is_ascii_digit()) {
+ format!("_{}", raw)
+ } else {
+ raw
+ }
+}
+
+/// Extract `%{param}` parameters from a string
+pub fn extract_params(s: &str) -> Vec<String> {
+ let mut params = Vec::new();
+ let mut chars = s.chars().peekable();
+ while let Some(c) = chars.next() {
+ if c == '%' && chars.peek() == Some(&'{') {
+ chars.next();
+ let mut param = String::new();
+ while let Some(&next) = chars.peek() {
+ if next == '}' {
+ chars.next();
+ break;
+ }
+ param.push(next);
+ chars.next();
+ }
+ if !param.is_empty() && !params.contains(&param) {
+ params.push(param);
+ }
+ }
+ }
+ params
+}
+
+/// Replace `%{param}` with `{}`, preserving occurrence order for `format!`
+pub fn replace_params_with_format(s: &str) -> String {
+ let mut result = String::new();
+ let mut chars = s.chars().peekable();
+ while let Some(c) = chars.next() {
+ if c == '%' && chars.peek() == Some(&'{') {
+ chars.next();
+ while let Some(&next) = chars.peek() {
+ if next == '}' {
+ chars.next();
+ break;
+ }
+ chars.next();
+ }
+ result.push_str("{}");
+ } else {
+ result.push(c);
+ }
+ }
+ result
+}
+
+/// Recursively scan a directory to collect all `.toml` files with their module paths
+pub fn scan_toml_files(dir: &Path) -> Vec<(Vec<String>, PathBuf)> {
+ let mut files = Vec::new();
+
+ if !dir.exists() {
+ return files;
+ }
+
+ if let Ok(entries) = fs::read_dir(dir) {
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if path.is_dir() {
+ let sub_files = scan_toml_files(&path);
+ let dir_name = path
+ .file_stem()
+ .unwrap_or_default()
+ .to_string_lossy()
+ .to_string();
+ for (mut mod_path, file_path) in sub_files {
+ mod_path.insert(0, dir_name.clone());
+ files.push((mod_path, file_path));
+ }
+ } else if path.extension().is_some_and(|ext| ext == "toml") {
+ files.push((vec![], path));
+ }
+ }
+ }
+
+ files
+}
+
+/// Parse a toml file
+pub fn parse_toml_file(path: &Path) -> Option<TomlFile> {
+ let content = fs::read_to_string(path).ok()?;
+ let value: toml::Value = content.parse().ok()?;
+
+ let table = value.as_table()?;
+
+ let mut raw_entries: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
+ let mut all_languages: BTreeSet<String> = BTreeSet::new();
+ let mut all_keys: BTreeSet<String> = BTreeSet::new();
+
+ for (lang_key, lang_val) in table {
+ all_languages.insert(lang_key.clone());
+ if let Some(lang_table) = lang_val.as_table() {
+ for (entry_key, entry_val) in lang_table {
+ all_keys.insert(entry_key.clone());
+ if let Some(s) = entry_val.as_str() {
+ raw_entries
+ .entry(entry_key.clone())
+ .or_default()
+ .insert(lang_key.clone(), s.to_string());
+ }
+ }
+ }
+ }
+
+ let mut entries = Vec::new();
+ for key in &all_keys {
+ let values = raw_entries.get(key).cloned().unwrap_or_default();
+
+ // Collect parameter list for each language (in occurrence order)
+ let lang_params: Vec<Vec<String>> = values.values().map(|v| extract_params(v)).collect();
+
+ // Convert to parameter name sets for comparison (names only, not order)
+ let param_sets: Vec<BTreeSet<String>> = lang_params
+ .iter()
+ .map(|p| p.iter().cloned().collect())
+ .collect();
+
+ // Conflict: inconsistent parameter name sets across languages (count or names differ)
+ let params_conflict = if param_sets.is_empty() {
+ false
+ } else {
+ let first = &param_sets[0];
+ !param_sets.iter().skip(1).all(|p| p == first)
+ };
+
+ // Take parameter order from the first language that has parameters as canonical; empty params on conflict
+ let (has_params, params) = if params_conflict {
+ (false, vec![])
+ } else {
+ let canonical = values
+ .values()
+ .find_map(|v| {
+ let p = extract_params(v);
+ if !p.is_empty() { Some(p) } else { None }
+ })
+ .unwrap_or_default();
+ (!canonical.is_empty(), canonical)
+ };
+
+ entries.push(TranslationEntry {
+ key: key.clone(),
+ values,
+ has_params,
+ params,
+ params_conflict,
+ });
+ }
+
+ let filename = path.file_stem()?.to_string_lossy().to_string();
+ let struct_name = filename_to_struct_name(&filename);
+
+ Some(TomlFile {
+ module_path: vec![],
+ struct_name,
+ entries,
+ all_languages,
+ })
+}
diff --git a/shakehand/src/lib.rs b/shakehand/src/lib.rs
new file mode 100644
index 0000000..419e088
--- /dev/null
+++ b/shakehand/src/lib.rs
@@ -0,0 +1,145 @@
+//! "Shake Hand!"
+//!
+//! > Let different languages shake hands with each other! 🤝
+//!
+//! This is a **purely compile-time** Rust internationalization library. **All** localized strings are fully embedded into the binary at compile time, with only minimal runtime overhead.
+//!
+//! # How to Use?
+//!
+//! ## 1. Add Dependency
+//!
+//! Add the following to your `Cargo.toml`:
+//!
+//! ```toml
+//! shakehand = "0.1"
+//! ```
+//!
+//! ## 2. Write Configuration Files
+//!
+//! Create a directory under your project to serve as the root for translations, e.g. `./locale/`.
+//! Create any `toml` file inside this directory, e.g. `./locale/global.toml`, representing a translation file.
+//!
+//! In the file, group translations by language section. The key is the translation key, and the value is the translated text.
+//! Text with parameters uses `%{parameter_name}` as placeholders, where the parameter name directly maps to the generated function's parameter name:
+//!
+//! ```toml
+//! [en]
+//! world = "world"
+//! greeting = "Hello, %{someone}!"
+//!
+//! [zh_CN]
+//! world = "世界"
+//! greeting = "你好,%{someone}!"
+//! ```
+//!
+//! ## 3. Load Translations
+//!
+//! In your Rust code, use `shakehand::locale!` to hardcode the entire directory into a module:
+//!
+//! ```rust
+//! pub mod translation {
+//! shakehand::locale!("./test-locale", fallback = "en");
+//! }
+//! ```
+//!
+//! The generated module will contain:
+//! - A `Languages` enum listing all languages
+//! - A `set_lang` function for switching the current language
+//! - A unit struct `Global` (named after `global.toml`), whose associated functions are the translations for each key
+//!
+//! ## 4. Call Translations
+//!
+//! Call translations just like ordinary functions, passing parameters by placeholder name:
+//!
+//! ```rust
+//! use crate::translation::{Global, Languages, set_lang};
+//!
+//! fn main() {
+//! set_lang(Languages::en);
+//! let greeting = Global::greeting("World");
+//! println!("{}", greeting); // Hello, World!
+//!
+//! set_lang(Languages::zh_CN);
+//! let greeting = Global::greeting("世界");
+//! println!("{}", greeting); // 你好,世界!
+//! }
+//!
+//! # pub mod translation {
+//! # shakehand::locale!("./test-locale", fallback = "en");
+//! # }
+//! ```
+//!
+//! You can also pass the return value of another translation as a parameter, since each parameterless translation function returns a `&'static str`, completely allocation-free:
+//!
+//! ```rust
+//! # use shakehand::locale;
+//! # use a::Global;
+//! # pub mod a { shakehand::locale!("./test-locale"); };
+//! # a::set_lang(a::Languages::en);
+//! let greeting = Global::greeting(Global::world());
+//! ```
+//!
+//! # Contributing
+//!
+//! Directly open a PR to the [repository](https://github.com/catilgrass/shakehand) and mention [@Weicao-CatilGrass](https://github.com/Weicao-CatilGrass).
+//!
+//! # License
+//!
+//! MIT or Apache 2.0
+
+use std::path::Path;
+
+use proc_macro::TokenStream;
+use syn::parse_macro_input;
+
+mod analyzer;
+mod shakehand;
+
+/// `locale!` macro: Generate an i18n module from toml files at compile time
+///
+/// # Usage
+///
+/// ```
+/// pub mod my_i18n {
+/// shakehand::locale!("./test-locale/", fallback = "en");
+/// }
+/// ```
+///
+/// # Parameters
+///
+/// - `path` - i18n directory path (relative to `Cargo.toml`)
+/// - `fallback` - optional, default language (defaults to `"en"`)
+#[proc_macro]
+pub fn locale(input: TokenStream) -> TokenStream {
+ let input = parse_macro_input!(input as analyzer::ShakehandInput);
+
+ let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
+
+ let base_path = Path::new(&manifest_dir).join(&input.path);
+ let base_path = just_fmt::fmt_path::fmt_path(&base_path).unwrap_or_else(|_| base_path.clone());
+
+ let scanned_files = analyzer::scan_toml_files(&base_path);
+
+ let mut parsed_files = Vec::new();
+ let mut all_languages: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
+
+ for (mod_path, file_path) in &scanned_files {
+ if let Some(mut toml_file) = analyzer::parse_toml_file(file_path) {
+ toml_file.module_path = mod_path.clone();
+ all_languages.extend(toml_file.all_languages.clone());
+ parsed_files.push(toml_file);
+ }
+ }
+
+ if parsed_files.is_empty() {
+ let lang_enum =
+ shakehand::generate_module(parsed_files, all_languages, input.fallback, &input.path);
+ return TokenStream::from(quote::quote! {
+ #lang_enum
+ });
+ }
+
+ let generated =
+ shakehand::generate_module(parsed_files, all_languages, input.fallback, &input.path);
+ TokenStream::from(generated)
+}
diff --git a/shakehand/src/shakehand.rs b/shakehand/src/shakehand.rs
new file mode 100644
index 0000000..3e73b09
--- /dev/null
+++ b/shakehand/src/shakehand.rs
@@ -0,0 +1,425 @@
+use proc_macro2::{Ident, TokenStream as TokenStream2};
+use quote::{format_ident, quote};
+use std::collections::{BTreeMap, BTreeSet};
+
+use crate::analyzer::{
+ TomlFile, TranslationEntry, extract_params, key_to_ident, lang_to_variant, path_to_mod_name,
+ replace_params_with_format,
+};
+
+/// Generate the language enum (and functions `lang()` / `set_lang()`)
+fn generate_languages_enum(
+ all_languages: &BTreeSet<String>,
+ fallback: &str,
+ locale_path: &str,
+) -> TokenStream2 {
+ let variants_info: Vec<(Ident, String)> = all_languages
+ .iter()
+ .map(|lang| {
+ let name = lang_to_variant(lang);
+ (format_ident!("{}", name), lang.clone())
+ })
+ .collect();
+
+ let enum_doc = format!("All language files present under \"{}\"", locale_path);
+
+ if variants_info.is_empty() {
+ return quote! {
+ /// This constant stores the discriminant of the current language variant.
+ /// It is initialized at program start by reading the locale or a config file.
+ pub static __SHAKE_HAND_LANG: std::sync::atomic::AtomicU8 =
+ std::sync::atomic::AtomicU8::new(0u8);
+
+ #[derive(Debug, Default, Clone, Copy)]
+ #[repr(u8)]
+ #[doc = #enum_doc]
+ pub enum Languages {}
+
+ #[inline(always)]
+ /// Get the current language from the global static variable
+ pub fn lang() -> Languages {
+ panic!("shakehand: no locale files found")
+ }
+
+ #[inline(always)]
+ /// Set the current language in the global static variable
+ pub fn set_lang(_lang: Languages) {
+ panic!("shakehand: no locale files found")
+ }
+ };
+ }
+
+ let fallback_idx = all_languages
+ .iter()
+ .position(|l| l == fallback)
+ .unwrap_or(0);
+
+ let fallback_ident = &variants_info[fallback_idx].0;
+
+ // List of enum variants with doc comments, fallback variant gets #[default]
+ let enum_variants: Vec<TokenStream2> = variants_info
+ .iter()
+ .enumerate()
+ .map(|(i, (ident, raw))| {
+ if i == fallback_idx {
+ quote! {
+ #[doc = #raw]
+ #[default]
+ #ident,
+ }
+ } else {
+ quote! {
+ #[doc = #raw]
+ #ident,
+ }
+ }
+ })
+ .collect();
+
+ // lang() match arms (match u8 values as returned by AtomicU8::load)
+
+ let lang_match_arms: Vec<TokenStream2> = variants_info
+ .iter()
+ .enumerate()
+ .map(|(i, (ident, _))| {
+ let idx = i as u8;
+ quote! { #idx => Languages::#ident, }
+ })
+ .collect();
+
+ quote! {
+ /// This constant stores the discriminant of the current language variant.
+ /// It is initialized at program start by reading the locale or a config file.
+ pub static __SHAKE_HAND_LANG: std::sync::atomic::AtomicU8 =
+ std::sync::atomic::AtomicU8::new(#fallback_idx as u8);
+
+ #[derive(Debug, Default, Clone, Copy)]
+ #[repr(u8)]
+ #[allow(non_camel_case_types)]
+ #[doc = #enum_doc]
+ pub enum Languages {
+ #(#enum_variants)*
+ }
+
+ /// Get the current language from the global static variable
+ #[inline(always)]
+ pub fn lang() -> Languages {
+ match __SHAKE_HAND_LANG.load(std::sync::atomic::Ordering::Relaxed) {
+ #(#lang_match_arms)*
+ _ => Languages::#fallback_ident,
+ }
+ }
+
+ /// Set the current language in the global static variable
+ #[inline(always)]
+ pub fn set_lang(lang: Languages) {
+ __SHAKE_HAND_LANG.store(lang as u8, std::sync::atomic::Ordering::Relaxed);
+ }
+ }
+}
+
+/// Generate a `format!(fmt_str, args…)` expression for a value that has parameters
+fn make_format_expr(value: &str) -> TokenStream2 {
+ let fmt_str = replace_params_with_format(value);
+ let lang_params = extract_params(value);
+ let format_args: Vec<TokenStream2> = lang_params
+ .iter()
+ .map(|p| {
+ let var = format_ident!("{}", just_fmt::snake_case!(p));
+ // 取出 .as_ref() 后的变量值
+ quote! { #var }
+ })
+ .collect();
+ quote! { format!(#fmt_str, #(#format_args),*) }
+}
+
+/// Generate match arms for a single entry (arms for languages with values) and a `_ =>` catch-all (fallback)
+fn make_match_arms(
+ entry: &TranslationEntry,
+ all_available: &BTreeSet<String>,
+ fallback: &str,
+) -> (Vec<TokenStream2>, TokenStream2) {
+ let mut arms: Vec<TokenStream2> = Vec::new();
+ let mut found_fallback = false;
+
+ let mut fallback_arm = if entry.has_params {
+ quote! { _ => ::std::string::String::new(), }
+ } else {
+ quote! { _ => "", }
+ };
+
+ for lang in all_available {
+ let value = entry.values.get(lang.as_str());
+ let variant_name = format_ident!("{}", lang_to_variant(lang));
+ let is_fallback = lang == fallback;
+
+ match value {
+ Some(v) if entry.has_params => {
+ let body = make_format_expr(v);
+ let arm = quote! { Languages::#variant_name => #body, };
+ if is_fallback {
+ found_fallback = true;
+ fallback_arm = quote! { _ => #body, };
+ }
+ arms.push(arm);
+ }
+ Some(v) => {
+ let arm = quote! { Languages::#variant_name => #v, };
+ if is_fallback {
+ found_fallback = true;
+ fallback_arm = quote! { _ => #v, };
+ }
+ arms.push(arm);
+ }
+ None => {}
+ }
+ }
+
+ // When the fallback language doesn't have a value for this key, use the first available language as a catch-all
+ if !found_fallback && let Some(first_val) = entry.values.values().next() {
+ if entry.has_params {
+ let body = make_format_expr(first_val);
+ fallback_arm = quote! { _ => #body, };
+ } else {
+ fallback_arm = quote! { _ => #first_val, };
+ }
+ }
+
+ (arms, fallback_arm)
+}
+
+/// Generate a method for a single translation entry
+fn generate_entry_method(
+ entry: &TranslationEntry,
+ all_languages: &BTreeSet<String>,
+ fallback: &str,
+) -> TokenStream2 {
+ let method_name = format_ident!("{}", key_to_ident(&entry.key));
+ let key_str = format!("Key \"{}\"", entry.key);
+
+ // Doc table showing each language's value for this key
+ let mut lang_rows: Vec<TokenStream2> = Vec::new();
+ // Table header
+ lang_rows.push(quote! { #[doc = "|Language|Value|"] });
+ lang_rows.push(quote! { #[doc = "|-|-|"] });
+ for lang in all_languages.iter() {
+ let val = entry
+ .values
+ .get(lang.as_str())
+ .map(|s| s.as_str())
+ .unwrap_or("(NO TRANSLATION)");
+ let row = format!("|**{}**|*\"{}\"*|", lang, val);
+ lang_rows.push(quote! { #[doc = #row] });
+ }
+ let lang_docs = lang_rows;
+
+ // Parameter name conflict: compile error + deprecated function
+ if entry.params_conflict {
+ let err_msg = format!(
+ "shakehand: key `{}` has inconsistent parameter names across languages",
+ entry.key,
+ );
+ let panic_msg = format!(
+ "shakehand: key `{}` has inconsistent parameter names across languages, fix the .toml file",
+ entry.key,
+ );
+ return quote! {
+ ::core::compile_error!(#err_msg);
+
+ #[deprecated(note = "parameter mismatch across languages, fix the .toml file")]
+ #[doc = #key_str]
+ ///
+ #(#lang_docs)*
+ #[must_use]
+ pub fn #method_name () -> ! {
+ panic!(#panic_msg)
+ }
+ };
+ }
+
+ // Only generate match arms for languages that have a translation; missing ones fall through to `_ =>`
+ let (match_arms, catch_all) =
+ make_match_arms(entry, &entry.values.keys().cloned().collect(), fallback);
+
+ if entry.has_params {
+ let params_with_type: Vec<TokenStream2> = entry
+ .params
+ .iter()
+ .map(|p| {
+ let name = format_ident!("{}", just_fmt::snake_case!(p));
+ quote! { #name: impl AsRef<str> }
+ })
+ .collect();
+
+ let param_bindings: Vec<TokenStream2> = entry
+ .params
+ .iter()
+ .map(|p| {
+ let name = format_ident!("{}", just_fmt::snake_case!(p));
+ quote! { let #name = #name.as_ref(); }
+ })
+ .collect();
+
+ let param_docs: Vec<TokenStream2> = entry
+ .params
+ .iter()
+ .map(|p| {
+ let doc = format!("- `{}`", p);
+ quote! { #[doc = #doc] }
+ })
+ .collect();
+
+ quote! {
+ #[inline(always)]
+ #[doc = #key_str]
+ ///
+ #(#lang_docs)*
+ ///
+ /// # Parameters
+ #(#param_docs)*
+ #[must_use]
+ pub fn #method_name (#(#params_with_type),*) -> String {
+ #(#param_bindings)*
+ match lang() {
+ #(#match_arms)*
+ #catch_all
+ }
+ }
+ }
+ } else {
+ quote! {
+ #[inline(always)]
+ #[doc = #key_str]
+ ///
+ #(#lang_docs)*
+ #[must_use]
+ pub fn #method_name () -> &'static str {
+ match lang() {
+ #(#match_arms)*
+ #catch_all
+ }
+ }
+ }
+ }
+}
+
+/// Generate a struct and its impl block for a single toml file
+fn generate_struct(
+ toml_file: &TomlFile,
+ all_languages: &BTreeSet<String>,
+ locale_path: &str,
+ fallback: &str,
+) -> TokenStream2 {
+ let struct_name = format_ident!("{}", toml_file.struct_name);
+ let methods: Vec<TokenStream2> = toml_file
+ .entries
+ .iter()
+ .map(|entry| generate_entry_method(entry, all_languages, fallback))
+ .collect();
+
+ let struct_name_str = toml_file.struct_name.as_str();
+
+ // Count how many keys each language has, for the table
+ let mut lang_counts: Vec<(String, usize)> = all_languages
+ .iter()
+ .map(|lang| {
+ let count = toml_file
+ .entries
+ .iter()
+ .filter(|e| e.values.contains_key(lang.as_str()))
+ .count();
+ (lang.clone(), count)
+ })
+ .collect();
+ lang_counts.sort_by(|a, b| a.1.cmp(&b.1).reverse());
+
+ // Table rows
+ let mut count_rows: Vec<TokenStream2> = Vec::new();
+ count_rows.push(quote! { #[doc = "|Language|Count|"] });
+ count_rows.push(quote! { #[doc = "|-|-|"] });
+ for (lang, count) in &lang_counts {
+ let row = format!("|**{}**|{}|", lang, count);
+ count_rows.push(quote! { #[doc = #row] });
+ }
+
+ let path_doc = format!(
+ "Language information from file `{}/{}.toml`",
+ locale_path, struct_name_str
+ );
+
+ quote! {
+ #[doc = concat!("# ", #struct_name_str)]
+ ///
+ #[doc = #path_doc]
+ ///
+ #(#count_rows)*
+ pub struct #struct_name;
+
+ impl #struct_name {
+ #(#methods)*
+ }
+ }
+}
+
+/// Generate the complete module code
+pub fn generate_module(
+ files: Vec<TomlFile>,
+ all_languages: BTreeSet<String>,
+ fallback: String,
+ locale_path: &str,
+) -> TokenStream2 {
+ let lang_enum = generate_languages_enum(&all_languages, &fallback, locale_path);
+
+ // Group by module path
+ let mut root_files: Vec<&TomlFile> = Vec::new();
+ let mut sub_modules: BTreeMap<String, Vec<&TomlFile>> = BTreeMap::new();
+
+ for f in &files {
+ if f.module_path.is_empty() {
+ root_files.push(f);
+ } else {
+ let mod_name = f.module_path[0].clone();
+ sub_modules.entry(mod_name).or_default().push(f);
+ }
+ }
+
+ // Generate root-level structs
+ let root_structs: Vec<TokenStream2> = root_files
+ .iter()
+ .map(|f| generate_struct(f, &all_languages, locale_path, &fallback))
+ .collect();
+
+ // Generate sub-modules
+ let sub_mods: Vec<TokenStream2> = sub_modules
+ .iter()
+ .map(|(mod_name, mod_files): (&String, &Vec<&TomlFile>)| {
+ let mod_ident = format_ident!("{}", path_to_mod_name(mod_name));
+ let sub_structs: Vec<TokenStream2> = mod_files
+ .iter()
+ .map(|f| {
+ let fixed_file = TomlFile {
+ module_path: f.module_path[1..].to_vec(),
+ struct_name: f.struct_name.clone(),
+ entries: f.entries.clone(),
+ all_languages: f.all_languages.clone(),
+ };
+ generate_struct(&fixed_file, &all_languages, locale_path, &fallback)
+ })
+ .collect();
+
+ quote! {
+ pub mod #mod_ident {
+ #(#sub_structs)*
+ }
+ }
+ })
+ .collect();
+
+ quote! {
+ #lang_enum
+
+ #(#root_structs)*
+
+ #(#sub_mods)*
+ }
+}
diff --git a/shakehand/test-locale/global.toml b/shakehand/test-locale/global.toml
new file mode 100644
index 0000000..0fde1bd
--- /dev/null
+++ b/shakehand/test-locale/global.toml
@@ -0,0 +1,7 @@
+[en]
+world = "world"
+greeting = "Hello, %{someone}!"
+
+[zh_CN]
+world = "世界"
+gretting = "你好,%{someone}!"