Generating documentation in macros

前端 未结 1 1273
甜味超标
甜味超标 2020-11-27 07:12

I have a couple of macros to reduce boilerplate when defining certain tuple-structs of the form:

macro_rules! new_type (($name:ident, $bytes:expr) => (
           


        
相关标签:
1条回答
  • 2020-11-27 08:16

    It is possible to capture doc comments in macro invocations. It is not widely-known, but Rust documentation is actually represented as a special kind of attribute on an item. For example:

    /// Some documentation comment
    pub fn function() {}
    
    // is equivalent to
    
    #[doc="Some documentation comment"]
    pub fn function() {}
    

    And it is possible to capture attributes in macros. There are already several macros which use this ability, the most used probably being bitflags!:

    macro_rules! bitflags {
        (
            $(#[$outer:meta])*
            pub struct $BitFlags:ident: $T:ty {
                $(
                    $(#[$inner:ident $($args:tt)*])*
                    const $Flag:ident = $value:expr;
                )+
            }
        ) => { /* ... */ };
        // ...
    }
    

    Note the $(#[$outer:meta])* and $(#[$inner:meta])* parts of the pattern. These capture all attributes placed before the respective item in the pattern. If you write a doc comment there, it will be converted to the doc attribute and will be passed to rustdoc, as usual.

    The following is an example from the quick_error crate which also uses this approach:

    quick_error! {
        #[derive(Debug)]
        pub enum SomeError {
            /// IO Error
            Io(err: io::Error) {}
            /// Arbitrary system error
            Sys(errno: nix::Errno) {}
        }
    }
    

    It does work — here is an example of the structure generated by quick_error macro, and here is its definition.

    0 讨论(0)
提交回复
热议问题