const_fn-0.4.3/.cargo_vcs_info.json0000644000000001121375005340500127030ustar { "git": { "sha1": "8684f7ec1965df5434d5eec38b340f10030fce49" } } const_fn-0.4.3/.editorconfig010064400007650000024000000004561374331052500141730ustar 00000000000000# 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 [*.sh] switch_case_indent = true const_fn-0.4.3/.gitattributes010064400007650000024000000001271374635224000144070ustar 00000000000000* text=auto eol=lf *.rs text eol=lf whitespace=tab-in-indent,trailing-space,tabwidth=4 const_fn-0.4.3/.github/CODEOWNERS010064400007650000024000000000131355357360200144440ustar 00000000000000* @taiki-e const_fn-0.4.3/.github/bors.toml010064400007650000024000000000561365006157700147230ustar 00000000000000status = ["ci"] delete_merged_branches = true const_fn-0.4.3/.github/workflows/ci.yml010064400007650000024000000050551375005316300162310ustar 00000000000000name: CI on: pull_request: push: branches: - master - staging schedule: - cron: '0 1 * * *' 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 }} - if: matrix.rust == 'nightly' run: cargo install cargo-hack - run: cargo test --all - if: matrix.rust == 'nightly' run: bash scripts/check-minimal-versions.sh clippy: name: clippy runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Install Rust and Clippy run: ci/install-component.sh clippy - run: cargo clippy --all --all-features --all-targets rustfmt: name: rustfmt runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Install Rust and Rustfmt run: ci/install-component.sh rustfmt - 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 - run: cargo doc --no-deps --all --all-features shellcheck: name: shellcheck runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - run: shellcheck **/*.sh # 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 - shellcheck 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 - shellcheck runs-on: ubuntu-latest steps: - name: Mark the job as a failure run: exit 1 const_fn-0.4.3/.gitignore010064400007650000024000000004201373611441400134760ustar 00000000000000target Cargo.lock # For platform and editor specific settings, it is recommended to add to # a global .gitignore file. # Refs: https://docs.github.com/en/free-pro-team@latest/github/using-git/ignoring-files#configuring-ignored-files-for-all-repositories-on-your-computer const_fn-0.4.3/CHANGELOG.md010064400007650000024000000071701375005325700133330ustar 00000000000000# 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.3] - 2020-11-02 * [`const_fn` no longer fails to compile if unable to determine rustc version. Instead, it now displays a warning.](https://github.com/taiki-e/const_fn/pull/31) * [`const_fn` no longer relies on debug print format.](https://github.com/taiki-e/const_fn/pull/30) ## [0.4.2] - 2020-08-31 * [Improve error messages when failed to parse version information.](https://github.com/taiki-e/const_fn/pull/26) * [Fix compile failure with cargo installed by yum.](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.3...HEAD [0.4.3]: https://github.com/taiki-e/const_fn/compare/v0.4.2...v0.4.3 [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 const_fn-0.4.3/Cargo.toml0000644000000021331375005340500107060ustar # 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.3" authors = ["Taiki Endo "] 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 const_fn-0.4.3/Cargo.toml.orig010064400007650000024000000011711375005330600143770ustar 00000000000000[package] name = "const_fn" version = "0.4.3" authors = ["Taiki Endo "] 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 const_fn-0.4.3/LICENSE-APACHE010060000007650000024000000236761372637416500134560ustar 00000000000000 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 const_fn-0.4.3/LICENSE-MIT010060000007650000024000000017771372637347200131640ustar 00000000000000Permission 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. const_fn-0.4.3/README.md010064400007650000024000000046741372313276100130050ustar 00000000000000# \#\[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 ) * MIT license ([LICENSE-MIT](LICENSE-MIT) or ) 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. const_fn-0.4.3/build.rs010064400007650000024000000067041375005315100131620ustar 00000000000000#![forbid(unsafe_code)] #![warn(rust_2018_idioms, single_use_lifetimes)] 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() { let rustc = env::var_os("RUSTC").map_or_else(|| "rustc".into(), PathBuf::from); let version = match Version::from_rustc(&rustc) { Ok(version) => version.print(), Err(e) => { println!( "cargo:warning={}: unable to determine rustc version: {}", env!("CARGO_PKG_NAME"), e ); return; } }; 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"); // Mark as build script has been run successfully. println!("cargo:rustc-cfg=const_fn_has_build_script"); } struct Version { minor: u32, nightly: bool, } impl Version { // Based on https://github.com/cuviper/autocfg/blob/1.0.1/src/version.rs#L25-L59 // // TODO: use autocfg if https://github.com/cuviper/autocfg/issues/28 merged // or https://github.com/taiki-e/const_fn/issues/27 rejected. fn from_rustc(rustc: &Path) -> Result { let output = Command::new(rustc).args(&["--version", "--verbose"]).output().map_err(|e| { format!("could not execute `{} --version --verbose`: {}", rustc.display(), e) })?; if !output.status.success() { return Err(format!( "process didn't exit successfully: `{} --version --verbose`", rustc.display() )); } let output = str::from_utf8(&output.stdout).map_err(|e| { format!("failed to parse output of `{} --version --verbose`: {}", rustc.display(), e) })?; // Find the release line in the verbose version output. let release = output .lines() .find(|line| line.starts_with("release: ")) .map(|line| &line["release: ".len()..]) .ok_or_else(|| { format!( "could not find rustc release from output of `{} --version --verbose`: {}", rustc.display(), output ) })?; // Split the version and channel info. let mut version_channel = release.split('-'); let version = version_channel.next().unwrap(); let channel = version_channel.next(); let minor = (|| { // 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()?; Some(minor) })() .ok_or_else(|| { format!("unexpected output from `{} --version --verbose`: {}", rustc.display(), output) })?; let nightly = channel.map_or(false, |c| c == "dev" || c == "nightly"); Ok(Self { minor, nightly }) } fn print(&self) -> String { format!("Version {{ minor: {}, nightly: {} }}\n", self.minor, self.nightly) } } const_fn-0.4.3/ci/install-component.sh010075500007650000024000000013541375005316300161140ustar 00000000000000#!/bin/bash # Install nightly Rust with a given component. # # If the component is unavailable on the latest nightly, # use the latest toolchain with the component available. # # When using stable Rust, this script is basically unnecessary as almost components available. # # Refs: https://github.com/rust-lang/rustup-components-history#the-web-part set -euo pipefail package="${1:?}" target="${2:-x86_64-unknown-linux-gnu}" date=$(curl -sSf https://rust-lang.github.io/rustup-components-history/"${target}"/"${package}") # shellcheck disable=1090 "$(cd "$(dirname "${0}")" && pwd)"/install-rust.sh nightly-"${date}" rustup component add "${package}" case "${package}" in rustfmt) "${package}" -V ;; *) cargo "${package}" -V ;; esac const_fn-0.4.3/ci/install-rust.sh010075500007650000024000000003011375005316300150760ustar 00000000000000#!/bin/bash set -euo pipefail toolchain="${1:-nightly}" rustup toolchain install "${toolchain}" --no-self-update --profile minimal rustup default "${toolchain}" rustup -V rustc -V cargo -V const_fn-0.4.3/rustfmt.toml010064400007650000024000000022471375005316300141170ustar 00000000000000# 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 const_fn-0.4.3/scripts/README.md010064400007650000024000000004141373573554700144760ustar 00000000000000This directory contains scripts used by the developers of this project. Some scripts in this directory are also used in CI, but scripts intended to be used only in CI and scripts not intended to be used directly by the developers are basically in the `ci` directory. const_fn-0.4.3/scripts/check-minimal-versions.sh010064400007650000024000000034251374331212100201010ustar 00000000000000#!/bin/bash # Check all public crates with minimal version dependencies. # # Usage: # bash scripts/check-minimal-versions.sh [check|test] # # Note: # - This script modifies Cargo.toml and Cargo.lock while running # - This script exits with 1 if there are any unstaged changes # - This script requires nightly Rust and cargo-hack # # Refs: https://github.com/rust-lang/cargo/issues/5657 set -euo pipefail cd "$(cd "$(dirname "${0}")" && pwd)"/.. # Decide Rust toolchain. # If the `CI` environment variable is not set to `true`, then nightly is used by default. if [[ "${1:-none}" == "+"* ]]; then toolchain="${1}" shift elif [[ "${CI:-false}" != "true" ]]; then cargo +nightly -V >/dev/null || exit 1 toolchain="+nightly" fi # This script requires nightly Rust and cargo-hack if [[ "${toolchain:-+nightly}" != "+nightly"* ]] || ! cargo hack -V &>/dev/null; then echo "error: check-minimal-versions.sh requires nightly Rust and cargo-hack" exit 1 fi subcmd="${1:-check}" case "${subcmd}" in check | test) ;; *) echo "error: invalid argument \`${1}\`" exit 1 ;; esac # This script modifies Cargo.toml and Cargo.lock, so make sure there are no # unstaged changes. git diff --exit-code # Restore original Cargo.toml and Cargo.lock on exit. trap 'git checkout .' EXIT if [[ "${subcmd}" == "check" ]]; then # 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 fi # Update Cargo.lock to minimal version dependencies. cargo ${toolchain:-} update -Zminimal-versions # Run check for all public members of the workspace. cargo ${toolchain:-} hack "${subcmd}" --workspace --all-features --ignore-private -Zfeatures=all const_fn-0.4.3/src/ast.rs010064400007650000024000000075521373223540200134440ustar 00000000000000use proc_macro::{Delimiter, Literal, Span, TokenStream, TokenTree}; use crate::{ iter::TokenIter, to_tokens::ToTokens, utils::{parse_as_empty, tt_span}, Result, }; pub(crate) struct Func { pub(crate) attrs: Vec, pub(crate) sig: Vec, pub(crate) body: TokenTree, pub(crate) print_const: bool, } pub(crate) fn parse_input(input: TokenStream) -> Result { let mut input = TokenIter::new(input); 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 TokenIter) -> Vec { let mut sig = Vec::new(); loop { match input.peek() { Some(TokenTree::Group(group)) if group.delimiter() == Delimiter::Brace => break, None => break, Some(_) => sig.push(input.next().unwrap()), } } sig } fn parse_attrs(input: &mut TokenIter) -> Result> { 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 { pub(crate) token: Literal, value: String, } impl LitStr { pub(crate) fn new(token: Literal) -> Result { let value = token.to_string(); // unlike `syn::LitStr`, only accepts `"..."` if value.starts_with('"') && value.ends_with('"') { Ok(Self { token, 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); } } const_fn-0.4.3/src/error.rs010064400007650000024000000023111372435362100137770ustar 00000000000000use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; use std::iter::FromIterator; pub(crate) struct Error { span: Span, msg: String, } impl Error { pub(crate) fn new(span: Span, msg: impl Into) -> Self { Self { span, msg: msg.into() } } // 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 }), ]) } } const_fn-0.4.3/src/iter.rs010064400007650000024000000021251372435234400136150ustar 00000000000000// Based on https://github.com/dtolnay/proc-macro-hack/blob/0.5.18/src/iter.rs use proc_macro::{token_stream, Delimiter, TokenStream, TokenTree}; pub(crate) struct TokenIter { stack: Vec, peeked: Option, } impl TokenIter { pub(crate) fn new(tokens: TokenStream) -> Self { Self { stack: vec![tokens.into_iter()], peeked: None } } pub(crate) fn peek(&mut self) -> Option<&TokenTree> { self.peeked = self.next(); self.peeked.as_ref() } } impl Iterator for TokenIter { type Item = TokenTree; fn next(&mut self) -> Option { if let Some(tt) = self.peeked.take() { return Some(tt); } loop { let top = self.stack.last_mut()?; match top.next() { None => drop(self.stack.pop()), Some(TokenTree::Group(ref group)) if group.delimiter() == Delimiter::None => { self.stack.push(group.stream().into_iter()); } Some(tt) => return Some(tt), } } } } const_fn-0.4.3/src/lib.rs010064400007650000024000000165051375005330600134220ustar 00000000000000//! 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.3")] #![doc(test( no_crate_inject, attr(deny(warnings, rust_2018_idioms, single_use_lifetimes), allow(dead_code)) ))] #![forbid(unsafe_code)] #![warn(future_incompatible, rust_2018_idioms, single_use_lifetimes, unreachable_pub)] #![warn(clippy::all, clippy::default_trait_access)] // mem::take, #[non_exhaustive], and Option::{as_deref, as_deref_mut} require Rust 1.40, // matches! requires Rust 1.42, str::{strip_prefix, strip_suffix} requires Rust 1.45 #![allow( clippy::mem_replace_with_default, clippy::manual_non_exhaustive, clippy::option_as_ref_deref, clippy::match_like_matches_macro, clippy::manual_strip )] // older compilers require explicit `extern crate`. #[allow(unused_extern_crates)] extern crate proc_macro; #[macro_use] mod utils; mod ast; mod error; mod iter; mod to_tokens; use proc_macro::{Delimiter, TokenStream, TokenTree}; use std::str::FromStr; use crate::{ ast::{Func, LitStr}, error::Error, to_tokens::ToTokens, utils::{cfg_attrs, parse_as_empty, tt_span}, }; type Result = std::result::Result; /// 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(arg) => arg, Err(e) => return e.to_compile_error(), }; let func = match ast::parse_input(input) { Ok(func) => func, Err(e) => return e.to_compile_error(), }; expand(arg, func) } fn expand(arg: Arg, mut func: Func) -> TokenStream { match arg { Arg::Cfg(cfg) => { let (mut tokens, cfg_not) = cfg_attrs(cfg); tokens.extend(func.to_token_stream()); tokens.extend(cfg_not); func.print_const = false; tokens.extend(func.to_token_stream()); tokens } Arg::Feature(feat) => { let (mut tokens, cfg_not) = cfg_attrs(feat); 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 || req.minor > VERSION.minor { func.print_const = false; } func.to_token_stream() } Arg::Nightly => { func.print_const = VERSION.nightly; 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 { let mut iter = tokens.into_iter(); let next = iter.next(); let next_span = tt_span(next.as_ref()); match next { Some(TokenTree::Ident(i)) => match &*i.to_string() { "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" => { let next = iter.next(); return match next.as_ref() { Some(TokenTree::Punct(p)) if p.as_char() == '=' => match iter.next() { Some(TokenTree::Literal(l)) => { let l = LitStr::new(l)?; parse_as_empty(iter)?; Ok(Arg::Feature( vec![TokenTree::Ident(i), next.unwrap(), l.token.into()] .into_iter() .collect(), )) } tt => Err(error!(tt_span(tt.as_ref()), "expected string literal")), }, tt => Err(error!(tt_span(tt), "expected `=`")), }; } _ => {} }, Some(TokenTree::Literal(l)) => { if let Ok(l) = LitStr::new(l) { parse_as_empty(iter)?; return match l.value().parse::() { Ok(req) => Ok(Arg::Version(req)), Err(e) => Err(error!(l.span(), "{}", e)), }; } } _ => {} } Err(error!(next_span, "expected one of: `nightly`, `cfg`, `feature`, string literal")) } struct VersionReq { major: u32, minor: u32, } impl FromStr for VersionReq { type Err = String; fn from_str(s: &str) -> Result { let mut pieces = s.split('.'); let major = pieces .next() .ok_or("need to specify the major version")? .parse::() .map_err(|e| e.to_string())?; let minor = pieces .next() .ok_or("need to specify the minor version")? .parse::() .map_err(|e| e.to_string())?; if let Some(s) = pieces.next() { Err(format!("unexpected input: .{}", s)) } else { Ok(Self { major, minor }) } } } struct Version { minor: u32, nightly: bool, } #[cfg(const_fn_has_build_script)] const VERSION: Version = include!(concat!(env!("OUT_DIR"), "/version.rs")); // If build script has not run or unable to determine version, it is considered as Rust 1.0. #[cfg(not(const_fn_has_build_script))] const VERSION: Version = Version { minor: 0, nightly: false }; const_fn-0.4.3/src/to_tokens.rs010064400007650000024000000015701372344431700146630ustar 00000000000000use proc_macro::{Ident, Literal, TokenStream, TokenTree}; 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()); } } const_fn-0.4.3/src/utils.rs010064400007650000024000000026661373223540200140160ustar 00000000000000use proc_macro::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream, TokenTree}; 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) -> Result<()> { match tokens.next() { Some(tt) => Err(error!(tt.span(), "unexpected token: {}", tt)), None => Ok(()), } } // (`#[cfg()]`, `#[cfg(not())]`) 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)) }