Skip to main content

docstring_attr_silly/
lib.rs

1//! # `#[docstring]`
2//!
3//! This crate allows you to annotate your crates with `#[docstring]`, and
4//! subsequently use Python-style "docstrings" in them:
5//!
6//! ```rust
7//! # use docstring_attr_silly::docstring;
8//!
9//! #[docstring]
10//! fn foobar() -> i32 {
11//!     "returns a really cool number";
12//!
13//!     4
14//! }
15//! ```
16//!
17//! ## Features
18//!
19//! Sure!
20//!
21//! ## Known Limitations
22//!
23//! 1. It's really silly.
24//! 2. Needs `;` after the docstring because I was too lazy
25//!    to make it work without (see source code)
26
27#[proc_macro_attribute]
28pub fn docstring(_: TokenStream, item: TokenStream) -> TokenStream {
29    let mut fn_ = parse_macro_input!(item as ItemFn);
30
31    if let Some(
32        Stmt::Expr(
33            Expr::Lit(
34                ExprLit { lit: Lit::Str(s), .. }
35            ),
36            _
37        )
38    ) = fn_.block.stmts.get(0) {
39
40        let s = s.clone();
41        fn_.block.stmts.remove(0);
42        fn_.attrs.push(parse_quote! { #![doc = #s] });
43    }
44
45    fn_.into_token_stream().into()
46}
47
48use proc_macro::TokenStream;
49use quote::ToTokens;
50use syn::*;