Skip to main content

ntex_macros/
lib.rs

1//! Procedural macros for ntex.
2//!
3//! You don't need to depend on this crate directly, `ntex` re-exports every
4//! macro:
5//!
6//! - `#[ntex::main]` runs an async function on the ntex runtime, see
7//!   [`rt_main`].
8//! - `#[ntex::test]` does the same for a test, see [`rt_test`].
9//! - `#[ntex::web::get]`, `#[ntex::web::post]` and friends turn an async
10//!   function into a web handler with a path and a method guard, see
11//!   [`web_get`].
12//!
13//! ## Route macros
14//!
15//! | `ntex::web` | Method    | This crate        |
16//! |-------------|-----------|-------------------|
17//! | `get`       | `GET`     | [`web_get`]       |
18//! | `post`      | `POST`    | [`web_post`]      |
19//! | `put`       | `PUT`     | [`web_put`]       |
20//! | `delete`    | `DELETE`  | [`web_delete`]    |
21//! | `head`      | `HEAD`    | [`web_head`]      |
22//! | `connect`   | `CONNECT` | [`web_connect`]   |
23//! | `options`   | `OPTIONS` | [`web_options`]   |
24//! | `trace`     | `TRACE`   | [`web_trace`]     |
25//! | `patch`     | `PATCH`   | [`web_patch`]     |
26//! | `query`     | `QUERY`   | [`web_query`]     |
27//!
28//! All of them take the same arguments, they are described on [`web_get`].
29//!
30//! ```rust
31//! use ntex::web::{App, HttpResponse, get, types::Path};
32//!
33//! #[get("/users/{id}")]
34//! async fn user(id: Path<u32>) -> HttpResponse {
35//!     HttpResponse::Ok().body(format!("user {}", id.into_inner()))
36//! }
37//!
38//! // `user` is now a service, register it on an application
39//! let app = App::<()>::new().service(user);
40//! ```
41
42#![forbid(unsafe_code)]
43
44use proc_macro::TokenStream;
45use proc_macro2::TokenStream as TokenStream2;
46use quote::quote;
47
48mod parse;
49mod route;
50mod sys;
51
52/// Creates a route handler with a `GET` method guard.
53///
54/// Re-exported as `ntex::web::get`.
55///
56/// Syntax: `#[get("path"[, guard = "fn_name"]*[, state = Type])]`
57///
58/// The macro takes a handler function and replaces it with a unit struct of
59/// the same name. The struct is a web service, you register it with
60/// `.service()` on an `App` or a `scope`. The function itself ends up inside
61/// the generated code, so you can't call it directly anymore. The struct is
62/// always `pub`, whatever the visibility of the function.
63///
64/// The function is any handler `Route::to()` accepts: an `async fn` with up
65/// to 16 extractors, or a plain `fn` that returns a future. The function name
66/// is also used as the resource name, so it works with `url_for()`.
67///
68/// ## Arguments
69///
70/// - `"path"` - path of the resource, the same syntax as for
71///   `Resource::new()`, for example `"/users/{id}"`. Required, must come
72///   first.
73/// - `guard = "fn_name"` - adds a guard built with
74///   `ntex::web::guard::fn_guard()`. The value is the name of a function
75///   `fn(&RequestHead) -> bool` that is in scope where the macro is used. It
76///   must be a plain name, paths like `"guards::is_json"` are not supported,
77///   import the function instead. Can be given more than once, all guards must
78///   pass.
79/// - `state = Type` - type of the application state, written as a type path
80///   without quotes. The handler can then only be registered on an
81///   `App<Type>`, and its errors use the error type of `Type`. It does not
82///   give the handler access to the state. Defaults to `()`, the state of
83///   `App::new()`.
84///
85/// ## Examples
86///
87/// ```rust
88/// use ntex::http::RequestHead;
89/// use ntex::web::{App, HttpResponse, get, post};
90///
91/// #[get("/")]
92/// async fn index() -> HttpResponse {
93///     HttpResponse::Ok().body("hello")
94/// }
95///
96/// fn is_json(req: &RequestHead) -> bool {
97///     req.headers()
98///         .get("content-type")
99///         .is_some_and(|v| v == "application/json")
100/// }
101///
102/// // only matches POST requests with a json content type
103/// #[post("/items", guard = "is_json")]
104/// async fn create_item(body: String) -> HttpResponse {
105///     HttpResponse::Created().body(body)
106/// }
107///
108/// let app = App::<()>::new().service((index, create_item));
109/// ```
110///
111/// With a custom application state:
112///
113/// ```rust
114/// use ntex::web::{self, App, HttpResponse, get};
115///
116/// #[derive(Clone)]
117/// struct MyState;
118///
119/// impl web::State for MyState {
120///     type Error = web::DefaultError;
121/// }
122///
123/// #[get("/", state = MyState)]
124/// async fn index() -> HttpResponse {
125///     HttpResponse::Ok().build()
126/// }
127///
128/// let app = App::<MyState>::new().service(index);
129/// ```
130#[proc_macro_attribute]
131pub fn web_get(args: TokenStream, input: TokenStream) -> TokenStream {
132    let gen_code = match route::Route::new(args, input, route::MethodType::Get) {
133        Ok(gen_code) => gen_code,
134        Err(err) => return err.to_compile_error().into(),
135    };
136    gen_code.generate()
137}
138
139/// Creates a route handler with a `POST` method guard.
140///
141/// Re-exported as `ntex::web::post`.
142///
143/// Syntax: `#[post("path"[, guard = "fn_name"]*[, state = Type])]`
144///
145/// Works the same way and takes the same arguments as [`web_get`].
146#[proc_macro_attribute]
147pub fn web_post(args: TokenStream, input: TokenStream) -> TokenStream {
148    let gen_code = match route::Route::new(args, input, route::MethodType::Post) {
149        Ok(gen_code) => gen_code,
150        Err(err) => return err.to_compile_error().into(),
151    };
152    gen_code.generate()
153}
154
155/// Creates a route handler with a `PUT` method guard.
156///
157/// Re-exported as `ntex::web::put`.
158///
159/// Syntax: `#[put("path"[, guard = "fn_name"]*[, state = Type])]`
160///
161/// Works the same way and takes the same arguments as [`web_get`].
162#[proc_macro_attribute]
163pub fn web_put(args: TokenStream, input: TokenStream) -> TokenStream {
164    let gen_code = match route::Route::new(args, input, route::MethodType::Put) {
165        Ok(gen_code) => gen_code,
166        Err(err) => return err.to_compile_error().into(),
167    };
168    gen_code.generate()
169}
170
171/// Creates a route handler with a `DELETE` method guard.
172///
173/// Re-exported as `ntex::web::delete`.
174///
175/// Syntax: `#[delete("path"[, guard = "fn_name"]*[, state = Type])]`
176///
177/// Works the same way and takes the same arguments as [`web_get`].
178#[proc_macro_attribute]
179pub fn web_delete(args: TokenStream, input: TokenStream) -> TokenStream {
180    let gen_code = match route::Route::new(args, input, route::MethodType::Delete) {
181        Ok(gen_code) => gen_code,
182        Err(err) => return err.to_compile_error().into(),
183    };
184    gen_code.generate()
185}
186
187/// Creates a route handler with a `HEAD` method guard.
188///
189/// Re-exported as `ntex::web::head`.
190///
191/// Syntax: `#[head("path"[, guard = "fn_name"]*[, state = Type])]`
192///
193/// Works the same way and takes the same arguments as [`web_get`].
194#[proc_macro_attribute]
195pub fn web_head(args: TokenStream, input: TokenStream) -> TokenStream {
196    let gen_code = match route::Route::new(args, input, route::MethodType::Head) {
197        Ok(gen_code) => gen_code,
198        Err(err) => return err.to_compile_error().into(),
199    };
200    gen_code.generate()
201}
202
203/// Creates a route handler with a `CONNECT` method guard.
204///
205/// Re-exported as `ntex::web::connect`.
206///
207/// Syntax: `#[connect("path"[, guard = "fn_name"]*[, state = Type])]`
208///
209/// Works the same way and takes the same arguments as [`web_get`].
210#[proc_macro_attribute]
211pub fn web_connect(args: TokenStream, input: TokenStream) -> TokenStream {
212    let gen_code = match route::Route::new(args, input, route::MethodType::Connect) {
213        Ok(gen_code) => gen_code,
214        Err(err) => return err.to_compile_error().into(),
215    };
216    gen_code.generate()
217}
218
219/// Creates a route handler with a `OPTIONS` method guard.
220///
221/// Re-exported as `ntex::web::options`.
222///
223/// Syntax: `#[options("path"[, guard = "fn_name"]*[, state = Type])]`
224///
225/// Works the same way and takes the same arguments as [`web_get`].
226#[proc_macro_attribute]
227pub fn web_options(args: TokenStream, input: TokenStream) -> TokenStream {
228    let gen_code = match route::Route::new(args, input, route::MethodType::Options) {
229        Ok(gen_code) => gen_code,
230        Err(err) => return err.to_compile_error().into(),
231    };
232    gen_code.generate()
233}
234
235/// Creates a route handler with a `TRACE` method guard.
236///
237/// Re-exported as `ntex::web::trace`.
238///
239/// Syntax: `#[trace("path"[, guard = "fn_name"]*[, state = Type])]`
240///
241/// Works the same way and takes the same arguments as [`web_get`].
242#[proc_macro_attribute]
243pub fn web_trace(args: TokenStream, input: TokenStream) -> TokenStream {
244    let gen_code = match route::Route::new(args, input, route::MethodType::Trace) {
245        Ok(gen_code) => gen_code,
246        Err(err) => return err.to_compile_error().into(),
247    };
248    gen_code.generate()
249}
250
251/// Creates a route handler with a `PATCH` method guard.
252///
253/// Re-exported as `ntex::web::patch`.
254///
255/// Syntax: `#[patch("path"[, guard = "fn_name"]*[, state = Type])]`
256///
257/// Works the same way and takes the same arguments as [`web_get`].
258#[proc_macro_attribute]
259pub fn web_patch(args: TokenStream, input: TokenStream) -> TokenStream {
260    let gen_code = match route::Route::new(args, input, route::MethodType::Patch) {
261        Ok(gen_code) => gen_code,
262        Err(err) => return err.to_compile_error().into(),
263    };
264    gen_code.generate()
265}
266
267/// Creates a route handler with a `QUERY` method guard.
268///
269/// Re-exported as `ntex::web::query`.
270///
271/// Syntax: `#[query("path"[, guard = "fn_name"]*[, state = Type])]`
272///
273/// Works the same way and takes the same arguments as [`web_get`].
274#[proc_macro_attribute]
275pub fn web_query(args: TokenStream, input: TokenStream) -> TokenStream {
276    let gen_code = match route::Route::new(args, input, route::MethodType::Query) {
277        Ok(gen_code) => gen_code,
278        Err(err) => return err.to_compile_error().into(),
279    };
280    gen_code.generate()
281}
282
283/// Runs an async function on the ntex runtime.
284///
285/// Re-exported as `ntex::main`.
286///
287/// The function becomes a normal blocking function. When called, it builds a
288/// `System`, runs the body to completion and returns its result, so the
289/// function can return a value, for example `std::io::Result<()>`. It does
290/// not have to be `main`.
291///
292/// ```rust
293/// #[ntex::main]
294/// async fn main() -> std::io::Result<()> {
295///     println!("Hello world");
296///     Ok(())
297/// }
298/// ```
299///
300/// ## Arguments
301///
302/// - `name = "..."` - name of the system. Defaults to the function name.
303/// - `signals = true/false` - handle process signals. Off by default.
304/// - `fatal_signals = true/false` - report `SIGSEGV` and `SIGABRT` as
305///   `Signal::Panic`, the process still terminates. Unix only, only useful
306///   together with `signals = true`. Off by default.
307/// - `panic_handling = true/false` - report application panics as
308///   `Signal::Panic`. Only useful together with `signals = true`. Off by
309///   default.
310/// - `ping_interval = N` - how often, in milliseconds, the system pings its
311///   arbiters to spot busy ones. Defaults to 2000, zero turns pings off.
312/// - `timer_resolution = N` - resolution of the timer wheel in milliseconds,
313///   a power of two between 1 and 16. Defaults to 16.
314/// - `thread_pool = N` - maximum number of blocking thread-pool workers,
315///   passed to `Builder::thread_pool_limit`. Defaults to 64 per arbiter.
316/// - `task_callbacks = path` - a `fn() -> ntex::rt::TaskCallbacks` factory for
317///   instrumenting spawned tasks, passed to `Builder::task_callbacks`. It is
318///   called on every thread of the system. None by default.
319/// - `rt = path` - the runtime to run on, a value that implements
320///   `ntex::rt::Runner`. Defaults to `ntex::rt::DefaultRuntime`, the runtime
321///   picked by ntex features.
322///
323/// ```rust
324/// #[ntex::main(name = "server", signals = true, ping_interval = 250)]
325/// async fn main() {
326///     println!("Hello world");
327/// }
328/// ```
329#[proc_macro_attribute]
330pub fn rt_main(args: TokenStream, item: TokenStream) -> TokenStream {
331    let mut args = match sys::MainArgs::parse(args.into()) {
332        Ok(args) => args,
333        Err(err) => return err.into(),
334    };
335    let input = match parse::ItemFn::parse(item.into()) {
336        Ok(input) => input,
337        Err(err) => return err.into(),
338    };
339
340    if !input.is_async() {
341        return input.fn_error("only async fn is supported").into();
342    }
343
344    let attrs = input.attrs();
345    let vis = input.vis();
346    let sig = input.sig_without_async();
347    let body = input.body();
348    let runner = args.gen_sys_rt();
349    let config = args.gen_sys_config(input.ident());
350
351    (quote! {
352        #(#attrs)*
353        #vis #sig {
354            ntex::rt::System::build()
355                #config
356                .build( #runner )
357                .block_on(async move #body)
358        }
359    })
360    .into()
361}
362
363/// Runs an async test on the ntex runtime.
364///
365/// Re-exported as `ntex::test`.
366///
367/// The macro adds `#[test]`, unless the function already has it, and runs the
368/// body on a new `System` named after the test. The system is built in
369/// testing mode, without signal and panic handling, and always uses
370/// `ntex::rt::DefaultRuntime`. The test can return a `Result`, like a normal
371/// test.
372///
373/// ## Arguments
374///
375/// - `timer_resolution = N` - resolution of the timer wheel in milliseconds,
376///   a power of two between 1 and 16. Defaults to 16.
377/// - `task_callbacks = path` - a `fn() -> ntex::rt::TaskCallbacks` factory, as
378///   for [`rt_main`].
379///
380/// Other arguments, including the rest of those of [`rt_main`], are a compile
381/// error. Build a `System` manually for any other runtime configuration.
382///
383/// It also turns on `env_logger` at `trace` level, unless `RUST_LOG` is set.
384/// Set `NTEX_NO_TEST_LOG` or enable the `no-test-logging` feature of ntex to
385/// turn logging off.
386///
387/// ```no_run
388/// #[ntex::test]
389/// async fn my_test() {
390///     assert!(true);
391/// }
392///
393/// #[ntex::test]
394/// async fn my_fallible_test() -> std::io::Result<()> {
395///     Ok(())
396/// }
397///
398/// #[ntex::test(timer_resolution = 1)]
399/// async fn my_precise_timer_test() {}
400/// ```
401#[proc_macro_attribute]
402pub fn rt_test(args: TokenStream, item: TokenStream) -> TokenStream {
403    gen_test(
404        args,
405        item,
406        quote!(ntex::util::enable_test_logging();),
407        quote!(ntex::rt::System),
408        quote!(ntex::rt::DefaultRuntime),
409    )
410}
411
412/// Same as [`rt_test`] for crates that depend on `ntex-rt` directly. Doesn't
413/// enable test logging.
414#[doc(hidden)]
415#[proc_macro_attribute]
416pub fn rt_test2(args: TokenStream, item: TokenStream) -> TokenStream {
417    gen_test(
418        args,
419        item,
420        TokenStream2::new(),
421        quote!(ntex_rt::System),
422        quote!(ntex::rt::DefaultRuntime),
423    )
424}
425
426/// Same as [`rt_test`] for tests inside the `ntex` crate itself, it refers to
427/// `crate::` paths.
428#[doc(hidden)]
429#[proc_macro_attribute]
430pub fn rt_test_internal(args: TokenStream, item: TokenStream) -> TokenStream {
431    gen_test(
432        args,
433        item,
434        quote!(crate::util::enable_test_logging();),
435        quote!(ntex_rt::System),
436        quote!(crate::rt::DefaultRuntime),
437    )
438}
439
440/// Expands a test function, `setup` runs before the system is built
441fn gen_test(
442    args: TokenStream,
443    item: TokenStream,
444    setup: TokenStream2,
445    system: TokenStream2,
446    runtime: TokenStream2,
447) -> TokenStream {
448    let config = match sys::TestArgs::parse(args.into()) {
449        Ok(args) => args.gen_sys_config(),
450        Err(err) => return err.into(),
451    };
452
453    let input = match parse::ItemFn::parse(item.into()) {
454        Ok(input) => input,
455        Err(err) => return err.into(),
456    };
457
458    if !input.is_async() {
459        return input
460            .fn_error(format!("only async fn is supported, {}", input.ident()))
461            .into();
462    }
463
464    let name = input.ident();
465    let ret = input.output();
466    let fut = boxed_future(input.output_type(), input.body());
467    let attrs = input.attrs();
468    let test_attr = if input.has_attr("test") {
469        TokenStream2::new()
470    } else {
471        quote!(#[test])
472    };
473
474    (quote! {
475        #test_attr
476        #(#attrs)*
477        fn #name() #ret {
478            #setup
479            #system::build()
480                .name(stringify!(#name))
481                .testing()
482                #config
483                .build(#runtime)
484                .block_on(#fut)
485        }
486    })
487    .into()
488}
489
490/// Box the test body so the runtime's `block_on` is generated once per
491/// return type instead of once per test function
492fn boxed_future(output: TokenStream2, body: TokenStream2) -> TokenStream2 {
493    quote! {
494        ::std::boxed::Box::pin(async #body)
495            as ::std::pin::Pin<::std::boxed::Box<dyn ::std::future::Future<Output = #output>>>
496    }
497}