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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! This crate provide a set of attribute macros to faciliate canister development.
//!
//! The macros fall into two categories:
//! * To register functions as canister entry points
//! * To import another canister as a rust struct for inter-canister operation.
//!
//! ## Register functions as canister entry points
//!
//! These macros are directly related to the [Internet Computer Specification](https://smartcontracts.org/docs/interface-spec/index.html#_entry_points).
//!
//! * [`init`](attr.init.html)
//! * [`pre_upgrade`](attr.pre_upgrade.html)
//! * [`post_upgrade`](attr.post_upgrade.html)
//! * [`inspect_message`](attr.inspect_message.html)
//! * [`heartbeat`](attr.heartbeat.html)
//! * [`update`](attr.update.html)
//! * [`query`](attr.query.html)
//!
//! ## Import another canister as a rust struct
//!
//! * [`import`](attr.import.html)

#![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 std::sync::atomic::{AtomicU32, Ordering};
use syn::Error;

mod export;
mod import;

// To generate unique identifiers for functions and arguments
static NEXT_ID: AtomicU32 = AtomicU32::new(0);
pub(crate) fn id() -> u32 {
    NEXT_ID.fetch_add(1, Ordering::SeqCst)
}

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)
}

/// 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!()
/// }
/// ```
///
/// 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() -> ic_cdk::export::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!()
/// }
/// ```
///
/// 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!()
/// }
/// ```
///
/// You can specify a guard function to be executed before the init function.
/// When the guard function returns an error, the init function will not proceed.
///
/// ```rust
/// # use ic_cdk::init;
/// fn guard_function() -> Result<(), String> {
///     // ...
/// # unimplemented!()
/// }
/// #[init(guard = "guard_function")]
/// 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!()
/// }
/// ```
///
/// You can specify a guard function to be executed before the pre_upgrade function.
/// When the guard function returns an error, the pre_upgrade function will not proceed.
///
/// ```rust
/// # use ic_cdk::pre_upgrade;
/// fn guard_function() -> Result<(), String> {
///     // ...
/// # unimplemented!()
/// }
/// #[pre_upgrade(guard = "guard_function")]
/// 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!()
/// }
/// ```
///
/// You can specify a guard function to be executed before the post_upgrade function.
/// When the guard function returns an error, the post_upgrade function will not proceed.
///
/// ```rust
/// # use ic_cdk::post_upgrade;
/// fn guard_function() -> Result<(), String> {
///     // ...
/// # unimplemented!()
/// }
/// #[post_upgrade(guard = "guard_function")]
/// 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!()
/// }
/// ```
///
/// You can specify a guard function to be executed before the heartbeat function.
/// When the guard function returns an error, the heartbeat function will not proceed.
///
/// ```rust
/// # use ic_cdk::heartbeat;
/// fn guard_function() -> Result<(), String> {
///     // ...
/// # unimplemented!()
/// }
/// #[heartbeat(guard = "guard_function")]
/// 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!()
/// }
/// ```
///
/// You can specify a guard function to be executed before the inspect_message function.
/// When the guard function returns an error, the inspect_message function will not proceed.
///
/// ```rust
/// # use ic_cdk::*;
/// fn guard_function() -> Result<(), String> {
///     // ...
/// # unimplemented!()
/// }
/// #[inspect_message(guard = "guard_function")]
/// 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)
}

/// Import another canister as a rust struct.
///
/// All public interfaces defined in corresponding candid file can be accessed through the annotated struct.
///
/// # Example
///
/// You can specify the canister with it's name.
///
/// Please be noted that this approach relies on the project organization by [dfx](https://github.com/dfinity/sdk).
///
/// During `dfx build`, the imported canister will be correctly resolved.
///
/// ```rust,ignore
/// # use ic_cdk::import;
/// #[import(canister = "some_canister")]
/// struct SomeCanister;
/// ```
///
/// Or you can specify both the `canister_id` and the `candid_path`.
///
/// ```rust,ignore
/// # use ic_cdk::import;
/// #[import(canister_id = "abcde-cai", candid_path = "path/to/some_canister.did")]
/// struct SomeCanister;
/// ```
#[proc_macro_attribute]
pub fn import(attr: TokenStream, item: TokenStream) -> TokenStream {
    handle_debug_and_errors(import::ic_import, "ic_import", attr, item)
}