How to figure out the parameters and syntax for Rust macros?

89 Views Asked by At

For example: using the salvo_oapi crate, I have the following code:

use bson::doc;
use salvo::prelude::*;

use crate::{
    features::auth::models::user::{get_user_from_depot, User},
    utils::api_error::ApiError,
};

/// How to know what macros this cargo supports? Docs are unclear
#[endpoint(tags("Auth"), operationId = "fetch_user")]
pub async fn fetch_user(depot: &mut Depot) -> Result<Json<User>, ApiError> {
    let user = get_user_from_depot(depot)?;

    Ok(Json(user.clone()))
}

When I open cargo or the marco source code I can't find any place where the allowed macros are and what their names and inputs would be; very frustrating experience.

2

There are 2 best solutions below

1
Aurel Bílý On

The specific question/comment about the endpoint macro is indeed better addressed by the developers of salvo-oapi. Best open an issue: the docs here should have described how the macro is used, or at least linked to a guide/tutorial.

More generally, documentation of macros (of any kind) is not as easy as documentation of functions in Rust. This is because macros, by design, can treat the AST in non-standard ways to allow syntax extensions (within reason). So, where one attribute macro might use the syntax #[foo(a = 1, b = 2)], another might use #[foo(1, 2)], and yet another might be simply #[foo] with additional "inputs" coming from the body of the annotated item.

0
Fredrik Hammar On

I agree it can be frustrating to find where things are documented sometimes, especially when it's not where you expect it. But it is also difficult for the developers to predict where the user's entry point into the documentation is.

Going directly to the definition of salvo_oapi::endpoint is not documented and the source is minimal because an attribute macro does not actually do anything by itself.

Instead, it is processed in later in the salvo_oapi::endpoint module so the developers probably thought it was natural to document it there.

In these situations I recommend starting from the top of the crate documentation to see if they have any mentions. A bit down on salvo_oapi crate documentation you can find modules list with endpoint at the top with a good description:

Endpoint attribute macro implements OpenAPI path for the decorated function.

And in the Attribute Macros section you can find that endpoint is the only attribute macro available.