Port over doc comments in route macros.

This allows documentation on the functions to appear in the generated
docs, e.g.:

```rust
/// The index page
async fn index() -> &'static str {
    "Hello!"
}
```
This commit is contained in:
Erik Johnston 2021-02-23 22:54:38 +00:00
parent d92ab7e8e0
commit cb1a712296
4 changed files with 37 additions and 0 deletions

View File

@ -1,6 +1,7 @@
# Changes
## Unreleased - 2021-xx-xx
* Preserve doc comments when using route macros.
## 0.5.0-beta.1 - 2021-02-10

View File

@ -176,6 +176,9 @@ pub struct Route {
args: Args,
ast: syn::ItemFn,
resource_type: ResourceType,
/// The doc comment attribute to copy to generated struct, if any.
doc_attribute: Option<syn::Attribute>,
}
fn guess_resource_type(typ: &syn::Type) -> ResourceType {
@ -221,6 +224,17 @@ impl Route {
let ast: syn::ItemFn = syn::parse(input)?;
let name = ast.sig.ident.clone();
// Try and pull out the doc comments so that we can reapply them to the
// generated struct.
let mut doc_attribute = None;
for attr in &ast.attrs {
if let Some(ident) = attr.path.get_ident() {
if ident == "doc" {
doc_attribute = Some(attr.clone());
}
}
}
let args = Args::new(args, method)?;
if args.methods.is_empty() {
return Err(syn::Error::new(
@ -248,6 +262,7 @@ impl Route {
args,
ast,
resource_type,
doc_attribute,
})
}
}
@ -265,6 +280,7 @@ impl ToTokens for Route {
methods,
},
resource_type,
doc_attribute,
} = self;
let resource_name = name.to_string();
let method_guards = {
@ -287,6 +303,7 @@ impl ToTokens for Route {
};
let stream = quote! {
#doc_attribute
#[allow(non_camel_case_types, missing_docs)]
pub struct #name;

View File

@ -9,6 +9,8 @@ fn compile_macros() {
t.compile_fail("tests/trybuild/route-missing-method-fail.rs");
t.compile_fail("tests/trybuild/route-duplicate-method-fail.rs");
t.compile_fail("tests/trybuild/route-unexpected-method-fail.rs");
t.pass("tests/trybuild/docstring-ok.rs");
}
// #[rustversion::not(nightly)]

View File

@ -0,0 +1,17 @@
use actix_web::{Responder, HttpResponse, App, test};
use actix_web_codegen::*;
/// Docstrings shouldn't break anything.
#[get("/")]
async fn index() -> impl Responder {
HttpResponse::Ok()
}
#[actix_web::main]
async fn main() {
let srv = test::start(|| App::new().service(index));
let request = srv.get("/");
let response = request.send().await.unwrap();
assert!(response.status().is_success());
}