aboutsummaryrefslogtreecommitdiff
path: root/zkvms/risc0/wrapper_macro/src/lib.rs
blob: 7fa328b1ee3a44fd1d84392be82be18f6999ef04 (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
use proc_macro::TokenStream;

#[path = "../../../../guests_macro/src/parse_fn.rs"]
mod parse_fn;
use crate::parse_fn::{args_divide_grouped, args_divide_public, args_split, split_fn};

/// Create a body, which reads all inputs, stores them in variables, then
/// commits the ones, defined as public in `default_public_input.toml` to the
/// journal and finally executes the guest entrypoint function with those
/// arguments, committing its output.
///
/// # Usage
///
/// Inside RISC0's guest (excluding the `entrypoint_expr` call):
///
/// ```rust
/// make_wrapper!{fn main(...) -> ...}
/// ```
///
/// # Example output
///
/// ```rust
/// {
///     let ... : ... = read();
///     let ... : ... = read();
///     ...
///     commit(&...);
///     commit(&...);
///     ...
///     commit(&zkp::main(..., ..., ...));
/// }
/// ```
#[proc_macro]
pub fn make_wrapper(item: TokenStream) -> TokenStream {
    let (name, args, ret) = split_fn(&item);
    let args_split = args_split(&args);

    let mut out = TokenStream::new();
    for arg in args_split {
        out.extend(format!("let {} = read();", arg).parse::<TokenStream>());
    }

    let public_inputs = toml::from_str::<toml::Table>(include_str!(concat!(
        env!("INPUTS_DIR"),
        "/default_public_input.toml"
    )))
    .unwrap();
    let public_patterns = args_divide_public(&args, &public_inputs.keys().collect())
        .0
         .0;
    for pattern in public_patterns.iter() {
        out.extend(format!("commit(&{});", pattern).parse::<TokenStream>());
    }

    let (ts_patterns, _) = args_divide_grouped(&args);

    out.extend(format!("commit(&zkp::{}{});", name, ts_patterns).parse::<TokenStream>());

    let mut block = TokenStream::new();
    block.extend(format!("{{ {} }}", out).parse::<TokenStream>());
    block
}