summaryrefslogtreecommitdiff
path: root/mingling_macros/src/lib.rs
blob: 13d5ddc0bc29e90171947b8aee578362b6afc3d1 (plain) (blame)
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
//! Mingling Macros Crate
//!
//! This crate provides procedural macros for the Mingling framework.
//! Macros are implemented in separate modules and re-exported here.

use proc_macro::TokenStream;
use proc_macro2::Ident;
use quote::quote;
use syn::parse_macro_input;

mod chain;
mod chain_struct;
mod dispatcher_chain;
mod node;
mod render;
mod renderer;

use once_cell::sync::Lazy;
use std::sync::Mutex;

// Global variable declarations for storing chain and renderer mappings
pub(crate) static CHAINS: Lazy<Mutex<Vec<String>>> = Lazy::new(|| Mutex::new(Vec::new()));
pub(crate) static RENDERERS: Lazy<Mutex<Vec<String>>> = Lazy::new(|| Mutex::new(Vec::new()));
pub(crate) static CHAINS_EXIST: Lazy<Mutex<Vec<String>>> = Lazy::new(|| Mutex::new(Vec::new()));
pub(crate) static RENDERERS_EXIST: Lazy<Mutex<Vec<String>>> = Lazy::new(|| Mutex::new(Vec::new()));

/// Creates a command node from a dot-separated path string.
/// The path components are automatically converted to kebab-case.
///
/// # Examples
///
/// ```ignore
/// use mingling_macros::node;
///
/// // Creates a node representing "subcommand.action"
/// // The components will be converted to kebab-case
/// let node = node!("subcommand.action");
/// ```
#[proc_macro]
pub fn node(input: TokenStream) -> TokenStream {
    node::node(input)
}

/// Macro for creating wrapper types with automatic trait implementations.
///
/// This macro creates a new struct that wraps an inner type and automatically
/// implements common traits:
/// - `From<InnerType>` and `Into<InnerType>`
/// - `new()` constructor
/// - `Default` (if inner type implements Default)
/// - `AsRef<InnerType>` and `AsMut<InnerType>`
/// - `Deref` and `DerefMut` to inner type
/// - `Into<mingling::AnyOutput>` and `Into<mingling::ChainProcess>`
/// - Helper methods `to_chain()` and `to_render()` for chaining operations
///
/// When the `serde` feature is enabled, the struct also derives `serde::Serialize`.
///
/// # Examples
///
/// ```ignore
/// use mingling_macros::chain_struct;
///
/// // Creates a wrapper type around String
/// chain_struct!(NameString = String);
///
/// // Usage:
/// let name = NameString::new("Hello".to_string());
/// let inner: String = name.into(); // Into conversion
/// let name2 = NameString::from("World".to_string()); // From conversion
/// let ref_str: &String = name2.as_ref(); // AsRef
/// let chain_process = name2.to_chain(); // Convert to ChainProcess
/// ```
#[proc_macro]
pub fn chain_struct(input: TokenStream) -> TokenStream {
    chain_struct::chain_struct(input)
}

/// Creates a dispatcher chain for command execution.
///
/// This macro generates a dispatcher struct that implements the `Dispatcher` trait
/// for command chain execution. It creates a dispatcher that begins a chain process
/// with the given command name and arguments.
///
/// # Syntax
///
/// `dispatcher!("command_name", CommandStruct => ChainStruct)`
///
/// - `command_name`: A string literal representing the command name
/// - `CommandStruct`: The name of the dispatcher struct to generate
/// - `ChainStruct`: The name of the chain wrapper struct to generate
///
/// # Examples
///
/// ```ignore
/// use mingling_macros::dispatcher;
///
/// // Creates a dispatcher for the "init" command
/// dispatcher!("init", InitDispatcher => InitChain);
///
/// // This generates:
/// // - A dispatcher struct `InitDispatcher` that implements `Dispatcher`
/// // - A chain wrapper struct `InitChain` wrapping `Vec<String>`
/// // - The dispatcher will create a chain process when invoked
/// ```
#[proc_macro]
pub fn dispatcher(input: TokenStream) -> TokenStream {
    dispatcher_chain::dispatcher_chain(input)
}

/// Creates a dispatcher for rendering operations.
///
/// This macro generates a dispatcher struct that implements the `Dispatcher` trait
/// for rendering operations. It creates a dispatcher that begins a render process
/// with the given command name and arguments.
///
/// # Syntax
///
/// `dispatcher_render!("command_name", CommandStruct => ChainStruct)`
///
/// - `command_name`: A string literal representing the command name
/// - `CommandStruct`: The name of the dispatcher struct to generate
/// - `ChainStruct`: The name of the chain wrapper struct to generate
///
/// # Examples
///
/// ```ignore
/// use mingling_macros::dispatcher_render;
///
/// // Creates a render dispatcher for the "show" command
/// dispatcher_render!("show", ShowDispatcher => ShowChain);
///
/// // This generates:
/// // - A dispatcher struct `ShowDispatcher` that implements `Dispatcher`
/// // - A chain wrapper struct `ShowChain` wrapping `Vec<String>`
/// // - The dispatcher will create a render process when invoked
/// ```
#[proc_macro]
pub fn dispatcher_render(input: TokenStream) -> TokenStream {
    dispatcher_chain::dispatcher_render(input)
}

/// Macro for printing to a RenderResult without newline.
///
/// This macro expands to a call to `RenderResult::print` with formatted arguments.
/// It expects a mutable reference to a `RenderResult` named `r` to be in scope.
///
/// # Examples
///
/// ```ignore
/// use mingling_macros::r_print;
///
/// let mut r = RenderResult::default();
/// r_print!("Hello, {}!", "world");
/// ```
#[proc_macro]
pub fn r_print(input: TokenStream) -> TokenStream {
    render::r_print(input)
}

/// Macro for printing to a RenderResult with newline.
///
/// This macro expands to a call to `RenderResult::println` with formatted arguments.
/// It expects a mutable reference to a `RenderResult` named `r` to be in scope.
///
/// # Examples
///
/// ```ignore
/// use mingling_macros::r_println;
///
/// let mut r = RenderResult::default();
/// r_println!("Hello, {}!", "world");
/// ```
#[proc_macro]
pub fn r_println(input: TokenStream) -> TokenStream {
    render::r_println(input)
}

/// Attribute macro for automatically generating structs that implement the `Chain` trait.
///
/// This macro transforms an async function into a struct that implements
/// the `Chain` trait. The struct name is automatically generated from the function name
/// by converting it to PascalCase.
///
/// # Examples
///
/// ```ignore
/// use mingling_macros::chain;
///
/// #[chain]
/// pub async fn init_entry(_: InitBegin) -> mingling::ChainProcess {
///     AnyOutput::new::<InitResult>("Init!".to_string().into()).route_chain()
/// }
/// ```
///
/// This generates:
/// ```ignore
/// pub struct InitEntry;
/// impl Chain for InitEntry {
///     type Previous = InitBegin;
///     async fn proc(_: Self::Previous) -> mingling::ChainProcess {
///         AnyOutput::new::<InitResult>("Init!".to_string().into()).route_chain()
///     }
/// }
/// ```
#[proc_macro_attribute]
pub fn chain(_attr: TokenStream, item: TokenStream) -> TokenStream {
    chain::chain_attr(item)
}

/// Attribute macro for automatically generating structs that implement the `Renderer` trait.
///
/// This macro transforms a function into a struct that implements
/// the `Renderer` trait. The struct name is automatically generated from the function name
/// by converting it to PascalCase.
///
/// # Examples
///
/// ```ignore
/// use mingling_macros::renderer;
///
/// #[renderer]
/// fn init_result_render(p: InitResult) {
///     let str: String = p.into();
///     r_println!("{}", str);
/// }
/// ```
///
/// This generates:
/// ```ignore
/// pub struct InitResultRender;
/// impl Renderer for InitResultRender {
///     type Previous = InitResult;
///
///     fn render(p: Self::Previous, r: &mut RenderResult) {
///         let str: String = p.into();
///         r_println!("{}", str);
///     }
/// }
/// ```
#[proc_macro_attribute]
pub fn renderer(_attr: TokenStream, item: TokenStream) -> TokenStream {
    renderer::renderer_attr(item)
}

/// Macro for creating a program structure that collects all chains and renderers.
///
/// This macro creates a struct that implements the `ProgramCollect` trait,
/// which collects all chains and renderers registered with `#[chain]` and `#[renderer]`
/// attribute macros. The program can then be used to execute the command chain.
///
/// # Examples
///
/// ```ignore
/// use mingling_macros::program;
///
/// program!(MyProgram);
///
/// // This generates:
/// pub struct MyProgram;
/// impl mingling::ProgramCollect for MyProgram {
///     mingling::__dispatch_program_renderers!(...);
///     mingling::__dispatch_program_chains!(...);
///     fn has_renderer(any: &mingling::AnyOutput) -> bool { ... }
///     fn has_chain(any: &mingling::AnyOutput) -> bool { ... }
/// }
/// impl MyProgram {
///     pub fn new() -> mingling::Program<MyProgram> {
///         mingling::Program::new()
///     }
/// }
/// ```
#[proc_macro]
pub fn program(input: TokenStream) -> TokenStream {
    let name = parse_macro_input!(input as Ident);

    let renderers = RENDERERS.lock().unwrap().clone();
    let chains = CHAINS.lock().unwrap().clone();
    let renderer_exist = RENDERERS_EXIST.lock().unwrap().clone();
    let chain_exist = CHAINS_EXIST.lock().unwrap().clone();

    let renderer_tokens: Vec<proc_macro2::TokenStream> = renderers
        .iter()
        .map(|s| syn::parse_str::<proc_macro2::TokenStream>(s).unwrap())
        .collect();

    let chain_tokens: Vec<proc_macro2::TokenStream> = chains
        .iter()
        .map(|s| syn::parse_str::<proc_macro2::TokenStream>(s).unwrap())
        .collect();

    let renderer_exist_tokens: Vec<proc_macro2::TokenStream> = renderer_exist
        .iter()
        .map(|s| syn::parse_str::<proc_macro2::TokenStream>(s).unwrap())
        .collect();

    let chain_exist_tokens: Vec<proc_macro2::TokenStream> = chain_exist
        .iter()
        .map(|s| syn::parse_str::<proc_macro2::TokenStream>(s).unwrap())
        .collect();

    let expanded = quote! {
        pub struct #name;

        impl ::mingling::ProgramCollect for #name {
            ::mingling::__dispatch_program_renderers!(
                #(#renderer_tokens)*
            );
            ::mingling::__dispatch_program_chains!(
                #(#chain_tokens)*
            );
            fn has_renderer(any: &::mingling::AnyOutput) -> bool {
                match any.type_id {
                    #(#renderer_exist_tokens)*
                    _ => false
                }
            }
            fn has_chain(any: &::mingling::AnyOutput) -> bool {
                match any.type_id {
                    #(#chain_exist_tokens)*
                    _ => false
                }
            }
        }

        impl #name {
            pub fn new() -> ::mingling::Program<#name> {
                ::mingling::Program::new()
            }
        }
    };

    TokenStream::from(expanded)
}

/// Internal macro for registering chains.
///
/// This macro is used internally by the `#[chain]` attribute macro
/// and should not be used directly.
#[doc(hidden)]
#[proc_macro]
pub fn __register_chain(input: TokenStream) -> TokenStream {
    let chain_entry = parse_macro_input!(input as syn::LitStr);
    let entry_str = chain_entry.value();

    CHAINS.lock().unwrap().push(entry_str);

    TokenStream::new()
}

/// Internal macro for registering renderers.
///
/// This macro is used internally by the `#[renderer]` attribute macro
/// and should not be used directly.
#[doc(hidden)]
#[proc_macro]
pub fn __register_renderer(input: TokenStream) -> TokenStream {
    let renderer_entry = parse_macro_input!(input as syn::LitStr);
    let entry_str = renderer_entry.value();

    RENDERERS.lock().unwrap().push(entry_str);

    TokenStream::new()
}