Skip to main content

actix_cloud_codegen/
lib.rs

1//! Procedural macros for [`actix-cloud`](https://crates.io/crates/actix-cloud).
2//!
3//! - [`main`]: attribute for the `main` function that runs it on the Actix Web runtime
4//!   through `actix_cloud`'s re-exported `actix_web`.
5//! - `i18n` (feature `i18n`): load locale files at compile time.
6
7#![cfg_attr(docsrs, feature(doc_cfg))]
8
9use proc_macro::TokenStream;
10use quote::quote;
11#[cfg(feature = "i18n")]
12use std::{collections::BTreeMap, env, path};
13
14#[cfg(feature = "i18n")]
15mod i18n;
16
17/// Attribute for the `main` function, equivalent to
18/// `#[actix_web::rt::main(system = "actix_cloud::actix_web::rt::System")]`.
19///
20/// The runtime is taken from `actix_cloud`'s `actix_web` re-export, so the crate using
21/// this macro does not need a direct `actix-web` dependency.
22///
23/// ```ignore
24/// #[actix_cloud::main]
25/// async fn main() -> std::io::Result<()> {
26///     Ok(())
27/// }
28/// ```
29#[proc_macro_attribute]
30pub fn main(_: TokenStream, item: TokenStream) -> TokenStream {
31    main_impl(item.into()).into()
32}
33
34/// Implementation of [`main`], kept on `proc_macro2` types so it can be unit tested
35/// (`proc_macro::TokenStream` cannot be constructed outside a real macro expansion).
36fn main_impl(item: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
37    quote! {
38        #[actix_cloud::actix_web::rt::main(system = "actix_cloud::actix_web::rt::System")]
39        #item
40    }
41}
42
43#[cfg(feature = "i18n")]
44/// Init I18n translations.
45///
46/// Loads every `**/*.yml` file under `locales_path` at compile time and expands to an
47/// `actix_cloud::map!` table with flat `"locale.key"` entries, which is what
48/// `actix_cloud::i18n::Locale::add_locale` expects.
49///
50/// The path is resolved relative to the package's `CARGO_MANIFEST_DIR`.
51///
52/// ```ignore
53/// i18n!("locales");
54/// ```
55///
56/// # Panics
57///
58/// Panics if `CARGO_MANIFEST_DIR` is not set or not valid unicode, or if the locale
59/// files cannot be loaded.
60#[proc_macro]
61pub fn i18n(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
62    let option = match syn::parse::<i18n::Option>(input) {
63        Ok(input) => input,
64        Err(err) => return err.to_compile_error().into(),
65    };
66
67    // CARGO_MANIFEST_DIR is current build directory
68    let cargo_dir =
69        env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is not set or not valid unicode");
70    let locales_path = path::PathBuf::from(cargo_dir).join(option.locales_path);
71
72    let translation = load_translations(&locales_path);
73    let code = i18n::generate_code(&translation);
74
75    if rust_i18n_support::is_debug() {
76        println!("{code}");
77    }
78
79    code.into()
80}
81
82/// Load the locale files under `locales_path` and flatten them into `"locale.key"`
83/// entries, the format used by the runtime translation table.
84#[cfg(feature = "i18n")]
85fn load_translations(locales_path: &path::Path) -> BTreeMap<String, String> {
86    let data = rust_i18n_support::load_locales(&locales_path.display().to_string(), |_| false);
87    let mut translation = BTreeMap::new();
88    for (lang, mp) in data {
89        for (k, v) in mp {
90            translation.insert(format!("{lang}.{k}"), v);
91        }
92    }
93    translation
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn main_expands_to_actix_web_rt_attribute() {
102        let item = quote! {
103            async fn main() -> std::io::Result<()> {
104                Ok(())
105            }
106        };
107        let expected = quote! {
108            #[actix_cloud::actix_web::rt::main(system = "actix_cloud::actix_web::rt::System")]
109            async fn main() -> std::io::Result<()> {
110                Ok(())
111            }
112        };
113
114        assert_eq!(main_impl(item).to_string(), expected.to_string());
115    }
116
117    #[cfg(feature = "i18n")]
118    #[test]
119    fn loads_and_flattens_locales() {
120        let path = path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/locales");
121        let translations = load_translations(&path);
122
123        assert_eq!(
124            translations.get("en-US.hello").map(String::as_str),
125            Some("Hello")
126        );
127        assert_eq!(
128            translations.get("en-US.messages.greet").map(String::as_str),
129            Some("Hello, %{name}!")
130        );
131        assert_eq!(
132            translations.get("zh-CN.hello").map(String::as_str),
133            Some("你好")
134        );
135    }
136}