1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
//#![deny(missing_docs)] // https://github.com/rust-lang/rust/issues/42008
#![doc(html_root_url = "http://docs.rs/doc-cfg/0.1.0")]

//! The [`doc_cfg`] attribute is a convenience that removes the boilerplate
//! involved with using [`#[doc(cfg(..))]`](https://doc.rust-lang.org/unstable-book/language-features/doc-cfg.html)
//! in stable crates.
//!
//! Add the following to `Cargo.toml` to get started:
//!
//! ```toml,ignore
//! [dependencies]
//! doc-cfg = { version = "0.1" }
//!
//! [features]
//! unstable-doc-cfg = []
//!
//! [package.metadata.docs.rs]
//! features = ["unstable-doc-cfg"]
//! ```
//!
//! The name of the feature is important and should not be changed. Check out
//! [the full example for how to use it](http://arcnmx.github.io/doc-cfg/doc_cfg_example).
//!
//! The `unstable-doc-cfg` feature should only be turned on when documenting, the
//! `#[doc_cfg(..)]` attribute is otherwise identical to `#[cfg(..)]` when built
//! without it.

extern crate proc_macro;

use std::iter::FromIterator;
use proc_macro2::{TokenStream, TokenTree, Delimiter, Ident, Spacing};
use quote::quote;

/// The `#[doc_cfg(..)]` attribute works much like `#[cfg(..)]`, but it allows
/// the item being documented to show up in the crate documentation when built
/// on a platform or configuration that doesn't match the predicate.
///
/// It can be used like so:
///
/// ```no_run
/// #![cfg_attr(feature = "unstable-doc-cfg", feature(doc_cfg))]
///
/// use doc_cfg::doc_cfg;
///
/// #[doc_cfg(windows)]
/// pub fn cool_nonportable_fn() { }
/// ```
///
/// Check out [the full example to see how it looks](http://arcnmx.github.io/doc-cfg/doc_cfg_example).
///
/// ## `#[doc(cfg(..))]`
///
/// In cases where the predicate contains irrelevant implementation details or
/// private dependency names you can specify an alternate condition to be
/// included in the documentation:
///
/// ```no_run
/// #![cfg_attr(feature = "unstable-doc-cfg", feature(doc_cfg))]
///
/// use doc_cfg::doc_cfg;
///
/// #[doc_cfg(feature = "__private_feature")]
/// #[doc(cfg(feature = "cargo-feature-flag"))]
/// pub fn cool_fn() { }
/// ```
#[proc_macro_attribute]
pub fn doc_cfg(attr: proc_macro::TokenStream, input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    doc_cfg_(attr.into(), input.into(), needs_cfg_attr()).into()
}

fn needs_cfg_attr() -> bool {
    // TODO: when doc_cfg is stable, use rustc_version to decide whether to return false here
    true
}

fn doc_cfg_(attr: TokenStream, input: TokenStream, needs_cfg_attr: bool) -> TokenStream {
    if attr.clone().into_iter().next().is_none() {
        panic!("#[doc_cfg(..)] conditional missing");
    }

    let parsed = parse_item(input);

    let cfg = if needs_cfg_attr {
        quote! {
            #[cfg_attr(feature = "unstable-doc-cfg", cfg(any(#attr, rustdoc)))]
            #[cfg_attr(not(feature = "unstable-doc-cfg"), cfg(#attr))]
        }
    } else {
        quote! {
            #[cfg(any(#attr, rustdoc))]
        }
    };

    let doc_cfg = if parsed.doc_cfg.is_empty() {
        vec![quote! { #[doc(cfg(#attr))] }]
    } else {
        parsed.doc_cfg
    };

    let doc_cfg = doc_cfg.into_iter()
        .map(|doc_cfg| parse_cfg(doc_cfg).expect("internal doc_cfg parse error"))
        .map(|doc_cfg| if needs_cfg_attr {
            quote! {
                #[cfg_attr(feature = "unstable-doc-cfg", doc(cfg(#doc_cfg)))]
            }
        } else {
            quote! {
                #[doc(cfg(#doc_cfg))]
            }
        }).collect::<TokenStream>();

    let body = parsed.body;

    quote! {
        #doc_cfg
        #cfg
        #body
    }
}

fn parse_cfg_fn<I: IntoIterator<Item=TokenTree>>(cfg: I) -> Option<(Ident, TokenStream)> {
    let mut cfg = cfg.into_iter();

    if let TokenTree::Ident(id) = cfg.next()? {
        if let TokenTree::Group(group) = cfg.next()? {
            if group.delimiter() == Delimiter::Parenthesis && cfg.next().is_none() {
                return Some((id, group.stream()))
            }
        }
    }

    None
}

/// Extracts the inner expression from a #[doc(cfg(..))] attribute
fn parse_cfg<I: IntoIterator<Item=TokenTree>>(cfg: I) -> Option<TokenStream> {
    let mut cfg = cfg.into_iter();

    // Skip leading #
    let token = if let TokenTree::Punct(ref punct) = cfg.next()? {
        if punct.as_char() == '#' && punct.spacing() == Spacing::Alone {
            cfg.next()
        } else {
            None
        }
    } else {
        None
    }?;

    let group = if let TokenTree::Group(group) = token {
        Some(group)
    } else {
        None
    }?.stream();

    let (id, stream) = parse_cfg_fn(group)?;

    let (id, stream) = if &id == "doc" {
        parse_cfg_fn(stream)
    } else {
        None
    }?;

    if &id == "cfg" && cfg.next().is_none() {
        Some(stream)
    } else {
        None
    }
}

struct DocCfg {
    doc_cfg: Vec<TokenStream>,
    body: TokenStream,
}

fn parse_item(input: TokenStream) -> DocCfg {
    let mut doc_cfg_attrs = Vec::new();
    let mut output = Vec::new();
    let mut tokens = input.into_iter();

    let mut peek = tokens.next();
    while let Some(token) = peek.take() {
        peek = tokens.next();

        let is_doc_cfg = match (&token, &peek) {
            (TokenTree::Punct(ref punct), Some(TokenTree::Group(ref g)))
                if punct.as_char() == '#' => parse_cfg(vec![TokenTree::from(punct.clone()), g.clone().into()]).is_some(),
            _ => false,
        };

        if is_doc_cfg {
            if let Some(group) = peek.take() {
                doc_cfg_attrs.push(TokenStream::from_iter(vec![token, group]));
                peek = tokens.next();
            } else {
                unreachable!()
            }
        } else {
            output.push(token);
        }
    }

    DocCfg {
        doc_cfg: doc_cfg_attrs,
        body: TokenStream::from_iter(output),
    }
}

#[cfg(test)]
mod test {
    use quote::quote;
    use proc_macro2::{TokenStream, TokenTree};

    #[test]
    fn basic() {
        test(quote! {
            #[inline]
            fn test() { }
        }, quote! {
            #[cfg_attr(feature = "unstable-doc-cfg", doc(cfg(feature = "something")))]
            #[cfg_attr(feature = "unstable-doc-cfg", cfg(any(feature = "something", rustdoc)))]
            #[cfg_attr(not(feature = "unstable-doc-cfg"), cfg(feature = "something"))]
            #[inline]
            fn test() { }
        }, quote! {
            #[doc(cfg(feature = "something"))]
            #[cfg(any(feature = "something", rustdoc))]
            #[inline]
            fn test() { }
        }, quote! { feature = "something" });
    }

    #[test]
    fn custom_doc_cfg() {
        test(quote! {
            #[doc(cfg(feature = "somethingelse"))]
            fn test() { }
        }, quote! {
            #[cfg_attr(feature = "unstable-doc-cfg", doc(cfg(feature = "somethingelse")))]
            #[cfg_attr(feature = "unstable-doc-cfg", cfg(any(feature = "something", rustdoc)))]
            #[cfg_attr(not(feature = "unstable-doc-cfg"), cfg(feature = "something"))]
            fn test() { }
        }, quote! {
            #[doc(cfg(feature = "somethingelse"))]
            #[cfg(any(feature = "something", rustdoc))]
            fn test() { }
        }, quote! { feature = "something" });
    }

    #[test]
    fn multiple() {
        test(quote! {
            #[doc(cfg(feature = "something"))]
            #[inline]
            #[doc(cfg(feature = "somethingelse"))]
            fn test() { }
        }, quote! {
            #[cfg_attr(feature = "unstable-doc-cfg", doc(cfg(feature = "something")))]
            #[cfg_attr(feature = "unstable-doc-cfg", doc(cfg(feature = "somethingelse")))]
            #[cfg_attr(feature = "unstable-doc-cfg", cfg(any(all(feature = "something", feature = "somethingelse"), rustdoc)))]
            #[cfg_attr(not(feature = "unstable-doc-cfg"), cfg(all(feature = "something", feature = "somethingelse")))]
            #[inline]
            fn test() { }
        }, quote! {
            #[doc(cfg(feature = "something"))]
            #[doc(cfg(feature = "somethingelse"))]
            #[cfg(any(all(feature = "something", feature = "somethingelse"), rustdoc))]
            #[inline]
            fn test() { }
        }, quote! { all(feature = "something", feature = "somethingelse") });
    }

    #[test]
    #[should_panic]
    fn cfg_missing() {
        let _ = super::doc_cfg_(TokenStream::new(), quote! {
            fn test() { }
        }, true);
    }

    fn test(original: TokenStream, expected: TokenStream, expected_no_cfg_attr: TokenStream, attr: TokenStream) {
        let output = TokenStream::from(super::doc_cfg_(attr.clone(), original.clone(), true));
        compare(output, expected);

        let output = TokenStream::from(super::doc_cfg_(attr, original, false));
        compare(output, expected_no_cfg_attr);
    }

    fn compare(output: TokenStream, expected: TokenStream) {
        if !stream_eq(output.clone(), expected.clone()) {
            panic!("macro output mismatch\nexpected: {}\ngot     : {}", expected, output);
        }
    }

    fn stream_eq(lhs: TokenStream, rhs: TokenStream) -> bool {
        for (lhs, rhs) in lhs.into_iter().zip(rhs) {
            if !token_eq(&lhs, &rhs) {
                return false
            }
        }

        true
    }

    fn token_eq(lhs: &TokenTree, rhs: &TokenTree) -> bool {
        match (lhs, rhs) {
            (TokenTree::Group(lhs), TokenTree::Group(rhs)) if
                lhs.delimiter() == rhs.delimiter() && stream_eq(lhs.stream(), rhs.stream()) => true,
            (TokenTree::Punct(lhs), TokenTree::Punct(rhs)) if
                lhs.as_char() == rhs.as_char() && lhs.spacing() == rhs.spacing() => true,
            (TokenTree::Ident(lhs), TokenTree::Ident(rhs)) if
                lhs == rhs => true,
            (TokenTree::Literal(lhs), TokenTree::Literal(rhs)) if
                lhs.to_string() == rhs.to_string() => true,
            _ => false,
        }
    }
}