aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorChih-Hung Hsieh <chh@google.com>2020-10-21 01:19:47 -0700
committerChih-Hung Hsieh <chh@google.com>2020-10-21 01:40:17 -0700
commitfcfc9e618c6ba5265a91c242fb68343218fd5b61 (patch)
treeb9aad8dad8b06e64bc53f305f0c46134e4ecb718
parentd8d3e2ce34b7301dce39ce510bf8b0ede7b596d3 (diff)
downloadconst_fn-fcfc9e618c6ba5265a91c242fb68343218fd5b61.tar.gz
Import const_fn-0.4.2
Bug: 169611678 Test: make Change-Id: I1afe31e048749baadd86d44ff19eee0e159b3d0d
-rw-r--r--.cargo_vcs_info.json5
-rw-r--r--.editorconfig16
-rw-r--r--.gitattributes4
-rw-r--r--.github/CODEOWNERS1
-rw-r--r--.github/bors.toml2
-rw-r--r--.github/workflows/ci.yml127
-rw-r--r--.gitignore6
-rw-r--r--CHANGELOG.md116
-rw-r--r--Cargo.toml32
-rw-r--r--Cargo.toml.orig26
l---------LICENSE1
-rw-r--r--LICENSE-APACHE202
-rw-r--r--LICENSE-MIT23
-rw-r--r--METADATA19
-rw-r--r--MODULE_LICENSE_APACHE20
-rw-r--r--OWNERS1
-rw-r--r--README.md77
-rw-r--r--build.rs78
-rw-r--r--ci/check-minimal-versions.sh27
-rw-r--r--ci/install-component.sh22
-rw-r--r--ci/install-rust.sh13
-rw-r--r--rustfmt.toml27
-rw-r--r--src/ast.rs140
-rw-r--r--src/error.rs37
-rw-r--r--src/lib.rs221
-rw-r--r--src/to_tokens.rs36
-rw-r--r--src/utils.rs46
27 files changed, 1305 insertions, 0 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json
new file mode 100644
index 0000000..6c4b0a1
--- /dev/null
+++ b/.cargo_vcs_info.json
@@ -0,0 +1,5 @@
+{
+ "git": {
+ "sha1": "d306b29df53ab27a825e4213fc25f7e7aba493a6"
+ }
+}
diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 0000000..c93ffc7
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,16 @@
+# EditorConfig configuration
+# https://editorconfig.org
+
+# Top-most EditorConfig file
+root = true
+
+[*]
+end_of_line = lf
+insert_final_newline = true
+trim_trailing_whitespace = true
+charset = utf-8
+indent_style = space
+indent_size = 4
+
+[*.{json,yml,md}]
+indent_size = 2
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..45bca84
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,4 @@
+[attr]rust text eol=lf whitespace=tab-in-indent,trailing-space,tabwidth=4
+
+* text=auto eol=lf
+*.rs rust
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
new file mode 100644
index 0000000..2fdc28f
--- /dev/null
+++ b/.github/CODEOWNERS
@@ -0,0 +1 @@
+* @taiki-e
diff --git a/.github/bors.toml b/.github/bors.toml
new file mode 100644
index 0000000..1779788
--- /dev/null
+++ b/.github/bors.toml
@@ -0,0 +1,2 @@
+status = ["ci"]
+delete_merged_branches = true
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..63e3ab4
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,127 @@
+name: CI
+
+on:
+ pull_request:
+ push:
+ branches:
+ - master
+ - staging
+ - trying
+ schedule:
+ - cron: '00 01 * * *'
+
+env:
+ RUSTFLAGS: -Dwarnings
+ RUST_BACKTRACE: 1
+
+defaults:
+ run:
+ shell: bash
+
+jobs:
+ test:
+ name: test
+ strategy:
+ matrix:
+ rust:
+ # This is the minimum supported Rust version of this crate.
+ # When updating this, the reminder to update the minimum supported Rust version in README.md.
+ - 1.31.0
+ - 1.33.0
+ - 1.39.0
+ - 1.46.0
+ - stable
+ - beta
+ - nightly
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: Install Rust
+ run: |
+ . ./ci/install-rust.sh ${{ matrix.rust }}
+ - name: Install cargo-hack
+ if: matrix.rust == 'nightly'
+ run: |
+ cargo install cargo-hack
+ - name: cargo test
+ run: |
+ cargo test --all
+ - name: cargo check (minimal versions)
+ if: matrix.rust == 'nightly'
+ run: |
+ . ./ci/check-minimal-versions.sh
+
+ clippy:
+ name: clippy
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: Install Rust
+ run: |
+ . ./ci/install-rust.sh
+ - name: Install clippy
+ run: |
+ . ./ci/install-component.sh clippy
+ - name: cargo clippy
+ run: |
+ cargo clippy --all --all-features --all-targets
+
+ rustfmt:
+ name: rustfmt
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: Install Rust
+ run: |
+ . ./ci/install-rust.sh
+ - name: Install rustfmt
+ run: |
+ . ./ci/install-component.sh rustfmt
+ - name: cargo fmt --check
+ run: |
+ cargo fmt --all -- --check
+
+ rustdoc:
+ name: rustdoc
+ env:
+ RUSTDOCFLAGS: -Dwarnings
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - name: Install Rust
+ run: |
+ . ./ci/install-rust.sh
+ - name: cargo doc
+ run: |
+ cargo doc --no-deps --all --all-features
+
+ # These jobs don't actually test anything, but they're used to tell bors the
+ # build completed, as there is no practical way to detect when a workflow is
+ # successful listening to webhooks only.
+ #
+ # ALL THE PREVIOUS JOBS NEEDS TO BE ADDED TO THE `needs` SECTION OF THIS JOB!
+
+ ci-success:
+ name: ci
+ if: github.event_name == 'push' && success()
+ needs:
+ - test
+ - clippy
+ - rustfmt
+ - rustdoc
+ runs-on: ubuntu-latest
+ steps:
+ - name: Mark the job as a success
+ run: exit 0
+ ci-failure:
+ name: ci
+ if: github.event_name == 'push' && !success()
+ needs:
+ - test
+ - clippy
+ - rustfmt
+ - rustdoc
+ runs-on: ubuntu-latest
+ steps:
+ - name: Mark the job as a failure
+ run: exit 1
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..214d7a8
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,6 @@
+target
+Cargo.lock
+
+# For platform and editor specific settings, it is recommended to add to
+# a global .gitignore file.
+# Refs: https://help.github.com/en/articles/ignoring-files#create-a-global-gitignore
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..94890d8
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,116 @@
+# Changelog
+
+All notable changes to this project will be documented in this file.
+
+This project adheres to [Semantic Versioning](https://semver.org).
+
+## [Unreleased]
+
+## [0.4.2] - 2020-08-31
+
+* [Improve error messages when failed to parse version information.](https://github.com/taiki-e/const_fn/pull/26)
+
+## [0.4.1] - 2020-08-25
+
+* [Fix compile failure with non-cargo build systems.](https://github.com/taiki-e/const_fn/pull/23)
+
+## [0.4.0] - 2020-08-25
+
+* [Add support for version-based code generation.](https://github.com/taiki-e/const_fn/pull/17) The following conditions are available:
+
+ ```rust
+ use const_fn::const_fn;
+
+ // function is `const` on specified version and later compiler (including beta and nightly)
+ #[const_fn("1.36")]
+ pub const fn version() {
+ /* ... */
+ }
+
+ // function is `const` on nightly compiler (including dev build)
+ #[const_fn(nightly)]
+ pub const fn nightly() {
+ /* ... */
+ }
+
+ // function is `const` if `cfg(...)` is true
+ #[const_fn(cfg(...))]
+ pub const fn cfg() {
+ /* ... */
+ }
+
+ // function is `const` if `cfg(feature = "...")` is true
+ #[const_fn(feature = "...")]
+ pub const fn feature() {
+ /* ... */
+ }
+ ```
+
+* Improve compile time by removing proc-macro related dependencies ([#18](https://github.com/taiki-e/const_fn/pull/18), [#20](https://github.com/taiki-e/const_fn/pull/20)).
+
+## [0.3.1] - 2019-12-09
+
+* Updated `syn-mid` to 0.5.
+
+## [0.3.0] - 2019-10-20
+
+* `#[const_fn]` attribute may only be used on const functions.
+
+## [0.2.1] - 2019-08-15
+
+* Updated `proc-macro2`, `syn`, and `quote` to 1.0.
+
+* Updated `syn-mid` to 0.4.
+
+## [0.2.0] - 2019-06-16
+
+* Transition to Rust 2018. With this change, the minimum required version will go up to Rust 1.31.
+
+## [0.1.7] - 2019-02-18
+
+* Update syn-mid version to 0.3
+
+## [0.1.6] - 2019-02-15
+
+* Reduce compilation time
+
+## [0.1.5] - 2019-02-15
+
+* Revert 0.1.4
+
+## [0.1.4] - 2019-02-15 - YANKED
+
+* Reduce compilation time
+
+## [0.1.3] - 2019-01-06
+
+* Fix dependencies
+
+## [0.1.2] - 2018-12-27
+
+* Improve error messages
+
+## [0.1.1] - 2018-12-27
+
+* Improve an error message
+
+## [0.1.0] - 2018-12-25
+
+Initial release
+
+[Unreleased]: https://github.com/taiki-e/const_fn/compare/v0.4.2...HEAD
+[0.4.2]: https://github.com/taiki-e/const_fn/compare/v0.4.1...v0.4.2
+[0.4.1]: https://github.com/taiki-e/const_fn/compare/v0.4.0...v0.4.1
+[0.4.0]: https://github.com/taiki-e/const_fn/compare/v0.3.1...v0.4.0
+[0.3.1]: https://github.com/taiki-e/const_fn/compare/v0.3.0...v0.3.1
+[0.3.0]: https://github.com/taiki-e/const_fn/compare/v0.2.1...v0.3.0
+[0.2.1]: https://github.com/taiki-e/const_fn/compare/v0.2.0...v0.2.1
+[0.2.0]: https://github.com/taiki-e/const_fn/compare/v0.1.7...v0.2.0
+[0.1.7]: https://github.com/taiki-e/const_fn/compare/v0.1.6...v0.1.7
+[0.1.6]: https://github.com/taiki-e/const_fn/compare/v0.1.5...v0.1.6
+[0.1.5]: https://github.com/taiki-e/const_fn/compare/v0.1.4...v0.1.5
+[0.1.4]: https://github.com/taiki-e/const_fn/compare/v0.1.3...v0.1.4
+[0.1.3]: https://github.com/taiki-e/const_fn/compare/v0.1.2...v0.1.3
+[0.1.2]: https://github.com/taiki-e/const_fn/compare/v0.1.1...v0.1.2
+[0.1.1]: https://github.com/taiki-e/const_fn/compare/v0.1.0...v0.1.1
+[0.1.0]: https://github.com/taiki-e/const_fn/releases/tag/v0.1.0
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..312f02b
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,32 @@
+# 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 believe there's an error in this file please file an
+# issue against the rust-lang/cargo repository. If you're
+# editing this file be aware that the upstream Cargo.toml
+# will likely look very different (and much more reasonable)
+
+[package]
+edition = "2018"
+name = "const_fn"
+version = "0.4.2"
+authors = ["Taiki Endo <te316e89@gmail.com>"]
+description = "An attribute for easy generation of const functions with conditional compilations.\n"
+homepage = "https://github.com/taiki-e/const_fn"
+documentation = "https://docs.rs/const_fn"
+readme = "README.md"
+keywords = ["macros", "attribute", "const", "static"]
+categories = ["rust-patterns", "no-std"]
+license = "Apache-2.0 OR MIT"
+repository = "https://github.com/taiki-e/const_fn"
+[package.metadata.docs.rs]
+targets = ["x86_64-unknown-linux-gnu"]
+
+[lib]
+proc-macro = true
+
+[dependencies]
diff --git a/Cargo.toml.orig b/Cargo.toml.orig
new file mode 100644
index 0000000..fe9e6f0
--- /dev/null
+++ b/Cargo.toml.orig
@@ -0,0 +1,26 @@
+[package]
+name = "const_fn"
+version = "0.4.2"
+authors = ["Taiki Endo <te316e89@gmail.com>"]
+edition = "2018"
+license = "Apache-2.0 OR MIT"
+repository = "https://github.com/taiki-e/const_fn"
+homepage = "https://github.com/taiki-e/const_fn"
+documentation = "https://docs.rs/const_fn"
+keywords = ["macros", "attribute", "const", "static"]
+categories = ["rust-patterns", "no-std"]
+readme = "README.md"
+description = """
+An attribute for easy generation of const functions with conditional compilations.
+"""
+
+[package.metadata.docs.rs]
+targets = ["x86_64-unknown-linux-gnu"]
+
+[workspace]
+members = ["test_suite"]
+
+[lib]
+proc-macro = true
+
+[dependencies]
diff --git a/LICENSE b/LICENSE
new file mode 120000
index 0000000..6b579aa
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1 @@
+LICENSE-APACHE \ No newline at end of file
diff --git a/LICENSE-APACHE b/LICENSE-APACHE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/LICENSE-APACHE
@@ -0,0 +1,202 @@
+
+ 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..31aa793
--- /dev/null
+++ b/LICENSE-MIT
@@ -0,0 +1,23 @@
+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/METADATA b/METADATA
new file mode 100644
index 0000000..d499a12
--- /dev/null
+++ b/METADATA
@@ -0,0 +1,19 @@
+name: "const_fn"
+description: "An attribute for easy generation of const functions with conditional compilations."
+third_party {
+ url {
+ type: HOMEPAGE
+ value: "https://crates.io/crates/const_fn"
+ }
+ url {
+ type: ARCHIVE
+ value: "https://static.crates.io/crates/const_fn/const_fn-0.4.2.crate"
+ }
+ version: "0.4.2"
+ license_type: NOTICE
+ last_upgrade_date {
+ year: 2020
+ month: 10
+ day: 21
+ }
+}
diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/MODULE_LICENSE_APACHE2
diff --git a/OWNERS b/OWNERS
new file mode 100644
index 0000000..46fc303
--- /dev/null
+++ b/OWNERS
@@ -0,0 +1 @@
+include platform/prebuilts/rust:/OWNERS
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..325b789
--- /dev/null
+++ b/README.md
@@ -0,0 +1,77 @@
+# \#\[const\_fn\]
+
+[![crates-badge]][crates-url]
+[![docs-badge]][docs-url]
+[![license-badge]][license]
+[![rustc-badge]][rustc-url]
+
+[crates-badge]: https://img.shields.io/crates/v/const_fn.svg
+[crates-url]: https://crates.io/crates/const_fn
+[docs-badge]: https://docs.rs/const_fn/badge.svg
+[docs-url]: https://docs.rs/const_fn
+[license-badge]: https://img.shields.io/badge/license-Apache--2.0%20OR%20MIT-blue.svg
+[license]: #license
+[rustc-badge]: https://img.shields.io/badge/rustc-1.31+-lightgray.svg
+[rustc-url]: https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-2018.html
+
+An attribute for easy generation of const functions with conditional compilations.
+
+## Usage
+
+Add this to your `Cargo.toml`:
+
+```toml
+[dependencies]
+const_fn = "0.4"
+```
+
+The current const_fn requires Rust 1.31 or later.
+
+## Examples
+
+```rust
+use const_fn::const_fn;
+
+// function is `const` on specified version and later compiler (including beta and nightly)
+#[const_fn("1.36")]
+pub const fn version() {
+ /* ... */
+}
+
+// function is `const` on nightly compiler (including dev build)
+#[const_fn(nightly)]
+pub const fn nightly() {
+ /* ... */
+}
+
+// function is `const` if `cfg(...)` is true
+#[const_fn(cfg(...))]
+pub const fn cfg() {
+ /* ... */
+}
+
+// function is `const` if `cfg(feature = "...")` is true
+#[const_fn(feature = "...")]
+pub const fn feature() {
+ /* ... */
+}
+```
+
+## Alternatives
+
+This crate is proc-macro, but is very lightweight, and has no dependencies.
+
+You can manually define declarative macros with similar functionality (see [`if_rust_version`](https://github.com/ogoffart/if_rust_version#examples)), or [you can define the same function twice with different cfg](https://github.com/crossbeam-rs/crossbeam/blob/0b6ea5f69fde8768c1cfac0d3601e0b4325d7997/crossbeam-epoch/src/atomic.rs#L340-L372). (Note: the former approach requires more macros to be defined depending on the number of version requirements, the latter approach requires more functions to be maintained manually)
+
+## License
+
+Licensed under either of
+
+* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
+* MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
+
+at your option.
+
+### Contribution
+
+Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
diff --git a/build.rs b/build.rs
new file mode 100644
index 0000000..758b390
--- /dev/null
+++ b/build.rs
@@ -0,0 +1,78 @@
+use std::{
+ env, fs,
+ path::{Path, PathBuf},
+ process::Command,
+ str,
+};
+
+// The rustc-cfg strings below are *not* public API. Please let us know by
+// opening a GitHub issue if your build environment requires some way to enable
+// these cfgs other than by executing our build script.
+fn main() {
+ println!("cargo:rustc-cfg=const_fn_has_build_script");
+
+ let rustc = env::var_os("RUSTC").map_or_else(|| "rustc".into(), PathBuf::from);
+ let version = match Version::from_rustc(&rustc) {
+ Ok(version) => format!("{:#?}\n", version),
+ Err(e) => panic!("{}", e),
+ };
+
+ let out_dir = env::var_os("OUT_DIR").map(PathBuf::from).expect("OUT_DIR not set");
+ let out_file = out_dir.join("version.rs");
+ fs::write(out_file, version).expect("failed to write version.rs");
+}
+
+#[derive(Debug)]
+struct Version {
+ minor: u16,
+ patch: u16,
+ nightly: bool,
+}
+
+// Based on https://github.com/cuviper/autocfg/blob/1.0.1/src/version.rs
+//
+// Using our own parser instead of the existing crates to generate better errors.
+impl Version {
+ // from the verbose version output
+ fn from_vv(vv: &str) -> Option<Self> {
+ // Find the release line in the verbose version output.
+ let release = vv
+ .lines()
+ .find(|line| line.starts_with("release: "))
+ .map(|line| &line["release: ".len()..])?;
+
+ // Split the version and channel info.
+ let mut version_channel = release.split('-');
+ let version = version_channel.next().unwrap();
+ let channel = version_channel.next();
+
+ // Split the version into semver components.
+ let mut digits = version.splitn(3, '.');
+ let major = digits.next()?;
+ if major != "1" {
+ return None;
+ }
+ let minor = digits.next()?.parse().ok()?;
+ let patch = digits.next().unwrap_or("0").parse().ok()?;
+
+ let nightly = channel.map_or(false, |c| c == "dev" || c == "nightly");
+ Some(Version { minor, patch, nightly })
+ }
+
+ fn from_rustc(rustc: &Path) -> Result<Self, String> {
+ let output =
+ Command::new(rustc).args(&["--version", "--verbose"]).output().map_err(|e| {
+ format!("failed to run `{} --version --verbose`: {}", rustc.display(), e)
+ })?;
+ if !output.status.success() {
+ return Err("could not execute rustc".to_string());
+ }
+ let output = str::from_utf8(&output.stdout).map_err(|e| {
+ format!("failed to parse output of `{} --version --verbose`: {}", rustc.display(), e)
+ })?;
+
+ Self::from_vv(output).ok_or_else(|| {
+ format!("unexpected output from `{} --version --verbose`: {}", rustc.display(), output)
+ })
+ }
+}
diff --git a/ci/check-minimal-versions.sh b/ci/check-minimal-versions.sh
new file mode 100644
index 0000000..6152c15
--- /dev/null
+++ b/ci/check-minimal-versions.sh
@@ -0,0 +1,27 @@
+#!/bin/bash
+# Check all public crates with minimal version dependencies.
+#
+# Note that this script modifies Cargo.toml and Cargo.lock while this script is
+# running, and it is an error if there are any unstaged changes.
+#
+# Refs:
+# * minimal versions: https://github.com/rust-lang/cargo/issues/5657
+# * features 2.0: https://github.com/rust-lang/cargo/issues/8088
+
+set -euo pipefail
+
+# This script modifies Cargo.toml and Cargo.lock, so make sure there are no
+# unstaged changes.
+git diff --exit-code
+
+# Remove dev-dependencies from Cargo.toml to prevent the next `cargo update`
+# from determining minimal versions based on dev-dependencies.
+cargo hack --remove-dev-deps --workspace
+
+# Update Cargo.lock to minimal version dependencies.
+cargo update -Zminimal-versions
+# Run check for all public members of the workspace.
+cargo hack check --workspace --all-features --ignore-private -Zfeatures=all
+
+# Restore original Cargo.toml and Cargo.lock.
+git checkout .
diff --git a/ci/install-component.sh b/ci/install-component.sh
new file mode 100644
index 0000000..9aaa5ce
--- /dev/null
+++ b/ci/install-component.sh
@@ -0,0 +1,22 @@
+#!/bin/bash
+
+set -euo pipefail
+
+component="${1}"
+
+if ! rustup component add "${component}" 2>/dev/null; then
+ # If the component is unavailable on the latest nightly,
+ # use the latest toolchain with the component available.
+ # Refs: https://github.com/rust-lang/rustup-components-history#the-web-part
+ target=$(curl -sSf "https://rust-lang.github.io/rustup-components-history/x86_64-unknown-linux-gnu/${component}")
+ echo "'${component}' is unavailable on the default toolchain, use the toolchain 'nightly-${target}' instead"
+
+ . ci/install-rust.sh "nightly-${target}"
+
+ rustup component add "${component}"
+fi
+
+case "${component}" in
+ rustfmt) "${component}" -V ;;
+ *) cargo "${component}" -V ;;
+esac
diff --git a/ci/install-rust.sh b/ci/install-rust.sh
new file mode 100644
index 0000000..b6625b6
--- /dev/null
+++ b/ci/install-rust.sh
@@ -0,0 +1,13 @@
+#!/bin/bash
+
+set -euo pipefail
+
+toolchain="${1:-nightly}"
+
+rustup set profile minimal
+rustup update "${toolchain}" --no-self-update
+rustup default "${toolchain}"
+
+rustup -V
+rustc -V
+cargo -V
diff --git a/rustfmt.toml b/rustfmt.toml
new file mode 100644
index 0000000..18c6d2a
--- /dev/null
+++ b/rustfmt.toml
@@ -0,0 +1,27 @@
+# Rustfmt configuration
+# https://github.com/rust-lang/rustfmt/blob/master/Configurations.md
+
+# This is required for bug-fixes, which technically can't be made to the stable
+# first version.
+# This is unstable (tracking issue: https://github.com/rust-lang/rustfmt/issues/3383).
+version = "Two"
+# This is unstable (tracking issue: https://github.com/rust-lang/rustfmt/issues/3391)
+error_on_line_overflow = true
+
+# Override the default formatting style.
+# See https://internals.rust-lang.org/t/running-rustfmt-on-rust-lang-rust-and-other-rust-lang-repositories/8732/81.
+use_small_heuristics = "Max"
+# See https://github.com/rust-dev-tools/fmt-rfcs/issues/149.
+# This is unstable (tracking issue: https://github.com/rust-lang/rustfmt/issues/3370)
+overflow_delimited_expr = true
+
+# Apply rustfmt to more places.
+# This is unstable (tracking issue: https://github.com/rust-lang/rustfmt/issues/3362).
+merge_imports = true
+# This is unstable (tracking issue: https://github.com/rust-lang/rustfmt/issues/3348).
+format_code_in_doc_comments = true
+
+# Set the default settings again to always apply the proper formatting without
+# being affected by the editor settings.
+edition = "2018"
+tab_spaces = 4
diff --git a/src/ast.rs b/src/ast.rs
new file mode 100644
index 0000000..b9acee5
--- /dev/null
+++ b/src/ast.rs
@@ -0,0 +1,140 @@
+use proc_macro::{Delimiter, Literal, Span, TokenStream, TokenTree};
+use std::iter::Peekable;
+
+use crate::{
+ to_tokens::ToTokens,
+ utils::{parse_as_empty, tt_span},
+ Result,
+};
+
+pub(crate) struct Func {
+ pub(crate) attrs: Vec<Attribute>,
+ pub(crate) sig: Vec<TokenTree>,
+ pub(crate) body: TokenTree,
+ pub(crate) print_const: bool,
+}
+
+pub(crate) fn parse_input(input: TokenStream) -> Result<Func> {
+ let mut input = input.into_iter().peekable();
+
+ let attrs = parse_attrs(&mut input)?;
+ let sig = parse_signature(&mut input);
+ let body = input.next();
+ parse_as_empty(input)?;
+
+ if body.is_none()
+ || !sig
+ .iter()
+ .any(|tt| if let TokenTree::Ident(i) = tt { i.to_string() == "fn" } else { false })
+ {
+ return Err(error!(
+ Span::call_site(),
+ "#[const_fn] attribute may only be used on functions"
+ ));
+ }
+ if !sig
+ .iter()
+ .any(|tt| if let TokenTree::Ident(i) = tt { i.to_string() == "const" } else { false })
+ {
+ let span = sig
+ .iter()
+ .position(|tt| if let TokenTree::Ident(i) = tt { i.to_string() == "fn" } else { false })
+ .map(|i| sig[i].span())
+ .unwrap();
+ return Err(error!(span, "#[const_fn] attribute may only be used on const functions"));
+ }
+
+ Ok(Func { attrs, sig, body: body.unwrap(), print_const: true })
+}
+
+impl ToTokens for Func {
+ fn to_tokens(&self, tokens: &mut TokenStream) {
+ self.attrs.iter().for_each(|attr| attr.to_tokens(tokens));
+ if self.print_const {
+ self.sig.iter().for_each(|attr| attr.to_tokens(tokens));
+ } else {
+ self.sig
+ .iter()
+ .filter(
+ |tt| if let TokenTree::Ident(i) = tt { i.to_string() != "const" } else { true },
+ )
+ .for_each(|tt| tt.to_tokens(tokens));
+ }
+ self.body.to_tokens(tokens);
+ }
+}
+
+fn parse_signature(input: &mut Peekable<impl Iterator<Item = TokenTree>>) -> Vec<TokenTree> {
+ let mut sig = Vec::new();
+ loop {
+ match input.peek() {
+ Some(TokenTree::Group(group)) if group.delimiter() == Delimiter::Brace => break,
+ None => break,
+ _ => sig.push(input.next().unwrap()),
+ }
+ }
+ sig
+}
+
+fn parse_attrs(input: &mut Peekable<impl Iterator<Item = TokenTree>>) -> Result<Vec<Attribute>> {
+ let mut attrs = Vec::new();
+ loop {
+ let pound_token = match input.peek() {
+ Some(TokenTree::Punct(p)) if p.as_char() == '#' => input.next().unwrap(),
+ _ => break,
+ };
+ let group = match input.peek() {
+ Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Bracket => {
+ input.next().unwrap()
+ }
+ tt => return Err(error!(tt_span(tt), "expected `[`")),
+ };
+ attrs.push(Attribute { pound_token, group });
+ }
+ Ok(attrs)
+}
+
+pub(crate) struct Attribute {
+ // `#`
+ pub(crate) pound_token: TokenTree,
+ // `[...]`
+ pub(crate) group: TokenTree,
+}
+
+impl ToTokens for Attribute {
+ fn to_tokens(&self, tokens: &mut TokenStream) {
+ self.pound_token.to_tokens(tokens);
+ self.group.to_tokens(tokens);
+ }
+}
+
+pub(crate) struct LitStr {
+ token: Literal,
+ value: String,
+}
+
+impl LitStr {
+ pub(crate) fn new(token: &Literal) -> Result<Self> {
+ let value = token.to_string();
+ // unlike `syn::LitStr`, only accepts `"..."`
+ if value.starts_with('"') && value.ends_with('"') {
+ Ok(Self { token: token.clone(), value })
+ } else {
+ Err(error!(token.span(), "expected string literal"))
+ }
+ }
+
+ pub(crate) fn value(&self) -> &str {
+ &self.value[1..self.value.len() - 1]
+ }
+
+ pub(crate) fn span(&self) -> Span {
+ self.token.span()
+ }
+}
+
+impl ToTokens for LitStr {
+ fn to_tokens(&self, tokens: &mut TokenStream) {
+ self.token.to_tokens(tokens);
+ }
+}
diff --git a/src/error.rs b/src/error.rs
new file mode 100644
index 0000000..bd3ea92
--- /dev/null
+++ b/src/error.rs
@@ -0,0 +1,37 @@
+use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree};
+use std::{fmt, iter::FromIterator};
+
+pub(crate) struct Error {
+ span: Span,
+ msg: String,
+}
+
+impl Error {
+ pub(crate) fn new(span: Span, msg: impl fmt::Display) -> Self {
+ Error { span, msg: msg.to_string() }
+ }
+
+ // https://github.com/dtolnay/syn/blob/1.0.39/src/error.rs#L218-L237
+ pub(crate) fn to_compile_error(&self) -> TokenStream {
+ // compile_error!($msg)
+ TokenStream::from_iter(vec![
+ TokenTree::Ident(Ident::new("compile_error", self.span)),
+ TokenTree::Punct({
+ let mut punct = Punct::new('!', Spacing::Alone);
+ punct.set_span(self.span);
+ punct
+ }),
+ TokenTree::Group({
+ let mut group = Group::new(Delimiter::Brace, {
+ TokenStream::from_iter(vec![TokenTree::Literal({
+ let mut string = Literal::string(&self.msg);
+ string.set_span(self.span);
+ string
+ })])
+ });
+ group.set_span(self.span);
+ group
+ }),
+ ])
+ }
+}
diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644
index 0000000..e453950
--- /dev/null
+++ b/src/lib.rs
@@ -0,0 +1,221 @@
+//! An attribute for easy generation of const functions with conditional compilations.
+//!
+//! # Examples
+//!
+//! ```rust
+//! use const_fn::const_fn;
+//!
+//! // function is `const` on specified version and later compiler (including beta and nightly)
+//! #[const_fn("1.36")]
+//! pub const fn version() {
+//! /* ... */
+//! }
+//!
+//! // function is `const` on nightly compiler (including dev build)
+//! #[const_fn(nightly)]
+//! pub const fn nightly() {
+//! /* ... */
+//! }
+//!
+//! // function is `const` if `cfg(...)` is true
+//! # #[cfg(any())]
+//! #[const_fn(cfg(...))]
+//! # pub fn _cfg() { unimplemented!() }
+//! pub const fn cfg() {
+//! /* ... */
+//! }
+//!
+//! // function is `const` if `cfg(feature = "...")` is true
+//! #[const_fn(feature = "...")]
+//! pub const fn feature() {
+//! /* ... */
+//! }
+//! ```
+//!
+//! # Alternatives
+//!
+//! This crate is proc-macro, but is very lightweight, and has no dependencies.
+//!
+//! You can manually define declarative macros with similar functionality (see [`if_rust_version`](https://github.com/ogoffart/if_rust_version#examples)), or [you can define the same function twice with different cfg](https://github.com/crossbeam-rs/crossbeam/blob/0b6ea5f69fde8768c1cfac0d3601e0b4325d7997/crossbeam-epoch/src/atomic.rs#L340-L372).
+//! (Note: the former approach requires more macros to be defined depending on the number of version requirements, the latter approach requires more functions to be maintained manually)
+
+#![doc(html_root_url = "https://docs.rs/const_fn/0.4.2")]
+#![doc(test(
+ no_crate_inject,
+ attr(deny(warnings, rust_2018_idioms, single_use_lifetimes), allow(dead_code))
+))]
+#![forbid(unsafe_code)]
+#![warn(rust_2018_idioms, single_use_lifetimes, unreachable_pub)]
+#![warn(clippy::all, clippy::default_trait_access)]
+// mem::take and #[non_exhaustive] requires Rust 1.40
+#![allow(clippy::mem_replace_with_default, clippy::manual_non_exhaustive)]
+
+// older compilers require explicit `extern crate`.
+#[allow(unused_extern_crates)]
+extern crate proc_macro;
+
+#[macro_use]
+mod utils;
+
+mod ast;
+mod error;
+mod to_tokens;
+
+use proc_macro::{Delimiter, TokenStream, TokenTree};
+use std::str::FromStr;
+
+use crate::{
+ error::Error,
+ to_tokens::ToTokens,
+ utils::{cfg_attrs, parse_as_empty, tt_span},
+};
+
+type Result<T, E = Error> = std::result::Result<T, E>;
+
+/// An attribute for easy generation of const functions with conditional compilations.
+/// See crate level documentation for details.
+#[proc_macro_attribute]
+pub fn const_fn(args: TokenStream, input: TokenStream) -> TokenStream {
+ let arg = match parse_arg(args) {
+ Ok(a) => a,
+ Err(e) => return e.to_compile_error(),
+ };
+ let mut func = match ast::parse_input(input) {
+ Ok(i) => i,
+ Err(e) => return e.to_compile_error(),
+ };
+
+ match arg {
+ Arg::Cfg(c) => {
+ let (mut tokens, cfg_not) = cfg_attrs(c);
+ tokens.extend(func.to_token_stream());
+ tokens.extend(cfg_not);
+ func.print_const = false;
+ tokens.extend(func.to_token_stream());
+ tokens
+ }
+ Arg::Feature(f) => {
+ let (mut tokens, cfg_not) = cfg_attrs(f);
+ tokens.extend(func.to_token_stream());
+ tokens.extend(cfg_not);
+ func.print_const = false;
+ tokens.extend(func.to_token_stream());
+ tokens
+ }
+ Arg::Version(req) => {
+ if req.major > 1 || VERSION.as_ref().map_or(true, |v| req.minor > v.minor) {
+ func.print_const = false;
+ }
+ func.to_token_stream()
+ }
+ Arg::Nightly => {
+ if VERSION.as_ref().map_or(true, |v| !v.nightly) {
+ func.print_const = false;
+ }
+ func.to_token_stream()
+ }
+ }
+}
+
+enum Arg {
+ // `const_fn("...")`
+ Version(VersionReq),
+ // `const_fn(nightly)`
+ Nightly,
+ // `const_fn(cfg(...))`
+ Cfg(TokenStream),
+ // `const_fn(feature = "...")`
+ Feature(TokenStream),
+}
+
+fn parse_arg(tokens: TokenStream) -> Result<Arg> {
+ let tokens2 = tokens.clone();
+ let mut iter = tokens.into_iter();
+
+ let next = iter.next();
+ match &next {
+ Some(TokenTree::Ident(i)) => match i.to_string().as_str() {
+ "nightly" => {
+ parse_as_empty(iter)?;
+ return Ok(Arg::Nightly);
+ }
+ "cfg" => {
+ return match iter.next().as_ref() {
+ Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Parenthesis => {
+ parse_as_empty(iter)?;
+ Ok(Arg::Cfg(g.stream()))
+ }
+ tt => Err(error!(tt_span(tt), "expected `(`")),
+ };
+ }
+ "feature" => {
+ return match iter.next().as_ref() {
+ Some(TokenTree::Punct(p)) if p.as_char() == '=' => match iter.next().as_ref() {
+ Some(TokenTree::Literal(l)) if l.to_string().starts_with('"') => {
+ parse_as_empty(iter)?;
+ Ok(Arg::Feature(tokens2))
+ }
+ tt => Err(error!(tt_span(tt), "expected `=`")),
+ },
+ tt => Err(error!(tt_span(tt), "expected `=`")),
+ };
+ }
+ _ => {}
+ },
+ Some(TokenTree::Literal(l)) => {
+ if let Ok(l) = ast::LitStr::new(l) {
+ parse_as_empty(iter)?;
+ return match l.value().parse::<VersionReq>() {
+ Ok(req) => Ok(Arg::Version(req)),
+ Err(e) => Err(error!(l.span(), "{}", e)),
+ };
+ }
+ }
+ _ => {}
+ }
+
+ Err(error!(
+ tt_span(next.as_ref()),
+ "expected one of: `nightly`, `cfg`, `feature`, string literal"
+ ))
+}
+
+struct VersionReq {
+ major: u16,
+ minor: u16,
+}
+
+impl FromStr for VersionReq {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ let mut pieces = s.split('.');
+ let major = pieces
+ .next()
+ .ok_or("need to specify the major version")?
+ .parse::<u16>()
+ .map_err(|e| e.to_string())?;
+ let minor = pieces
+ .next()
+ .ok_or("need to specify the minor version")?
+ .parse::<u16>()
+ .map_err(|e| e.to_string())?;
+ if let Some(s) = pieces.next() {
+ Err(format!("unexpected input: {}", s))
+ } else {
+ Ok(Self { major, minor })
+ }
+ }
+}
+
+#[derive(Debug)]
+struct Version {
+ minor: u16,
+ patch: u16,
+ nightly: bool,
+}
+
+#[cfg(const_fn_has_build_script)]
+const VERSION: Option<Version> = Some(include!(concat!(env!("OUT_DIR"), "/version.rs")));
+#[cfg(not(const_fn_has_build_script))]
+const VERSION: Option<Version> = None;
diff --git a/src/to_tokens.rs b/src/to_tokens.rs
new file mode 100644
index 0000000..6cc51fd
--- /dev/null
+++ b/src/to_tokens.rs
@@ -0,0 +1,36 @@
+use proc_macro::*;
+use std::iter;
+
+pub(crate) trait ToTokens {
+ fn to_tokens(&self, tokens: &mut TokenStream);
+
+ fn to_token_stream(&self) -> TokenStream {
+ let mut tokens = TokenStream::new();
+ self.to_tokens(&mut tokens);
+ tokens
+ }
+}
+
+impl ToTokens for Ident {
+ fn to_tokens(&self, tokens: &mut TokenStream) {
+ tokens.extend(iter::once(TokenTree::Ident(self.clone())));
+ }
+}
+
+impl ToTokens for Literal {
+ fn to_tokens(&self, tokens: &mut TokenStream) {
+ tokens.extend(iter::once(TokenTree::Literal(self.clone())));
+ }
+}
+
+impl ToTokens for TokenTree {
+ fn to_tokens(&self, tokens: &mut TokenStream) {
+ tokens.extend(iter::once(self.clone()));
+ }
+}
+
+impl ToTokens for TokenStream {
+ fn to_tokens(&self, tokens: &mut TokenStream) {
+ tokens.extend(self.clone());
+ }
+}
diff --git a/src/utils.rs b/src/utils.rs
new file mode 100644
index 0000000..78be0a9
--- /dev/null
+++ b/src/utils.rs
@@ -0,0 +1,46 @@
+use proc_macro::*;
+use std::iter::FromIterator;
+
+use crate::Result;
+
+macro_rules! error {
+ ($span:expr, $msg:expr) => {{
+ crate::error::Error::new($span, $msg)
+ }};
+ ($span:expr, $($tt:tt)*) => {
+ error!($span, format!($($tt)*))
+ };
+}
+
+pub(crate) fn tt_span(tt: Option<&TokenTree>) -> Span {
+ tt.map_or_else(Span::call_site, TokenTree::span)
+}
+
+pub(crate) fn parse_as_empty(mut tokens: impl Iterator<Item = TokenTree>) -> Result<()> {
+ match tokens.next() {
+ Some(tt) => Err(error!(tt.span(), "unexpected token: {}", tt)),
+ None => Ok(()),
+ }
+}
+
+// (`#[cfg(<tokens>)]`, `#[cfg(not(<tokens>))]`)
+pub(crate) fn cfg_attrs(tokens: TokenStream) -> (TokenStream, TokenStream) {
+ let f = |tokens| {
+ let tokens = TokenStream::from_iter(vec![
+ TokenTree::Ident(Ident::new("cfg", Span::call_site())),
+ TokenTree::Group(Group::new(Delimiter::Parenthesis, tokens)),
+ ]);
+ TokenStream::from_iter(vec![
+ TokenTree::Punct(Punct::new('#', Spacing::Alone)),
+ TokenTree::Group(Group::new(Delimiter::Bracket, tokens)),
+ ])
+ };
+
+ let cfg_not = TokenTree::Group(Group::new(Delimiter::Parenthesis, tokens.clone()));
+ let cfg_not = TokenStream::from_iter(vec![
+ TokenTree::Ident(Ident::new("not", Span::call_site())),
+ cfg_not,
+ ]);
+
+ (f(tokens), f(cfg_not))
+}