summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDongHun Kwak <dh0128.kwak@samsung.com>2023-03-27 08:28:16 +0900
committerDongHun Kwak <dh0128.kwak@samsung.com>2023-03-27 08:28:16 +0900
commit201409143b85f76b1cf4f62085a88519a9fcea94 (patch)
tree33cad49992bbc5bbabe7de73d74d1815a9ad8828
downloadrust-document-features-201409143b85f76b1cf4f62085a88519a9fcea94.tar.gz
rust-document-features-201409143b85f76b1cf4f62085a88519a9fcea94.tar.bz2
rust-document-features-201409143b85f76b1cf4f62085a88519a9fcea94.zip
Import document-features 0.2.7upstream/0.2.7upstream
-rw-r--r--.cargo_vcs_info.json6
-rw-r--r--.github/workflows/rust.yml47
-rw-r--r--.gitignore2
-rw-r--r--CHANGELOG.md38
-rw-r--r--Cargo.toml40
-rw-r--r--Cargo.toml.orig27
-rw-r--r--LICENSE-APACHE73
-rw-r--r--LICENSE-MIT19
-rw-r--r--README.md43
-rw-r--r--lib.rs880
-rw-r--r--rustfmt.toml1
-rw-r--r--tests/self-doc.rs38
12 files changed, 1214 insertions, 0 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json
new file mode 100644
index 0000000..2cc8384
--- /dev/null
+++ b/.cargo_vcs_info.json
@@ -0,0 +1,6 @@
+{
+ "git": {
+ "sha1": "2f77c4e102d4546eb4a2291b396ed39c4533df1d"
+ },
+ "path_in_vcs": ""
+} \ No newline at end of file
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml
new file mode 100644
index 0000000..c85b8f5
--- /dev/null
+++ b/.github/workflows/rust.yml
@@ -0,0 +1,47 @@
+name: Rust
+
+on:
+ push:
+ branches: [ master ]
+ pull_request:
+ branches: [ master ]
+
+env:
+ CARGO_TERM_COLOR: always
+ RUSTFLAGS: -D warnings
+ RUST_BACKTRACE: 1
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ rust:
+ - stable
+ - 1.54.0
+ - nightly
+
+ steps:
+ - uses: actions/checkout@v2
+ - uses: actions-rs/toolchain@v1
+ with:
+ profile: minimal
+ toolchain: ${{ matrix.rust }}
+ override: true
+ - name: Run tests
+ run: cargo test --verbose --all-features
+ - name: Run docs
+ run: cargo doc --verbose
+ format:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v2
+ - name: Install latest stable
+ uses: actions-rs/toolchain@v1
+ with:
+ toolchain: stable
+ override: true
+ components: rustfmt
+ - name: Run rustfmt
+ run: cargo fmt --all -- --check
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..06aba01
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+Cargo.lock
+/target
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..aa4f453
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,38 @@
+# Changelog
+
+## 0.2.7 - 2002-12-21
+
+* Fix parsing of Cargo.toml with multi-line array of array (#16)
+
+## 0.2.6 - 2022-09-24
+
+* Fix parsing of escaped string literal in the macro arguments
+
+## 0.2.5 - 2022-09-17
+
+* Allow customization of the output with the `feature_label=` parameter
+
+## 0.2.4 - 2022-09-14
+
+* Fix dependencies or features written with quotes
+
+## 0.2.3 - 2022-08-15
+
+* Fix parsing of table with `#` within strings (#10)
+
+## 0.2.2 - 2022-07-25
+
+* Fix parsing of dependencies or feature spanning multiple lines (#9)
+
+## 0.2.1 - 2022-02-12
+
+* Fix indentation of multi-lines feature comments (#5)
+
+## 0.2.0 - 2022-02-11
+
+* Added ability to document optional features. (This is a breaking change in the
+ sense that previously ignored comments may now result in errors)
+
+## 0.1.0 - 2022-02-01
+
+Initial release
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..e7d6d33
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,40 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2018"
+name = "document-features"
+version = "0.2.7"
+authors = ["Slint Developers <info@slint-ui.com>"]
+description = "Extract documentation for the feature flags from comments in Cargo.toml"
+homepage = "https://slint-ui.com"
+readme = "README.md"
+keywords = [
+ "documentation",
+ "features",
+ "rustdoc",
+ "macro",
+]
+categories = ["development-tools"]
+license = "MIT OR Apache-2.0"
+repository = "https://github.com/slint-ui/document-features"
+
+[lib]
+path = "lib.rs"
+proc-macro = true
+
+[dependencies.litrs]
+version = "0.2.3"
+default-features = false
+
+[features]
+default = []
+self-test = []
diff --git a/Cargo.toml.orig b/Cargo.toml.orig
new file mode 100644
index 0000000..c4ba7a9
--- /dev/null
+++ b/Cargo.toml.orig
@@ -0,0 +1,27 @@
+# Copyright © SixtyFPS GmbH <info@sixtyfps.io>
+# SPDX-License-Identifier: MIT OR Apache-2.0
+
+[package]
+name = "document-features"
+version = "0.2.7"
+authors = ["Slint Developers <info@slint-ui.com>"]
+edition = "2018"
+license = "MIT OR Apache-2.0"
+repository = "https://github.com/slint-ui/document-features"
+homepage = "https://slint-ui.com"
+description = "Extract documentation for the feature flags from comments in Cargo.toml"
+categories = ["development-tools"]
+keywords = ["documentation", "features", "rustdoc", "macro"]
+
+[lib]
+proc-macro = true
+path = "lib.rs"
+
+[features]
+default = []
+
+## Internal feature used only for the tests, don't enable
+self-test = []
+
+[dependencies]
+litrs = { version = "0.2.3", default-features = false }
diff --git a/LICENSE-APACHE b/LICENSE-APACHE
new file mode 100644
index 0000000..137069b
--- /dev/null
+++ b/LICENSE-APACHE
@@ -0,0 +1,73 @@
+Apache License
+Version 2.0, January 2004
+http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
+
+"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
+
+"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
+
+"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
+
+"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
+
+"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
+
+"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
+
+"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
+
+"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
+
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
+
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/LICENSE-MIT b/LICENSE-MIT
new file mode 100644
index 0000000..13a82b2
--- /dev/null
+++ b/LICENSE-MIT
@@ -0,0 +1,19 @@
+Copyright (c) 2020 Olivier Goffart <ogoffart@sixtyfps.io>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..81fccc0
--- /dev/null
+++ b/README.md
@@ -0,0 +1,43 @@
+# Document your crate's feature flags
+
+[![Crates.io](https://img.shields.io/crates/v/document-features)](https://crates.io/crates/document-features)
+[![Documentation](https://docs.rs/document-features/badge.svg)](https://docs.rs/document-features/)
+
+This crate 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.
+
+Use `## ` and `#! ` comments in your Cargo.toml to document features, for example:
+
+```toml
+[dependencies]
+document-features = "0.2"
+## ...
+
+[features]
+## The foo feature enables the `foo` functions
+foo = []
+## The bar feature enables the [`bar`] module
+bar = []
+
+#! ### Experimental features
+#! The following features are experimental
+
+## Activate the fusion reactor
+fusion = []
+```
+
+These comments keep the feature definition and documentation next to each other, and they are then
+rendered into your crate documentation.
+
+Check out the [documentation](https://docs.rs/document-features/) for more details.
+
+## Contributions
+
+Contributions are welcome. We accept pull requests and bug reports.
+
+## License
+
+MIT OR Apache-2.0
diff --git a/lib.rs b/lib.rs
new file mode 100644
index 0000000..5ce0b50
--- /dev/null
+++ b/lib.rs
@@ -0,0 +1,880 @@
+// 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 the contents of `Cargo.toml`.
+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 or an optional dependency.
+There should not be `#! ` comments between the comment and the feature they document.
+
+`#! ` 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 = "..."
+## ...
+
+[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
+###
+### ⚠️ Can lead to explosions
+fusion = []
+
+[dependencies]
+document-features = "0.2"
+
+##! ### Optional dependencies
+
+### Enable this feature to implement the trait for the types from the genial crate
+genial = { version = "0.2", optional = true }
+
+### This awesome dependency is specified in its own table
+[dependencies.awesome]
+version = "1.3.5"
+optional = true
+*/
+=>
+ /**
+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
+
+ ⚠️ Can lead to explosions
+
+#### Optional dependencies
+* **`genial`** — Enable this feature to implement the trait for the types from the genial crate
+
+* **`awesome`** — This awesome dependency is specified in its own table
+
+*/
+)]
+/*!
+
+## Customization
+
+You can customize the formatting of the features in the generated documentation by setting
+the key **`feature_label=`** to a given format string. This format string must be either
+a [string literal](https://doc.rust-lang.org/reference/tokens.html#string-literals) or
+a [raw string literal](https://doc.rust-lang.org/reference/tokens.html#raw-string-literals).
+Every occurrence of `{feature}` inside the format string will be substituted with the name of the feature.
+
+For instance, to emulate the HTML formatting used by `rustdoc` one can use the following:
+
+```rust
+#![doc = document_features::document_features!(feature_label = r#"<span class="stab portability"><code>{feature}</code></span>"#)]
+```
+
+The default formatting is equivalent to:
+
+```rust
+#![doc = document_features::document_features!(feature_label = "**`{feature}`**")]
+```
+
+## 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.2", optional = true }
+
+[package.metadata.docs.rs]
+features = ["document-features"]
+## Alternative: enable all features so they are all documented
+## all-features = true
+```
+ */
+
+#[cfg(not(feature = "default"))]
+compile_error!(
+ "The feature `default` must be enabled to ensure \
+ forward compatibility with future version of this crate"
+);
+
+extern crate proc_macro;
+
+use proc_macro::{TokenStream, TokenTree};
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::convert::TryFrom;
+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()
+}
+
+fn compile_error(msg: &str, tt: Option<TokenTree>) -> TokenStream {
+ let span = tt.as_ref().map_or_else(proc_macro::Span::call_site, TokenTree::span);
+ use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing};
+ use std::iter::FromIterator;
+ TokenStream::from_iter(vec![
+ TokenTree::Ident(Ident::new("compile_error", span)),
+ TokenTree::Punct({
+ let mut punct = Punct::new('!', Spacing::Alone);
+ punct.set_span(span);
+ punct
+ }),
+ TokenTree::Group({
+ let mut group = Group::new(Delimiter::Brace, {
+ TokenStream::from_iter([TokenTree::Literal({
+ let mut string = Literal::string(msg);
+ string.set_span(span);
+ string
+ })])
+ });
+ group.set_span(span);
+ group
+ }),
+ ])
+}
+
+#[derive(Default)]
+struct Args {
+ feature_label: Option<String>,
+}
+
+fn parse_args(input: TokenStream) -> Result<Args, TokenStream> {
+ let mut token_trees = input.into_iter().fuse();
+
+ // parse the key, ensuring that it is the identifier `feature_label`
+ match token_trees.next() {
+ None => return Ok(Args::default()),
+ Some(TokenTree::Ident(ident)) if ident.to_string() == "feature_label" => (),
+ tt => return Err(compile_error("expected `feature_label`", tt)),
+ }
+
+ // parse a single equal sign `=`
+ match token_trees.next() {
+ Some(TokenTree::Punct(p)) if p.as_char() == '=' => (),
+ tt => return Err(compile_error("expected `=`", tt)),
+ }
+
+ // parse the value, ensuring that it is a string literal containing the substring `"{feature}"`
+ let feature_label;
+ if let Some(tt) = token_trees.next() {
+ match litrs::StringLit::<String>::try_from(&tt) {
+ Ok(string_lit) if string_lit.value().contains("{feature}") => {
+ feature_label = string_lit.value().to_string()
+ }
+ _ => {
+ return Err(compile_error(
+ "expected a string literal containing the substring \"{feature}\"",
+ Some(tt),
+ ))
+ }
+ }
+ } else {
+ return Err(compile_error(
+ "expected a string literal containing the substring \"{feature}\"",
+ None,
+ ));
+ }
+
+ // ensure there is nothing left after the format string
+ if let tt @ Some(_) = token_trees.next() {
+ return Err(compile_error("unexpected token after the format string", tt));
+ }
+
+ Ok(Args { feature_label: Some(feature_label) })
+}
+
+/// Produce a literal string containing documentation extracted from Cargo.toml
+///
+/// See the [crate] documentation for details
+#[proc_macro]
+pub fn document_features(tokens: TokenStream) -> TokenStream {
+ parse_args(tokens)
+ .and_then(|args| document_features_impl(&args))
+ .unwrap_or_else(std::convert::identity)
+}
+
+fn document_features_impl(args: &Args) -> 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, args).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, args: &Args) -> Result<String, String> {
+ // Get all lines between the "[features]" and the next block
+ let mut lines = cargo_toml
+ .lines()
+ .map(str::trim)
+ // 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();
+ let mut current_table = "";
+ while let Some(line) = lines.next() {
+ 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(table) = line.strip_prefix("[") {
+ current_table = table
+ .split_once("]")
+ .map(|(t, _)| t.trim())
+ .ok_or_else(|| format!("Parse error while parsing line: {}", line))?;
+ if !current_comment.is_empty() {
+ let dep = current_table
+ .rsplit_once(".")
+ .and_then(|(table, dep)| table.trim().ends_with("dependencies").then(|| dep))
+ .ok_or_else(|| format!("Not a feature: `{}`", line))?;
+ features.push((
+ dep.trim(),
+ std::mem::take(&mut top_comment),
+ std::mem::take(&mut current_comment),
+ ));
+ }
+ } else if let Some((dep, rest)) = line.split_once("=") {
+ let dep = dep.trim().trim_matches('"');
+ let rest = get_balanced(rest, &mut lines)
+ .map_err(|e| format!("Parse error while parsing value {}: {}", dep, e))?;
+ if current_table == "features" && dep == "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().to_string())
+ .filter(|d| !d.is_empty());
+ default_features.extend(defaults);
+ }
+ if !current_comment.is_empty() {
+ if current_table.ends_with("dependencies") {
+ if !rest
+ .split_once("optional")
+ .and_then(|(_, r)| r.trim().strip_prefix("="))
+ .map_or(false, |r| r.trim().starts_with("true"))
+ {
+ return Err(format!("Dependency {} is not an optional dependency", dep));
+ }
+ } else if current_table != "features" {
+ return Err(format!(
+ "Comment cannot be associated with a feature:{}",
+ current_comment
+ ));
+ }
+ features.push((
+ dep,
+ std::mem::take(&mut top_comment),
+ std::mem::take(&mut current_comment),
+ ));
+ }
+ }
+ }
+ if !current_comment.is_empty() {
+ return Err("Found comment not associated with a feature".into());
+ }
+ if features.is_empty() {
+ return Err("Could not find documented 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() {
+ if let Some(feature_label) = &args.feature_label {
+ writeln!(
+ result,
+ "{}* {}{} —{}",
+ top,
+ feature_label.replace("{feature}", f),
+ default,
+ comment
+ )
+ .unwrap();
+ } else {
+ writeln!(result, "{}* **`{}`**{} —{}", top, f, default, comment).unwrap();
+ }
+ } else {
+ if let Some(feature_label) = &args.feature_label {
+ writeln!(
+ result,
+ "{}* {}{}\n",
+ top,
+ feature_label.replace("{feature}", f),
+ default,
+ )
+ .unwrap();
+ } else {
+ writeln!(result, "{}* **`{}`**{}\n", top, f, default).unwrap();
+ }
+ }
+ }
+ result += &top_comment;
+ Ok(result)
+}
+
+fn get_balanced<'a>(
+ first_line: &'a str,
+ lines: &mut impl Iterator<Item = &'a str>,
+) -> Result<Cow<'a, str>, String> {
+ let mut line = first_line;
+ let mut result = Cow::from("");
+
+ let mut in_quote = false;
+ let mut level = 0;
+ loop {
+ let mut last_slash = false;
+ for (idx, b) in line.as_bytes().into_iter().enumerate() {
+ if last_slash {
+ last_slash = false
+ } else if in_quote {
+ match b {
+ b'\\' => last_slash = true,
+ b'"' | b'\'' => in_quote = false,
+ _ => (),
+ }
+ } else {
+ match b {
+ b'\\' => last_slash = true,
+ b'"' => in_quote = true,
+ b'{' | b'[' => level += 1,
+ b'}' | b']' if level == 0 => return Err("unbalanced source".into()),
+ b'}' | b']' => level -= 1,
+ b'#' => {
+ line = &line[..idx];
+ break;
+ }
+ _ => (),
+ }
+ }
+ }
+ if result.len() == 0 {
+ result = Cow::from(line);
+ } else {
+ *result.to_mut() += line;
+ }
+ if level == 0 {
+ return Ok(result);
+ }
+ line = if let Some(l) = lines.next() {
+ l
+ } else {
+ return Err("unbalanced source".into());
+ };
+ }
+}
+
+#[test]
+fn test_get_balanced() {
+ assert_eq!(
+ get_balanced(
+ "{",
+ &mut IntoIterator::into_iter(["a", "{ abc[], #ignore", " def }", "}", "xxx"])
+ ),
+ Ok("{a{ abc[], def }}".into())
+ );
+ assert_eq!(
+ get_balanced("{ foo = \"{#\" } #ignore", &mut IntoIterator::into_iter(["xxx"])),
+ Ok("{ foo = \"{#\" } ".into())
+ );
+ assert_eq!(
+ get_balanced("]", &mut IntoIterator::into_iter(["["])),
+ Err("unbalanced source".into())
+ );
+}
+
+#[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 == '#'), &Args::default())
+ .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",
+ )
+ };
+}
+
+// The following struct is inserted only during generation of the documentation in order to exploit doc-tests.
+// These doc-tests are used to check that invalid arguments to the `document_features!` macro cause a compile time error.
+// For a more principled way of testing compilation error, maybe investigate <https://docs.rs/trybuild>.
+//
+/// ```rust
+/// #![doc = document_features::document_features!()]
+/// #![doc = document_features::document_features!(feature_label = "**`{feature}`**")]
+/// #![doc = document_features::document_features!(feature_label = r"**`{feature}`**")]
+/// #![doc = document_features::document_features!(feature_label = r#"**`{feature}`**"#)]
+/// #![doc = document_features::document_features!(feature_label = "<span class=\"stab portability\"><code>{feature}</code></span>")]
+/// #![doc = document_features::document_features!(feature_label = r#"<span class="stab portability"><code>{feature}</code></span>"#)]
+/// ```
+/// ```compile_fail
+/// #![doc = document_features::document_features!(feature_label > "<span>{feature}</span>")]
+/// ```
+/// ```compile_fail
+/// #![doc = document_features::document_features!(label = "<span>{feature}</span>")]
+/// ```
+/// ```compile_fail
+/// #![doc = document_features::document_features!(feature_label = "{feat}")]
+/// ```
+/// ```compile_fail
+/// #![doc = document_features::document_features!(feature_label = 3.14)]
+/// ```
+/// ```compile_fail
+/// #![doc = document_features::document_features!(feature_label = )]
+/// ```
+/// ```compile_fail
+/// #![doc = document_features::document_features!(feature_label = "**`{feature}`**" extra)]
+/// ```
+#[cfg(doc)]
+struct FeatureLabelCompilationTest;
+
+#[cfg(test)]
+mod tests {
+ use super::{process_toml, Args};
+
+ #[track_caller]
+ fn test_error(toml: &str, expected: &str) {
+ let err = process_toml(toml, &Args::default()).unwrap_err();
+ assert!(err.contains(expected), "{:?} does not contain {:?}", err, expected)
+ }
+
+ #[test]
+ fn only_get_balanced_in_correct_table() {
+ process_toml(
+ r#"
+
+[package.metadata.release]
+pre-release-replacements = [
+ {test=\"\#\# \"},
+]
+[abcd]
+[features]#xyz
+#! abc
+#
+###
+#! def
+#!
+## 123
+## 456
+feat1 = ["plop"]
+#! ghi
+no_doc = []
+##
+feat2 = ["momo"]
+#! klm
+default = ["feat1", "something_else"]
+#! end
+ "#,
+ &Args::default(),
+ )
+ .unwrap();
+ }
+
+ #[test]
+ fn parse_error1() {
+ test_error(
+ r#"
+[features]
+[dependencies]
+foo = 4;
+"#,
+ "Could not find documented features",
+ );
+ }
+
+ #[test]
+ fn parse_error2() {
+ test_error(
+ r#"
+[packages]
+[dependencies]
+"#,
+ "Could not find documented features",
+ );
+ }
+
+ #[test]
+ fn parse_error3() {
+ test_error(
+ r#"
+[features]
+ff = []
+[abcd
+efgh
+[dependencies]
+"#,
+ "Parse error while parsing line: [abcd",
+ );
+ }
+
+ #[test]
+ fn parse_error4() {
+ test_error(
+ r#"
+[features]
+## dd
+## ff
+#! ee
+## ff
+"#,
+ "Cannot mix",
+ );
+ }
+
+ #[test]
+ fn parse_error5() {
+ test_error(
+ r#"
+[features]
+## dd
+"#,
+ "not associated with a feature",
+ );
+ }
+
+ #[test]
+ fn parse_error6() {
+ test_error(
+ r#"
+[features]
+# ff
+foo = []
+default = [
+#ffff
+# ff
+"#,
+ "Parse error while parsing value default",
+ );
+ }
+
+ #[test]
+ fn parse_error7() {
+ test_error(
+ r#"
+[features]
+# f
+foo = [ x = { ]
+bar = []
+"#,
+ "Parse error while parsing value foo",
+ );
+ }
+
+ #[test]
+ fn not_a_feature1() {
+ test_error(
+ r#"
+## hallo
+[features]
+"#,
+ "Not a feature: `[features]`",
+ );
+ }
+
+ #[test]
+ fn not_a_feature2() {
+ test_error(
+ r#"
+[package]
+## hallo
+foo = []
+"#,
+ "Comment cannot be associated with a feature: hallo",
+ );
+ }
+
+ #[test]
+ fn non_optional_dep1() {
+ test_error(
+ r#"
+[dev-dependencies]
+## Not optional
+foo = { version = "1.2", optional = false }
+"#,
+ "Dependency foo is not an optional dependency",
+ );
+ }
+
+ #[test]
+ fn non_optional_dep2() {
+ test_error(
+ r#"
+[dev-dependencies]
+## Not optional
+foo = { version = "1.2" }
+"#,
+ "Dependency foo is not an optional dependency",
+ );
+ }
+
+ #[test]
+ fn basic() {
+ let toml = r#"
+[abcd]
+[features]#xyz
+#! abc
+#
+###
+#! def
+#!
+## 123
+## 456
+feat1 = ["plop"]
+#! ghi
+no_doc = []
+##
+feat2 = ["momo"]
+#! klm
+default = ["feat1", "something_else"]
+#! end
+ "#;
+ let parsed = process_toml(toml, &Args::default()).unwrap();
+ assert_eq!(
+ parsed,
+ " abc\n def\n\n* **`feat1`** *(enabled by default)* — 123\n 456\n\n ghi\n* **`feat2`**\n\n klm\n end\n"
+ );
+ let parsed = process_toml(
+ toml,
+ &Args {
+ feature_label: Some(
+ "<span class=\"stab portability\"><code>{feature}</code></span>".into(),
+ ),
+ },
+ )
+ .unwrap();
+ assert_eq!(
+ parsed,
+ " abc\n def\n\n* <span class=\"stab portability\"><code>feat1</code></span> *(enabled by default)* — 123\n 456\n\n ghi\n* <span class=\"stab portability\"><code>feat2</code></span>\n\n klm\n end\n"
+ );
+ }
+
+ #[test]
+ fn dependencies() {
+ let toml = r#"
+#! top
+[dev-dependencies] #yo
+## dep1
+dep1 = { version="1.2", optional=true}
+#! yo
+dep2 = "1.3"
+## dep3
+[target.'cfg(unix)'.build-dependencies.dep3]
+version = "42"
+optional = true
+ "#;
+ let parsed = process_toml(toml, &Args::default()).unwrap();
+ assert_eq!(parsed, " top\n* **`dep1`** — dep1\n\n yo\n* **`dep3`** — dep3\n\n");
+ let parsed = process_toml(
+ toml,
+ &Args {
+ feature_label: Some(
+ "<span class=\"stab portability\"><code>{feature}</code></span>".into(),
+ ),
+ },
+ )
+ .unwrap();
+ assert_eq!(parsed, " top\n* <span class=\"stab portability\"><code>dep1</code></span> — dep1\n\n yo\n* <span class=\"stab portability\"><code>dep3</code></span> — dep3\n\n");
+ }
+
+ #[test]
+ fn multi_lines() {
+ let toml = r#"
+[package.metadata.foo]
+ixyz = [
+ ["array"],
+ [
+ "of",
+ "arrays"
+ ]
+]
+[dev-dependencies]
+## dep1
+dep1 = {
+ version="1.2-}",
+ optional=true
+}
+[features]
+default = [
+ "goo",
+ "\"]",
+ "bar",
+]
+## foo
+foo = [
+ "bar"
+]
+## bar
+bar = [
+
+]
+ "#;
+ let parsed = process_toml(toml, &Args::default()).unwrap();
+ assert_eq!(
+ parsed,
+ "* **`dep1`** — dep1\n\n* **`foo`** — foo\n\n* **`bar`** *(enabled by default)* — bar\n\n"
+ );
+ let parsed = process_toml(
+ toml,
+ &Args {
+ feature_label: Some(
+ "<span class=\"stab portability\"><code>{feature}</code></span>".into(),
+ ),
+ },
+ )
+ .unwrap();
+ assert_eq!(
+ parsed,
+ "* <span class=\"stab portability\"><code>dep1</code></span> — dep1\n\n* <span class=\"stab portability\"><code>foo</code></span> — foo\n\n* <span class=\"stab portability\"><code>bar</code></span> *(enabled by default)* — bar\n\n"
+ );
+ }
+
+ #[test]
+ fn dots_in_feature() {
+ let toml = r#"
+[features]
+## This is a test
+"teßt." = []
+default = ["teßt."]
+[dependencies]
+## A dep
+"dep" = { version = "123", optional = true }
+ "#;
+ let parsed = process_toml(toml, &Args::default()).unwrap();
+ assert_eq!(
+ parsed,
+ "* **`teßt.`** *(enabled by default)* — This is a test\n\n* **`dep`** — A dep\n\n"
+ );
+ let parsed = process_toml(
+ toml,
+ &Args {
+ feature_label: Some(
+ "<span class=\"stab portability\"><code>{feature}</code></span>".into(),
+ ),
+ },
+ )
+ .unwrap();
+ assert_eq!(
+ parsed,
+ "* <span class=\"stab portability\"><code>teßt.</code></span> *(enabled by default)* — This is a test\n\n* <span class=\"stab portability\"><code>dep</code></span> — A dep\n\n"
+ );
+ }
+}
diff --git a/rustfmt.toml b/rustfmt.toml
new file mode 100644
index 0000000..2a35f02
--- /dev/null
+++ b/rustfmt.toml
@@ -0,0 +1 @@
+use_small_heuristics = "Max"
diff --git a/tests/self-doc.rs b/tests/self-doc.rs
new file mode 100644
index 0000000..9364566
--- /dev/null
+++ b/tests/self-doc.rs
@@ -0,0 +1,38 @@
+#[test]
+fn ensure_it_compiles() {
+ document_features::document_features!();
+ document_features::document_features!(feature_label = "**`{feature}`**");
+ document_features::document_features!(feature_label = r"**`{feature}`**");
+ document_features::document_features!(feature_label = r#"**`{feature}`**"#);
+ document_features::document_features!(
+ feature_label = "<span class=\"stab portability\"><code>{feature}</code></span>"
+ );
+ document_features::document_features!(
+ feature_label = r#"<span class="stab portability"><code>{feature}</code></span>"#
+ );
+ document_features::document_features!(
+ feature_label = r##"<span class="stab portability"><code>{feature}</code></span>"##
+ );
+}
+
+#[test]
+fn self_doc() {
+ let actual = document_features::document_features!();
+ let expected =
+ "* **`self-test`** — Internal feature used only for the tests, don't enable\n\n";
+ assert_eq!(actual, expected);
+}
+
+#[test]
+fn self_doc_with_custom_label() {
+ let actual = document_features::document_features!(
+ feature_label = r#"<span class="stab portability"><code>{feature}</code></span>"#
+ );
+ let expected =
+ "* <span class=\"stab portability\"><code>self-test</code></span> — Internal feature used only for the tests, don't enable\n\n";
+ assert_eq!(actual, expected);
+ let actual2 = document_features::document_features!(
+ feature_label = "<span class=\"stab\u{0020}portability\"><code>{feature}</code></span>"
+ );
+ assert_eq!(actual2, expected);
+}