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
#![doc = include_str!("../README.md")]
#![warn(
    elided_lifetimes_in_paths,
    missing_debug_implementations,
    missing_docs,
    unsafe_op_in_unsafe_fn,
    clippy::undocumented_unsafe_blocks,
    clippy::missing_safety_doc
)]

use proc_macro::TokenStream;
use syn::Error;

mod export;

fn handle_debug_and_errors<F>(
    cb: F,
    name: &str,
    attr: TokenStream,
    item: TokenStream,
) -> TokenStream
where
    F: FnOnce(
        proc_macro2::TokenStream,
        proc_macro2::TokenStream,
    ) -> Result<proc_macro2::TokenStream, Error>,
{
    if std::env::var_os("IC_CDK_DEBUG").is_some() {
        eprintln!("--- IC_CDK_MACROS DEBUG ---");
        eprintln!("{}\n    attr: {}\n    item: {}", name, attr, item);
    }

    let result = cb(attr.into(), item.into());

    if std::env::var_os("IC_CDK_DEBUG").is_some() {
        eprintln!("--------- RESULT  ---------");
        if let Ok(ref stream) = result {
            eprintln!("{}", stream);
        }
        eprintln!("---------------------------");
    }

    result.map_or_else(|e| e.to_compile_error().into(), Into::into)
}

/// Create a `get_candid_pointer` method so that `dfx` can execute it to extract candid definition.
///
/// Call this macro only if you want the Candid export behavior.
/// Only call it once at the end of canister code outside query/update definition.
#[proc_macro]
pub fn export_candid(input: TokenStream) -> TokenStream {
    let input: proc_macro2::TokenStream = input.into();
    quote::quote! {
        ::candid::export_service!(#input);

        #[no_mangle]
        pub fn get_candid_pointer() -> *mut std::os::raw::c_char {
            let c_string = std::ffi::CString::new(__export_service()).unwrap();
            c_string.into_raw()
        }
    }
    .into()
}

/// Register a query call entry point.
///
/// This attribute macro will export a function with name `canister_query <name>`
/// in the canister module.
///
/// # Example
///
/// ```rust
/// # use ic_cdk::query;
/// #[query]
/// fn query_function() {
///     // ...
/// # unimplemented!()
/// }
/// ```
///
/// You can also specify the name of the exported function.
///
/// ```rust
/// # use ic_cdk::query;
/// #[query(name = "some_name")]
/// fn query_function() {
///     // ...
/// # unimplemented!()
/// }
/// ```
///
/// If you want to hide this method in the Candid generated by [export_candid!],
/// you will need to set `hidden` to `true`. The entry point still exists in the canister.
///
/// ```rust
/// # use ic_cdk::query;
/// #[query(hidden = true)]
/// fn query_function() {
///     // ...
/// # unimplemented!()
/// }
/// ```
///
/// You can specify a guard function to be executed before the query function.
/// When the guard function returns an error, the query function will not proceed.
///
/// ```rust
/// # use ic_cdk::query;
/// fn guard_function() -> Result<(), String> {
///     // ...
/// # unimplemented!()
/// }
/// #[query(guard = "guard_function")]
/// fn query_function() {
///     // ...
/// # unimplemented!()
/// }
/// ```
///
/// To be able to make inter-canister calls from a query call, it must be a *composite* query (which cannot be executed in replicated mode).
///
/// ```rust
/// # use ic_cdk::query;
/// # fn wallet_canister_principal() -> candid::Principal { unimplemented!() }
/// #[query(composite = true)]
/// async fn composite_query_function() {
///    let (wallet_name,): (Option<String>,) = ic_cdk::call(wallet_canister_principal(), "name", ()).await.unwrap();
/// }
/// ```
///
/// If you would rather call the [`call::reply`] function than return a value,
/// you will need to set `manual_reply` to `true` so that the canister does not
/// trap.
///
/// ```rust
/// # fn calculate_result() {}
/// # type MyResult = ();
/// # use ic_cdk::query;
/// use ic_cdk::api::call::{self, ManualReply};
/// #[query(manual_reply = true)]
/// fn query_function() -> ManualReply<MyResult> {
///     let result = calculate_result();
///     ManualReply::one(result)
/// }
/// ```
///
/// [`call::reply`]: https://docs.rs/ic-cdk/latest/ic_cdk/api/call/fn.reply.html
#[proc_macro_attribute]
pub fn query(attr: TokenStream, item: TokenStream) -> TokenStream {
    handle_debug_and_errors(export::ic_query, "ic_query", attr, item)
}

/// Register an update call entry point.
///
/// This attribute macro will export a function with name `canister_update <name>`
/// in the canister module.
///
/// # Example
///
/// ```rust
/// # use ic_cdk::update;
/// #[update]
/// fn update_function() {
///     // ...
/// # unimplemented!()
/// }
/// ```
///
/// You can also specify the name of the exported function.
///
/// ```rust
/// # use ic_cdk::update;
/// #[update(name = "some_name")]
/// fn update_function() {
///     // ...
/// # unimplemented!()
/// }
/// ```
///
/// If you want to hide this method in the Candid generated by [export_candid!],
/// you will need to set `hidden` to `true`. The entry point still exists in the canister.
///
/// ```rust
/// # use ic_cdk::update;
/// #[update(hidden = true)]
/// fn update_function() {
///     // ...
/// # unimplemented!()
/// }
/// ```
///
/// You can specify a guard function to be executed before the update function.
/// When the guard function returns an error, the update function will not proceed.
///
/// ```rust
/// # use ic_cdk::update;
/// fn guard_function() -> Result<(), String> {
///     // ...
/// # unimplemented!()
/// }
/// #[update(guard = "guard_function")]
/// fn update_function() {
///     // ...
/// # unimplemented!()
/// }
/// ```
///
/// If you would rather call the [`call::reply`] function than return a value,
/// you will need to set `manual_reply` to `true` so that the canister does not
/// trap.
///
/// ```rust
/// # fn calculate_result() {}
/// # type MyResult = ();
/// # use ic_cdk::update;
/// use ic_cdk::api::call::{self, ManualReply};
/// #[update(manual_reply = true)]
/// fn update_function() -> ManualReply<MyResult> {
///     let result = calculate_result();
///     ManualReply::one(result)
/// }
/// ```
///
/// [`call::reply`]: https://docs.rs/ic-cdk/latest/ic_cdk/api/call/fn.reply.html
#[proc_macro_attribute]
pub fn update(attr: TokenStream, item: TokenStream) -> TokenStream {
    handle_debug_and_errors(export::ic_update, "ic_update", attr, item)
}

/// Register the `canister_init` entry point of a canister.
///
/// This attribute macro will export the function `canister_init`
/// in the canister module.
///
/// The function under this attribute must have no return value.
///
/// Each canister can only have one `canister_init` entry point.
///
/// # Example
///
/// ```rust
/// # use ic_cdk::init;
/// #[init]
/// fn init_function() {
///     // ...
/// # unimplemented!()
/// }
/// ```
///
/// The init function may accept an argument, if that argument is a `CandidType`:
///
/// ```rust
/// # use ic_cdk::init;
/// # use candid::*;
///
/// #[derive(Clone, Debug, CandidType, Deserialize)]
/// struct InitArg {
///     foo: u8,
/// }
///
/// #[init]
/// fn init_function(arg: InitArg) {
///     // ...
/// # unimplemented!()
/// }
/// ```
///
/// In this case, the argument will be read from `ic0.msg_arg_data_size/copy` and passed to the
/// init function upon successful deserialization.
/// Refer to the [`canister_init` Specification](https://smartcontracts.org/docs/interface-spec/index.html#system-api-init) for more information.
#[proc_macro_attribute]
pub fn init(attr: TokenStream, item: TokenStream) -> TokenStream {
    handle_debug_and_errors(export::ic_init, "ic_init", attr, item)
}

/// Register the `canister_pre_upgrade` entry point of a canister.
///
/// This attribute macro will export the function `canister_pre_upgrade`
/// in the canister module.
///
/// The function under this attribute must have no return value.
///
/// Each canister can only have one `canister_pre_upgrade` entry point.
///
/// # Example
///
/// ```rust
/// # use ic_cdk::pre_upgrade;
/// #[pre_upgrade]
/// fn pre_upgrade_function() {
///     // ...
/// # unimplemented!()
/// }
/// ```
#[proc_macro_attribute]
pub fn pre_upgrade(attr: TokenStream, item: TokenStream) -> TokenStream {
    handle_debug_and_errors(export::ic_pre_upgrade, "ic_pre_upgrade", attr, item)
}

/// Register the `canister_post_upgrade` entry point of a canister.
///
/// This attribute macro will export the function `canister_post_upgrade`
/// in the canister module.
///
/// The function under this attribute must have no return value.
///
/// Each canister can only have one `canister_post_upgrade` entry point.
///
/// # Example
///
/// ```rust
/// # use ic_cdk::post_upgrade;
/// #[post_upgrade]
/// fn post_upgrade_function() {
///     // ...
/// # unimplemented!()
/// }
/// ```
#[proc_macro_attribute]
pub fn post_upgrade(attr: TokenStream, item: TokenStream) -> TokenStream {
    handle_debug_and_errors(export::ic_post_upgrade, "ic_post_upgrade", attr, item)
}

/// Register the `canister_heartbeat` entry point of a canister.
///
/// This attribute macro will export the function `canister_heartbeat`
/// in the canister module.
///
/// The function under this attribute must have no return value.
///
/// Each canister can only have one `canister_heartbeat` entry point.
///
/// # Example
///
/// ```rust
/// # use ic_cdk::heartbeat;
/// #[heartbeat]
/// fn heartbeat_function() {
///     // ...
/// # unimplemented!()
/// }
/// ```
#[proc_macro_attribute]
pub fn heartbeat(attr: TokenStream, item: TokenStream) -> TokenStream {
    handle_debug_and_errors(export::ic_heartbeat, "ic_heartbeat", attr, item)
}

/// Register the `canister_inspect_message` entry point of a canister.
///
/// This attribute macro will export the function `canister_inspect_message`
/// in the canister module.
///
/// The function under this attribute must have no return value.
///
/// Each canister can only have one `canister_inspect_message` entry point.
///
/// # Example
///
/// ```rust
/// # use ic_cdk::inspect_message;
/// #[inspect_message]
/// fn inspect_message_function() {
///     // ...
/// # unimplemented!()
/// }
/// ```
#[proc_macro_attribute]
pub fn inspect_message(attr: TokenStream, item: TokenStream) -> TokenStream {
    handle_debug_and_errors(export::ic_inspect_message, "ic_inspect_message", attr, item)
}