wstd_macro/
lib.rs

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
use proc_macro::TokenStream;
use quote::{quote, quote_spanned};
use syn::{parse_macro_input, spanned::Spanned, ItemFn};

#[proc_macro_attribute]
pub fn attr_macro_main(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as ItemFn);

    if input.sig.asyncness.is_none() {
        return quote_spanned! { input.sig.fn_token.span()=>
            compile_error!("fn must be `async fn`");
        }
        .into();
    }

    if input.sig.ident != "main" {
        return quote_spanned! { input.sig.ident.span()=>
            compile_error!("only `async fn main` can be used for #[wstd::main]");
        }
        .into();
    }

    if !input.sig.inputs.is_empty() {
        return quote_spanned! { input.sig.inputs.span()=>
            compile_error!("arguments to main are not supported");
        }
        .into();
    }
    let attrs = input.attrs;
    let output = input.sig.output;
    let block = input.block;
    quote! {
        pub fn main() #output {

            #(#attrs)*
            async fn __run() #output {
                #block
            }

            ::wstd::runtime::block_on(async {
                __run().await
            })
        }
    }
    .into()
}

#[proc_macro_attribute]
pub fn attr_macro_test(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as ItemFn);

    if input.sig.asyncness.is_none() {
        return quote_spanned! { input.sig.fn_token.span()=>
            compile_error!("fn must be `async fn`");
        }
        .into();
    }

    let name = input.sig.ident;

    if !input.sig.inputs.is_empty() {
        return quote_spanned! { input.sig.inputs.span()=>
            compile_error!("arguments to main are not supported");
        }
        .into();
    }
    let attrs = input.attrs;
    let output = input.sig.output;
    let block = input.block;
    quote! {
        #[test]
        pub fn #name() #output {

            #(#attrs)*
            async fn __run() #output {
                #block
            }

            ::wstd::runtime::block_on(async {
                __run().await
            })
        }
    }
    .into()
}

/// Enables a HTTP server main function, for creating [HTTP servers].
///
/// [HTTP servers]: https://docs.rs/wstd/latest/wstd/http/server/index.html
///
/// # Examples
///
/// ```ignore
/// #[wstd::http_server]
/// async fn main(request: Request<IncomingBody>, responder: Responder) -> Finished {
///     responder
///         .respond(Response::new("Hello!\n".into_body()))
///         .await
/// }
/// ```
#[proc_macro_attribute]
pub fn attr_macro_http_server(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as ItemFn);

    if input.sig.asyncness.is_none() {
        return quote_spanned! { input.sig.fn_token.span()=>
            compile_error!("fn must be `async fn`");
        }
        .into();
    }

    let output = &input.sig.output;
    let inputs = &input.sig.inputs;
    let name = &input.sig.ident;
    let body = &input.block;
    let attrs = &input.attrs;
    let vis = &input.vis;

    if name != "main" {
        return quote_spanned! { input.sig.ident.span()=>
            compile_error!("only `async fn main` can be used for #[wstd::http_server]");
        }
        .into();
    }

    quote! {
        struct TheServer;

        impl ::wstd::wasi::exports::http::incoming_handler::Guest for TheServer {
            fn handle(
                request: ::wstd::wasi::http::types::IncomingRequest,
                response_out: ::wstd::wasi::http::types::ResponseOutparam
            ) {
                #(#attrs)*
                #vis async fn __run(#inputs) #output {
                    #body
                }

                let responder = ::wstd::http::server::Responder::new(response_out);
                let _finished: ::wstd::http::server::Finished =
                    match ::wstd::http::request::try_from_incoming(request)
                {
                    Ok(request) => ::wstd::runtime::block_on(async { __run(request, responder).await }),
                    Err(err) => responder.fail(err),
                };
            }
        }

        ::wstd::wasi::http::proxy::export!(TheServer with_types_in ::wstd::wasi);

        // Provide an actual function named `main`.
        //
        // WASI HTTP server components don't use a traditional `main` function.
        // They export a function named `handle` which takes a `Request`
        // argument, and which may be called multiple times on the same
        // instance. To let users write a familiar `fn main` in a file
        // named src/main.rs, we provide this `wstd::http_server` macro, which
        // transforms the user's `fn main` into the appropriate `handle`
        // function.
        //
        // However, when the top-level file is named src/main.rs, rustc
        // requires there to be a function named `main` somewhere in it. This
        // requirement can be disabled using `#![no_main]`, however we can't
        // use that automatically because macros can't contain inner
        // attributes, and we don't want to require users to add `#![no_main]`
        // in their own code.
        //
        // So, we include a definition of a function named `main` here, which
        // isn't intended to ever be called, and exists just to satify the
        // requirement for a `main` function.
        //
        // Users could use `#![no_main]` if they want to. Or, they could name
        // their top-level file src/lib.rs and add
        // ```toml
        // [lib]
        // crate-type = ["cdylib"]
        // ```
        // to their Cargo.toml. With either of these, this "main" function will
        // be ignored as dead code.
        fn main() {
            unreachable!("HTTP server components should be run with `handle` rather than `run`")
        }
    }
    .into()
}