tauri_macros/lib.rs
1// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
2// SPDX-License-Identifier: Apache-2.0
3// SPDX-License-Identifier: MIT
4
5extern crate proc_macro;
6use crate::context::ContextItems;
7use proc_macro::TokenStream;
8use syn::{parse_macro_input, DeriveInput};
9
10mod command;
11mod runtime;
12
13#[macro_use]
14mod context;
15
16/// Mark a function as a command handler. It creates a wrapper function with the necessary glue code.
17///
18/// # Stability
19/// The output of this macro is managed internally by Tauri,
20/// and should not be accessed directly on normal applications.
21/// It may have breaking changes in the future.
22#[proc_macro_attribute]
23pub fn command(attributes: TokenStream, item: TokenStream) -> TokenStream {
24 command::wrapper(attributes, item)
25}
26
27/// Accepts a list of commands functions. Creates a handler that allows commands to be called from JS with invoke().
28///
29/// # Example
30/// ```rust,ignore
31/// use tauri::command;
32/// #[command]
33/// fn command_one() {}
34/// #[command]
35/// fn command_two() {}
36/// fn main() {
37/// tauri::Builder::default()
38/// .invoke_handler(tauri::generate_handler![command_one, command_two])
39/// .run(tauri::generate_context!())
40/// .expect("error while running tauri application");
41/// }
42/// ```
43/// # Stability
44/// The output of this macro is managed internally by Tauri,
45/// and should not be accessed directly on normal applications.
46/// It may have breaking changes in the future.
47#[proc_macro]
48pub fn generate_handler(item: TokenStream) -> TokenStream {
49 parse_macro_input!(item as command::Handler).into()
50}
51
52/// Reads a Tauri config file and generates a `::tauri::Context` based on the content.
53///
54/// # Stability
55/// The output of this macro is managed internally by Tauri,
56/// and should not be accessed directly on normal applications.
57/// It may have breaking changes in the future.
58#[proc_macro]
59pub fn generate_context(items: TokenStream) -> TokenStream {
60 // this macro is exported from the context module
61 let path = parse_macro_input!(items as ContextItems);
62 context::generate_context(path).into()
63}
64
65/// Adds the default type for the last parameter (assumed to be runtime) for a specific feature.
66///
67/// e.g. To default the runtime generic to type `crate::Wry` when the `wry` feature is enabled, the
68/// syntax would look like `#[default_runtime(crate::Wry, wry)`. This is **always** set for the last
69/// generic, so make sure the last generic is the runtime when using this macro.
70#[doc(hidden)]
71#[proc_macro_attribute]
72pub fn default_runtime(attributes: TokenStream, input: TokenStream) -> TokenStream {
73 let attributes = parse_macro_input!(attributes as runtime::Attributes);
74 let input = parse_macro_input!(input as DeriveInput);
75 runtime::default_runtime(attributes, input).into()
76}