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
#![feature(iter_intersperse)]
#![feature(doc_cfg)]
#![warn(missing_docs)]
//! The macros use by `tauri-interop` to generate dynamic code depending on the target
//!
//! Without `tauri-interop` the generated code can't compile.

use proc_macro::TokenStream;
use std::collections::HashSet;
use std::sync::Mutex;

use proc_macro_error::{emit_call_site_error, emit_call_site_warning, proc_macro_error};
use quote::{format_ident, quote, ToTokens};
use syn::{
    parse::Parser, parse_macro_input, punctuated::Punctuated, ExprPath, ItemFn, ItemMod, Token,
};

use crate::command::collect::commands_to_punctuated;

mod command;
mod event;

/// Conditionally adds [Listen] or [Emit] to a struct.
///
/// The field values inside the struct require to be self owned.
/// That means references aren't allowed inside the event struct.
///
/// Depending on the targeted architecture the macro generates different results.
/// When compiling to `wasm` the [Listen] trait is derived. Otherwise, [Emit] is derived.
///
/// Both traits generate a new mod in which the related field-structs are generated in.
/// The mod can be automatically renamed with `#[auto_naming(EnumLike)]` to behave
/// enum-like (for example a struct `Test`s mod would usually be named `test`, 'EnumLike'
/// names it `TestField` instead) and `#[mod_name(...)]` is a direct possibility to rename
/// the mod to any given name.
///
/// The generated field-structs represent a field of the struct and are used for the
/// derived trait functions. The fields are used to `emit`, `update` or `listen_to` a
/// given field. For detail usages see the individual traits defined in `tauri-interop`.
///
/// ### Example
///
/// ```
/// use tauri_interop_macro::Event;
///
/// #[derive(Event)]
/// struct EventModel {
///     foo: String,
///     pub bar: bool
/// }
/// 
/// impl tauri_interop::event::ManagedEmit for EventModel {}
///
/// // has to be defined in this example, otherwise the
/// // macro expansion panics because of missing super
/// fn main() {}
/// ```
#[cfg(feature = "event")]
#[doc(cfg(feature = "event"))]
#[proc_macro_derive(Event, attributes(auto_naming, mod_name))]
pub fn derive_event(stream: TokenStream) -> TokenStream {
    if cfg!(feature = "_wasm") {
        event::listen::derive(stream)
    } else {
        event::emit::derive(stream)
    }
}

/// Generates a default `Emit` implementation for the given struct.
///
/// Used for host code generation. It is not intended to be used directly.
/// See [Event] for the usage.
#[cfg(feature = "event")]
#[doc(cfg(feature = "event"))]
#[proc_macro_derive(Emit, attributes(auto_naming, mod_name))]
pub fn derive_emit(stream: TokenStream) -> TokenStream {
    event::emit::derive(stream)
}

/// Generates a default `EmitField` implementation for the given struct.
///
/// Used for host code generation. It is not intended to be used directly.
#[cfg(feature = "event")]
#[doc(cfg(feature = "event"))]
#[proc_macro_derive(EmitField, attributes(parent, parent_field_name, parent_field_ty))]
pub fn derive_emit_field(stream: TokenStream) -> TokenStream {
    event::emit::derive_field(stream)
}

/// Generates a default `Listen` implementation for the given struct.
///
/// Used for wasm code generation. It is not intended to be used directly.
/// See [Event] for the usage.
#[cfg(feature = "event")]
#[doc(cfg(feature = "event"))]
#[proc_macro_derive(Listen, attributes(auto_naming, mod_name))]
pub fn derive_listen(stream: TokenStream) -> TokenStream {
    event::listen::derive(stream)
}

/// Generates a default `ListenField` implementation for the given struct.
///
/// Used for wasm code generation. It is not intended to be used directly.
#[cfg(feature = "event")]
#[doc(cfg(feature = "event"))]
#[proc_macro_derive(ListenField, attributes(parent, parent_field_ty))]
pub fn derive_listen_field(stream: TokenStream) -> TokenStream {
    event::listen::derive_field(stream)
}

/// Generates the wasm counterpart to a defined `tauri::command`
#[proc_macro_attribute]
pub fn binding(_attributes: TokenStream, stream: TokenStream) -> TokenStream {
    command::convert_to_binding(stream)
}

lazy_static::lazy_static! {
    static ref COMMAND_LIST_ALL: Mutex<HashSet<String>> = Mutex::new(HashSet::new());
}

lazy_static::lazy_static! {
    static ref COMMAND_LIST: Mutex<HashSet<String>> = Mutex::new(HashSet::new());
}

static COMMAND_MOD_NAME: Mutex<Option<String>> = Mutex::new(None);

/// Conditionally adds the macro [macro@binding] or `tauri::command` to a struct
///
/// By using this macro, when compiling to wasm, a version that invokes the
/// current function is generated.
///
/// ### Collecting commands
/// When this macro is compiled to the host target, additionally to adding the
/// `tauri::command` macro, the option to auto collect the command via
/// [macro@collect_commands] and [macro@combine_handlers] is provided.
///
/// ### Binding generation
/// All parameter arguments with `tauri` in their name (case-insensitive) are
/// removed as argument in a defined command. That includes `tauri::*` usages
/// and `Tauri` named types.
///
/// The type returned is evaluated automatically and is most of the time 1:1
/// to the defined type. When using a wrapped `Result<T, E>` type, it should
/// include the phrase "Result" in the type name. Otherwise, the returned type
/// can't be successfully interpreted as a result and by that will result in
/// wrong type/error handling/serialization.
///
/// ### Example - Definition
///
/// ```rust
/// #[tauri_interop_macro::command]
/// fn trigger_something(name: &str) {
///     print!("triggers something, but doesn't need to wait for it")
/// }
///
/// #[tauri_interop_macro::command]
/// fn wait_for_sync_execution(value: &str) -> String {
///     format!("Has to wait that the backend completes the computation and returns the {value}")
/// }
///
/// #[tauri_interop_macro::command]
/// async fn asynchronous_execution(change: bool) -> Result<String, String> {
///     if change {
///         Ok("asynchronous execution returning result, need Result in their type name".into())
///     } else {
///         Err("if they don't it, the error will be not be parsed/handled".into())
///     }
/// }
///
/// #[tauri_interop_macro::command]
/// async fn heavy_computation() {
///   std::thread::sleep(std::time::Duration::from_millis(5000))
/// }
/// ```
///
/// ### Example - Usage
///
/// ```rust , ignore
/// fn main() {
///     trigger_something();
///
///     wasm_bindgen_futures::spawn_local(async move {
///         wait_for_sync_execution("value").await;
///         asynchronous_execution(true).await.expect("returns ok");
///         heavy_computation().await;
///     });
/// }
/// ```
#[proc_macro_attribute]
pub fn command(_attributes: TokenStream, stream: TokenStream) -> TokenStream {
    let fn_item = parse_macro_input!(stream as ItemFn);

    COMMAND_LIST
        .lock()
        .unwrap()
        .insert(fn_item.sig.ident.to_string());

    let command_macro = quote! {
        #[cfg_attr(target_family = "wasm", ::tauri_interop::binding)]
        #[cfg_attr(not(target_family = "wasm"), ::tauri::command(rename_all = "snake_case"))]
        #fn_item
    };

    TokenStream::from(command_macro.to_token_stream())
}

/// Marks a mod that contains commands
///
/// A mod needs to be marked when multiple command mods should be combined.
/// See [combine_handlers!] for a detailed explanation/example.
///
/// Requires usage of unstable feature: `#![feature(proc_macro_hygiene)]`
#[proc_macro_attribute]
pub fn commands(_attributes: TokenStream, stream: TokenStream) -> TokenStream {
    let item_mod = parse_macro_input!(stream as ItemMod);
    let _ = COMMAND_MOD_NAME
        .lock()
        .unwrap()
        .insert(item_mod.ident.to_string());

    TokenStream::from(item_mod.to_token_stream())
}

/// Collects all commands annotated with `tauri_interop::command` and
/// provides these with a `get_handlers()` in the current mod
///
/// ### Example
///
/// ```
/// #[tauri_interop_macro::command]
/// fn greet(name: &str) -> String {
///     format!("Hello, {}! You've been greeted from Rust!", name)
/// }
///
/// tauri_interop_macro::collect_commands!();
///
/// fn main() {
///     let _ = tauri::Builder::default()
///     // This is where you pass in the generated handler collector
///     // in this example this would only register cmd1
///         .invoke_handler(get_handlers());
/// }
/// ```
#[proc_macro]
pub fn collect_commands(_: TokenStream) -> TokenStream {
    let mut commands = COMMAND_LIST.lock().unwrap();
    let stream = command::collect::get_handler_function(
        format_ident!("get_handlers"),
        &commands,
        commands_to_punctuated(&commands),
        Vec::new(),
    );

    // logic for renaming the commands, so that combine methode can just use the provided commands
    if let Some(mod_name) = COMMAND_MOD_NAME.lock().unwrap().as_ref() {
        COMMAND_LIST_ALL
            .lock()
            .unwrap()
            .extend(command::collect::commands_with_mod_name(
                mod_name, &commands,
            ));
    } else {
        // if there is no mod provided we can just move/clear the commands
        COMMAND_LIST_ALL
            .lock()
            .unwrap()
            .extend(commands.iter().cloned());
    }

    // clearing the already used handlers
    commands.clear();
    // set mod name to none
    let _ = COMMAND_MOD_NAME.lock().unwrap().take();

    TokenStream::from(stream.to_token_stream())
}

/// Combines multiple modules containing commands
///
/// Takes multiple module paths as input and provides a `get_all_handlers()` function in
/// the current mod that registers all commands from the provided mods. This macro does
/// still require the invocation of [collect_commands!] at the end of a command mod. In
/// addition, a mod has to be marked with [macro@commands].
///
/// ### Example
///
/// ```
/// #[tauri_interop_macro::commands]
/// mod cmd1 {
///     #[tauri_interop_macro::command]
///     pub fn cmd1() {}
///
///     tauri_interop_macro::collect_commands!();
/// }
///
/// mod whatever {
///     #[tauri_interop_macro::commands]
///     pub mod cmd2 {
///         #[tauri_interop_macro::command]
///         pub fn cmd2() {}
///
///         tauri_interop_macro::collect_commands!();
///     }
/// }
///
/// tauri_interop_macro::combine_handlers!( cmd1, whatever::cmd2 );
///
/// fn main() {
///     let _ = tauri::Builder::default()
///     // This is where you pass in the combined handler collector
///     // in this example it will register cmd1::cmd1 and whatever::cmd2::cmd2
///         .invoke_handler(get_all_handlers());
/// }
/// ```
#[proc_macro_error]
#[proc_macro]
pub fn combine_handlers(stream: TokenStream) -> TokenStream {
    if cfg!(feature = "_wasm") {
        return Default::default()
    }
    
    let command_mods = Punctuated::<ExprPath, Token![,]>::parse_terminated
        .parse2(stream.into())
        .unwrap()
        .into_iter()
        .collect::<Vec<_>>();

    let org_commands = COMMAND_LIST_ALL.lock().unwrap();
    let commands = command::collect::get_filtered_commands(&org_commands, &command_mods);

    if commands.is_empty() {
        emit_call_site_error!("No commands will be registered")
    }

    let remaining_commands = COMMAND_LIST.lock().unwrap();
    if !remaining_commands.is_empty() {
        emit_call_site_error!(
            "Their are dangling commands that won't be registered. See {:?}",
            remaining_commands
        )
    }

    if org_commands.len() > commands.len() {
        let diff = org_commands
            .difference(&commands)
            .cloned()
            .intersperse(String::from(","))
            .collect::<String>();
        emit_call_site_warning!(
            "Not all commands will be registered. Missing commands: {:?}",
            diff
        );
    }

    TokenStream::from(command::collect::get_handler_function(
        format_ident!("get_all_handlers"),
        &commands,
        commands_to_punctuated(&commands),
        command_mods,
    ))
}

/// Simple macro to include multiple imports (seperated by `|`) not in wasm
///
/// ### Example
///
/// ```rust
/// tauri_interop_macro::host_usage! {
///     use tauri::State;
///     | use std::sync::RwLock;
/// }
///
/// #[tauri_interop_macro::command]
/// pub fn empty_invoke(_state: State<RwLock<String>>) {}
/// ```
#[proc_macro]
pub fn host_usage(stream: TokenStream) -> TokenStream {
    let uses = command::collect::uses(stream);
    TokenStream::from(quote! {
        #(
            #[cfg(not(target_family = "wasm"))]
            #uses
        )*
    })
}

/// Simple macro to include multiple imports (seperated by `|`) only in wasm
///
/// Equivalent to [host_usage!] for wasm imports only required in wasm.
/// For an example see [host_usage!].
#[proc_macro]
pub fn wasm_usage(stream: TokenStream) -> TokenStream {
    let uses = command::collect::uses(stream);
    TokenStream::from(quote! {
        #(
            #[cfg(target_family = "wasm")]
            #uses
        )*
    })
}