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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
// Copyright © SixtyFPS GmbH <info@sixtyfps.io>
// SPDX-License-Identifier: MIT OR Apache-2.0

/*!
Document your crate's feature flags.

This crates provides a macro that extracts "documentation" comments from Cargo.toml

To use this crate, add `#![doc = document_features::document_features!()]` in your crate documentation.
The `document_features!()` macro reads your `Cargo.toml` file, extracts feature comments and generates
a markdown string for your documentation.

Basic example:

```rust
//! Normal crate documentation goes here.
//!
//! ## Feature flags
#![doc = document_features::document_features!()]

// rest of the crate goes here.
```

## Documentation format:

The documentation of your crate features goes into `Cargo.toml`, where they are defined.

The `document_features!()` macro analyzes only the `[features]` section.
Similar to Rust's documentation comments `///` and `//!`, the macro understands
comments that start with `## ` and `#! `. Note the required trailing space.
Lines starting with `###` will not be understood as doc comment.

`## ` comments are meant to be *above* the feature they document.
There can be several `## ` comments, but they must always be followed by a
feature name, and no other `#! ` comments in between.

`#! ` comments are not associated with a particular feature, and will be printed
in where they occur. Use them to group features, for example.

## Examples:

*/
// Note: because rustdoc escapes the first `#` of a line starting with `#`,
// these docs comments have one more `#` ,
#![doc = self_test!(/**
[package]
name = "..."
## ...

[dependencies]
document-features = "0.1"
## ...

[features]
default = ["foo"]
##! This comments goes on top

### The foo feature enables the `foo` functions
foo = []

### The bar feature enables the bar module
bar = []

##! ### Experimental features
##! The following features are experimental

### Enable the fusion reactor
fusion = []
*/
=>
    /**
This comments goes on top
* **`foo`** *(enabled by default)* —  The foo feature enables the `foo` functions
* **`bar`** —  The bar feature enables the bar module
#### Experimental features
The following features are experimental
* **`fusion`** —  Enable the fusion reactor
*/
)]
/*!

## Compatibility

The minimum Rust version required to use this crate is Rust 1.54 because of the
feature to have macro in doc comments. You can make this crate optional and use
`#[cfg_attr()]` statements to enable it only when building the documentation:
You need to have two levels of `cfg_attr` because Rust < 1.54 doesn't parse the attribute
otherwise.

```rust,ignore
#![cfg_attr(
    feature = "document-features",
    cfg_attr(doc, doc = ::document_features::document_features!())
)]
```

In your Cargo.toml, enable this feature while generating the documentation on docs.rs:

```toml
[dependencies]
document-features = { version = "0.1", optional = true }

[package.metadata.docs.rs]
features = ["document-features"]
## Alternative: enable all features so they are all documented
## all-features = true
```
 */

extern crate proc_macro;
use proc_macro::TokenStream;

use std::collections::HashSet;
use std::fmt::Write;
use std::path::Path;
use std::str::FromStr;

fn error(e: &str) -> TokenStream {
    TokenStream::from_str(&format!("::core::compile_error!{{\"{}\"}}", e.escape_default())).unwrap()
}

#[proc_macro]
pub fn document_features(_: TokenStream) -> TokenStream {
    document_features_impl().unwrap_or_else(std::convert::identity)
}

fn document_features_impl() -> Result<TokenStream, TokenStream> {
    let path = std::env::var("CARGO_MANIFEST_DIR").unwrap();
    let mut cargo_toml = std::fs::read_to_string(Path::new(&path).join("Cargo.toml"))
        .map_err(|e| error(&format!("Can't open Cargo.toml: {:?}", e)))?;

    if !cargo_toml.contains("\n##") && !cargo_toml.contains("\n#!") {
        // On crates.io, Cargo.toml is usually "normalized" and stripped of all comments.
        // The original Cargo.toml has been renamed Cargo.toml.orig
        if let Ok(orig) = std::fs::read_to_string(Path::new(&path).join("Cargo.toml.orig")) {
            if orig.contains("##") || orig.contains("#!") {
                cargo_toml = orig;
            }
        }
    }

    let result = process_toml(&cargo_toml).map_err(|e| error(&e))?;
    Ok(std::iter::once(proc_macro::TokenTree::from(proc_macro::Literal::string(&result))).collect())
}

fn process_toml(cargo_toml: &str) -> Result<String, String> {
    // Get all lines between the "[features]" and the next block
    let lines = cargo_toml
        .lines()
        .map(str::trim)
        .skip_while(|l| !l.starts_with("[features]"))
        .skip(1) // skip the [features] line
        .take_while(|l| !l.starts_with("["))
        // and skip empty lines and comments that are not docs comments
        .filter(|l| {
            !l.is_empty() && (!l.starts_with("#") || l.starts_with("##") || l.starts_with("#!"))
        });
    let mut top_comment = String::new();
    let mut current_comment = String::new();
    let mut features = vec![];
    let mut default_features = HashSet::new();
    for line in lines {
        if let Some(x) = line.strip_prefix("#!") {
            if !x.is_empty() && !x.starts_with(" ") {
                continue; // it's not a doc comment
            }
            if !current_comment.is_empty() {
                return Err("Cannot mix ## and #! comments between features.".into());
            }
            writeln!(top_comment, "{}", x).unwrap();
        } else if let Some(x) = line.strip_prefix("##") {
            if !x.is_empty() && !x.starts_with(" ") {
                continue; // it's not a doc comment
            }
            writeln!(current_comment, "{}", x).unwrap();
        } else if let Some((dep, rest)) = line.split_once("=") {
            if dep.trim() == "default" {
                let defaults = rest
                    .trim()
                    .strip_prefix("[")
                    .and_then(|r| r.strip_suffix("]"))
                    .ok_or_else(|| format!("Parse error while parsing dependency {}", dep))?
                    .split(",")
                    .map(|d| d.trim().trim_matches(|c| c == '"' || c == '\'').trim())
                    .filter(|d| !d.is_empty());
                default_features.extend(defaults);
            } else {
                // Do not show features that do not have documentation
                if !current_comment.is_empty() {
                    features.push((
                        dep.trim(),
                        std::mem::take(&mut top_comment),
                        std::mem::take(&mut current_comment),
                    ));
                }
            }
        } else {
            return Err(format!("Parse error while processing the line:\n{}", line));
        }
    }
    if !current_comment.is_empty() {
        return Err("Found comment not associated with a feature".into());
    }
    if features.is_empty() {
        return Err("Could not find features in Cargo.toml".into());
    }
    let mut result = String::new();
    for (f, top, comment) in features {
        let default = if default_features.contains(f) { " *(enabled by default)*" } else { "" };
        if !comment.trim().is_empty() {
            write!(result, "{}* **`{}`**{} — {}", top, f, default, comment).unwrap();
        } else {
            writeln!(result, "{}* **`{}`**{}", top, f, default).unwrap();
        }
    }
    result += &top_comment;
    Ok(result)
}

#[cfg(feature = "self-test")]
#[proc_macro]
#[doc(hidden)]
/// Helper macro for the tests. Do not use
pub fn self_test_helper(input: TokenStream) -> TokenStream {
    process_toml((&input).to_string().trim_matches(|c| c == '"' || c == '#')).map_or_else(
        |e| error(&e),
        |r| std::iter::once(proc_macro::TokenTree::from(proc_macro::Literal::string(&r))).collect(),
    )
}

#[cfg(feature = "self-test")]
macro_rules! self_test {
    (#[doc = $toml:literal] => #[doc = $md:literal]) => {
        concat!(
            "\n`````rust\n\
            fn normalize_md(md : &str) -> String {
               md.lines().skip_while(|l| l.is_empty()).map(|l| l.trim())
                .collect::<Vec<_>>().join(\"\\n\")
            }
            assert_eq!(normalize_md(document_features::self_test_helper!(",
            stringify!($toml),
            ")), normalize_md(",
            stringify!($md),
            "));\n`````\n\n"
        )
    };
}

#[cfg(not(feature = "self-test"))]
macro_rules! self_test {
    (#[doc = $toml:literal] => #[doc = $md:literal]) => {
        concat!(
            "This contents in Cargo.toml:\n`````toml",
            $toml,
            "\n`````\n Generates the following:\n\
            <table><tr><th>Preview</th></tr><tr><td>\n\n",
            $md,
            "\n</td></tr></table>\n\n&nbsp;\n",
        )
    };
}

#[cfg(test)]
mod tests {
    use super::process_toml;

    #[track_caller]
    fn test_error(toml: &str, expected: &str) {
        let err = process_toml(toml).unwrap_err();
        assert!(err.contains(expected), "{:?} does not contain {:?}", err, expected)
    }

    #[test]
    fn parse_errors() {
        test_error(
            r#"
[features]
[dependencies]
foo = 4;
"#,
            "Could not find features",
        );

        test_error(
            r#"
[packages]
[dependencies]
"#,
            "Could not find features",
        );

        test_error(
            r#"
[features]
ff = []
abcd
efgh
[dependencies]
"#,
            "Parse error while processing the line:\nabcd",
        );

        test_error(
            r#"
[features]
## dd
## ff
#! ee
## ff
"#,
            "Cannot mix",
        );

        test_error(
            r#"
[features]
## dd
"#,
            "not associated with a feature",
        );

        test_error(
            r#"
[features]
# ff
foo = []
default = [
#ffff
# ff
"#,
            "Parse error while parsing dependency default",
        );
    }

    #[test]
    fn basic() {
        assert_eq!(
            process_toml(
                r#"
[abcd]
## aaa
#! aaa
[features]#xyz
#! abc
#
###
#! def
#!
## 123
## 456
feat1 = ["plop"]
#! ghi
no_doc = []
##
feat2 = ["momo"]
#! klm
default = ["feat1", "something_else"]
#! end
        "#
            )
            .unwrap(),
            " abc\n def\n\n* **`feat1`** *(enabled by default)* —  123\n 456\n ghi\n* **`feat2`**\n klm\n end\n"
        );
    }
}