const_fn-0.4.10/.cargo_vcs_info.json0000644000000001360000000000100127270ustar { "git": { "sha1": "05b3137441c930cb8f2ce17838682ca44c95f334" }, "path_in_vcs": "" }const_fn-0.4.10/CHANGELOG.md000064400000000000000000000123671046102023000133410ustar 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.10] - 2024-04-21 - Respect `RUSTC_WRAPPER` in rustc version detection. ## [0.4.9] - 2022-01-03 - [Fix detection of `-Z assume-incomplete-release` in recent nightly compilers.](https://github.com/taiki-e/const_fn/pull/39) ## [0.4.8] - 2021-05-19 - [Fix parsing of macro metavariable in attribute arguments.](https://github.com/taiki-e/const_fn/pull/37) ## [0.4.7] - 2021-04-17 - [Support compiling with `RUSTFLAGS='-Z assume-incomplete-release'` on nightly compiler.](https://github.com/taiki-e/const_fn/pull/35) ## [0.4.6] - 2021-03-27 - Fix compatibility issues with const generics. ## [0.4.5] - 2021-01-05 - Exclude unneeded files from crates.io. ## [0.4.4] - 2020-11-02 - [Accept `const_fn` attribute with no arguments and functions without `const` keyword.](https://github.com/taiki-e/const_fn/pull/34) This allows `const_fn` to be used as an optional dependency. ```rust #[cfg_attr(feature = "...", const_fn::const_fn)] pub fn func() { /* ... */ } ``` ## [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 **Note:** This release has been 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.10...HEAD [0.4.10]: https://github.com/taiki-e/const_fn/compare/v0.4.9...v0.4.10 [0.4.9]: https://github.com/taiki-e/const_fn/compare/v0.4.8...v0.4.9 [0.4.8]: https://github.com/taiki-e/const_fn/compare/v0.4.7...v0.4.8 [0.4.7]: https://github.com/taiki-e/const_fn/compare/v0.4.6...v0.4.7 [0.4.6]: https://github.com/taiki-e/const_fn/compare/v0.4.5...v0.4.6 [0.4.5]: https://github.com/taiki-e/const_fn/compare/v0.4.4...v0.4.5 [0.4.4]: https://github.com/taiki-e/const_fn/compare/v0.4.3...v0.4.4 [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.10/Cargo.toml0000644000000051100000000000100107220ustar # 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" rust-version = "1.31" name = "const_fn" version = "0.4.10" exclude = [ "/.*", "/tools", ] description = """ A lightweight attribute for easy generation of const functions with conditional compilations. """ readme = "README.md" keywords = [ "macros", "attribute", "const", "static", ] categories = [ "no-std", "no-std::no-alloc", "rust-patterns", ] 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 [dev-dependencies] [lints.clippy] all = "warn" as_ptr_cast_mut = "warn" default_union_representation = "warn" inline_asm_x86_att_syntax = "warn" pedantic = "warn" trailing_empty_array = "warn" transmute_undefined_repr = "warn" undocumented_unsafe_blocks = "warn" [lints.clippy.bool_assert_comparison] level = "allow" priority = 1 [lints.clippy.borrow_as_ptr] level = "allow" priority = 1 [lints.clippy.declare_interior_mutable_const] level = "allow" priority = 1 [lints.clippy.doc_markdown] level = "allow" priority = 1 [lints.clippy.float_cmp] level = "allow" priority = 1 [lints.clippy.manual_assert] level = "allow" priority = 1 [lints.clippy.manual_range_contains] level = "allow" priority = 1 [lints.clippy.missing_errors_doc] level = "allow" priority = 1 [lints.clippy.module_name_repetitions] level = "allow" priority = 1 [lints.clippy.nonminimal_bool] level = "allow" priority = 1 [lints.clippy.similar_names] level = "allow" priority = 1 [lints.clippy.single_match] level = "allow" priority = 1 [lints.clippy.single_match_else] level = "allow" priority = 1 [lints.clippy.struct_excessive_bools] level = "allow" priority = 1 [lints.clippy.struct_field_names] level = "allow" priority = 1 [lints.clippy.too_many_arguments] level = "allow" priority = 1 [lints.clippy.too_many_lines] level = "allow" priority = 1 [lints.clippy.type_complexity] level = "allow" priority = 1 [lints.rust] improper_ctypes = "warn" improper_ctypes_definitions = "warn" non_ascii_idents = "warn" rust_2018_idioms = "warn" single_use_lifetimes = "warn" unreachable_pub = "warn" const_fn-0.4.10/Cargo.toml.orig000064400000000000000000000052031046102023000144060ustar 00000000000000[package] name = "const_fn" version = "0.4.10" #publish:version edition = "2018" rust-version = "1.31" license = "Apache-2.0 OR MIT" repository = "https://github.com/taiki-e/const_fn" keywords = ["macros", "attribute", "const", "static"] categories = ["no-std", "no-std::no-alloc", "rust-patterns"] exclude = ["/.*", "/tools"] description = """ A lightweight attribute for easy generation of const functions with conditional compilations. """ [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [lib] proc-macro = true [dev-dependencies] [lints] workspace = true [workspace] members = ["test_suite"] # This table is shared by projects under github.com/taiki-e. # It is not intended for manual editing. [workspace.lints.rust] improper_ctypes = "warn" improper_ctypes_definitions = "warn" non_ascii_idents = "warn" rust_2018_idioms = "warn" single_use_lifetimes = "warn" unreachable_pub = "warn" # unsafe_op_in_unsafe_fn = "warn" # Set at crate-level instead since https://github.com/rust-lang/rust/pull/100081 is not available on MSRV [workspace.lints.clippy] all = "warn" # Downgrade deny-by-default lints pedantic = "warn" as_ptr_cast_mut = "warn" default_union_representation = "warn" inline_asm_x86_att_syntax = "warn" trailing_empty_array = "warn" transmute_undefined_repr = "warn" undocumented_unsafe_blocks = "warn" # Suppress buggy or noisy clippy lints bool_assert_comparison = { level = "allow", priority = 1 } borrow_as_ptr = { level = "allow", priority = 1 } # https://github.com/rust-lang/rust-clippy/issues/8286 declare_interior_mutable_const = { level = "allow", priority = 1 } # https://github.com/rust-lang/rust-clippy/issues/7665 doc_markdown = { level = "allow", priority = 1 } float_cmp = { level = "allow", priority = 1 } # https://github.com/rust-lang/rust-clippy/issues/7725 manual_assert = { level = "allow", priority = 1 } manual_range_contains = { level = "allow", priority = 1 } # https://github.com/rust-lang/rust-clippy/issues/6455#issuecomment-1225966395 missing_errors_doc = { level = "allow", priority = 1 } module_name_repetitions = { level = "allow", priority = 1 } nonminimal_bool = { level = "allow", priority = 1 } # buggy https://github.com/rust-lang/rust-clippy/issues?q=is%3Aissue+is%3Aopen+nonminimal_bool similar_names = { level = "allow", priority = 1 } single_match = { level = "allow", priority = 1 } single_match_else = { level = "allow", priority = 1 } struct_excessive_bools = { level = "allow", priority = 1 } struct_field_names = { level = "allow", priority = 1 } too_many_arguments = { level = "allow", priority = 1 } too_many_lines = { level = "allow", priority = 1 } type_complexity = { level = "allow", priority = 1 } const_fn-0.4.10/LICENSE-APACHE000064400000000000000000000236761046102023000134610ustar 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.10/LICENSE-MIT000064400000000000000000000017771046102023000131670ustar 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.10/README.md000064400000000000000000000056111046102023000130010ustar 00000000000000# \#\[const_fn\] [![crates.io](https://img.shields.io/crates/v/const_fn?style=flat-square&logo=rust)](https://crates.io/crates/const_fn) [![docs.rs](https://img.shields.io/badge/docs.rs-const__fn-blue?style=flat-square&logo=docs.rs)](https://docs.rs/const_fn) [![license](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue?style=flat-square)](#license) [![msrv](https://img.shields.io/badge/msrv-1.31-blue?style=flat-square&logo=rust)](https://www.rust-lang.org) [![github actions](https://img.shields.io/github/actions/workflow/status/taiki-e/const_fn/ci.yml?branch=main&style=flat-square&logo=github)](https://github.com/taiki-e/const_fn/actions) A lightweight attribute for easy generation of const functions with conditional compilations. ## Usage Add this to your `Cargo.toml`: ```toml [dependencies] const_fn = "0.4" ``` ## Examples ```rust use const_fn::const_fn; // function is `const` on specified version and later compiler (including beta, nightly, and dev build) #[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() { /* ... */ } ``` ### Use this crate as an optional dependency If no arguments are passed, `const_fn` will always make the function `const`. Therefore, you can use `const_fn` as an optional dependency by combination with `cfg_attr`. ```rust // function is `const` if `cfg(feature = "...")` is true #[cfg_attr(feature = "...", const_fn::const_fn)] pub fn optional() { /* ... */ } ``` ## 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) or [MIT license](LICENSE-MIT) at your option. 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.10/build.rs000064400000000000000000000101041046102023000131600ustar 00000000000000// SPDX-License-Identifier: Apache-2.0 OR MIT // The rustc-cfg emitted by the build script are *not* public API. use std::{env, fs, iter, path::PathBuf, process::Command, str}; fn main() { println!("cargo:rerun-if-changed=build.rs"); let version = match rustc_version() { Ok(version) => version.print(), Err(e) => { if env::var_os("CONST_FN_DENY_WARNINGS").unwrap_or_default() == "1" { panic!("unable to determine rustc version") } println!( "cargo:warning={}: unable to determine rustc version: {}", env!("CARGO_PKG_NAME"), e ); return; } }; let out_dir: PathBuf = env::var_os("OUT_DIR").expect("OUT_DIR not set").into(); let out_file = &out_dir.join("version"); fs::write(out_file, version) .unwrap_or_else(|e| panic!("failed to write {}: {}", out_file.display(), e)); if assume_incomplete_release() { println!("cargo:rustc-cfg=const_fn_assume_incomplete_release"); } // Mark as build script has been run successfully. println!("cargo:rustc-cfg=const_fn_has_build_script"); } fn rustc_version() -> Result { let rustc = env::var_os("RUSTC").ok_or("RUSTC not set")?; let rustc_wrapper = if env::var_os("CARGO_ENCODED_RUSTFLAGS").is_some() { env::var_os("RUSTC_WRAPPER").filter(|v| !v.is_empty()) } else { // Cargo sets environment variables for wrappers correctly only since https://github.com/rust-lang/cargo/pull/9601. None }; // Do not apply RUSTC_WORKSPACE_WRAPPER: https://github.com/cuviper/autocfg/issues/58#issuecomment-2067625980 let mut rustc = rustc_wrapper.into_iter().chain(iter::once(rustc)); let mut cmd = Command::new(rustc.next().unwrap()); cmd.args(rustc); // Use verbose version output because the packagers add extra strings to the normal version output. // Do not use long flags (--version --verbose) because clippy-deriver doesn't handle them properly. // -vV is also matched with that cargo internally uses: https://github.com/rust-lang/cargo/blob/14b46ecc62aa671d7477beba237ad9c6a209cf5d/src/cargo/util/rustc.rs#L65 let output = cmd.arg("-vV").output().map_err(|e| format!("could not execute {:?}: {}", cmd, e))?; let verbose_version = str::from_utf8(&output.stdout) .map_err(|e| format!("failed to parse output of {:?}: {}", cmd, e))?; Version::parse(verbose_version) .ok_or_else(|| format!("unexpected output from {:?}: {}", cmd, verbose_version)) } struct Version { minor: u32, nightly: bool, } impl Version { fn parse(verbose_version: &str) -> Option { let mut release = verbose_version .lines() .find(|line| line.starts_with("release: ")) .map(|line| &line["release: ".len()..])? .splitn(2, '-'); let version = release.next().unwrap(); let channel = release.next().unwrap_or_default(); 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 == "nightly" || channel == "dev"; Some(Self { minor, nightly }) } fn print(&self) -> String { format!("Version {{ minor: {}, nightly: {} }}\n", self.minor, self.nightly) } } // https://github.com/taiki-e/const_fn/issues/27 // https://github.com/rust-lang/rust/pull/81468 fn assume_incomplete_release() -> bool { // Recognized formats: -Z( )?assume-incomplete-release // https://github.com/rust-lang/cargo/issues/10111 if let Some(rustflags) = env::var_os("CARGO_ENCODED_RUSTFLAGS") { for mut flag in rustflags.to_string_lossy().split('\x1f') { if flag.starts_with("-Z") { flag = &flag["-Z".len()..]; } if flag == "assume-incomplete-release" { return true; } } } false } const_fn-0.4.10/src/ast.rs000064400000000000000000000100501046102023000134370ustar 00000000000000// SPDX-License-Identifier: Apache-2.0 OR MIT use proc_macro::{Delimiter, Ident, Literal, Span, TokenStream, TokenTree}; use crate::{iter::TokenIter, to_tokens::ToTokens, utils::tt_span, Result}; pub(crate) struct Func { attrs: Vec, // [const] [async] [unsafe] [extern []] fn sig: Vec, body: TokenStream, pub(crate) print_const: bool, } pub(crate) fn parse_input(input: TokenStream) -> Result { let input = &mut TokenIter::new(input); let attrs = parse_attrs(input)?; let sig = parse_signature(input); let body: TokenStream = input.collect(); if body.is_empty() || !sig .iter() .any(|tt| if let TokenTree::Ident(i) = tt { i.to_string() == "fn" } else { false }) { bail!(Span::call_site(), "#[const_fn] attribute may only be used on functions"); } Ok(Func { attrs, sig, body, 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![]; let mut has_const = false; loop { match input.peek() { None => break, Some(TokenTree::Ident(i)) if !has_const => { match &*i.to_string() { "fn" => { sig.push(TokenTree::Ident(Ident::new("const", i.span()))); sig.push(input.next().unwrap()); break; } "const" => { has_const = true; } "async" | "unsafe" | "extern" => { has_const = true; sig.push(TokenTree::Ident(Ident::new("const", i.span()))); } _ => {} } sig.push(input.next().unwrap()); } Some(TokenTree::Ident(i)) if i.to_string() == "fn" => { sig.push(input.next().unwrap()); break; } Some(_) => sig.push(input.next().unwrap()), } } sig } fn parse_attrs(input: &mut TokenIter) -> Result> { let mut attrs = vec![]; 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 => bail!(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 { bail!(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() } } const_fn-0.4.10/src/error.rs000064400000000000000000000031401046102023000140030ustar 00000000000000// SPDX-License-Identifier: Apache-2.0 OR MIT use std::iter::FromIterator; use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; macro_rules! format_err { ($span:expr, $msg:expr $(,)*) => { crate::error::Error::new($span, String::from($msg)) }; ($span:expr, $($tt:tt)*) => { format_err!($span, format!($($tt)*)) }; } macro_rules! bail { ($($tt:tt)*) => { return Err(format_err!($($tt)*)) }; } pub(crate) type Result = std::result::Result; pub(crate) struct Error { span: Span, msg: String, } impl Error { pub(crate) fn new(span: Span, msg: String) -> Self { Self { span, msg } } // https://github.com/dtolnay/syn/blob/1.0.39/src/error.rs#L218-L237 pub(crate) fn into_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.10/src/iter.rs000064400000000000000000000022041046102023000136150ustar 00000000000000// SPDX-License-Identifier: Apache-2.0 OR MIT // Based on https://github.com/dtolnay/proc-macro-hack/blob/0.5.19/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.10/src/lib.rs000064400000000000000000000165431046102023000134330ustar 00000000000000// SPDX-License-Identifier: Apache-2.0 OR MIT /*! A lightweight 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, nightly, and dev build) #[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() { /* ... */ } ``` ### Use this crate as an optional dependency If no arguments are passed, `const_fn` will always make the function `const`. Therefore, you can use `const_fn` as an optional dependency by combination with `cfg_attr`. ```rust // function is `const` if `cfg(feature = "...")` is true #[cfg_attr(feature = "...", const_fn::const_fn)] pub fn optional() { /* ... */ } ``` ## 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(test( no_crate_inject, attr( deny(warnings, rust_2018_idioms, single_use_lifetimes), allow(dead_code, unused_variables) ) ))] #![forbid(unsafe_code)] // older compilers require explicit `extern crate`. #[allow(unused_extern_crates)] extern crate proc_macro; #[macro_use] mod error; mod ast; mod iter; mod to_tokens; mod utils; use std::str::FromStr; use proc_macro::{Delimiter, TokenStream, TokenTree}; use crate::{ ast::LitStr, error::{Error, Result}, iter::TokenIter, to_tokens::ToTokens, utils::{cfg_attrs, parse_as_empty, tt_span}, }; /// A lightweight 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 { expand(args, input).unwrap_or_else(Error::into_compile_error) } fn expand(args: TokenStream, input: TokenStream) -> Result { let arg = parse_arg(args)?; let mut func = ast::parse_input(input)?; Ok(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 + u32::from(cfg!(const_fn_assume_incomplete_release)) > VERSION.minor { func.print_const = false; } func.to_token_stream() } Arg::Nightly => { func.print_const = VERSION.nightly; func.to_token_stream() } Arg::Always => func.to_token_stream(), }) } enum Arg { // `const_fn("...")` Version(VersionReq), // `const_fn(nightly)` Nightly, // `const_fn(cfg(...))` Cfg(TokenStream), // `const_fn(feature = "...")` Feature(TokenStream), // `const_fn` Always, } fn parse_arg(tokens: TokenStream) -> Result { let iter = &mut TokenIter::new(tokens); let next = iter.next(); let next_span = tt_span(next.as_ref()); match next { None => return Ok(Arg::Always), 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 => bail!(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 => bail!(tt_span(tt.as_ref()), "expected string literal"), }, tt => bail!(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) => bail!(l.span(), "{}", e), }; } } Some(_) => {} } bail!(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")); // 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.10/src/to_tokens.rs000064400000000000000000000011401046102023000146550ustar 00000000000000// SPDX-License-Identifier: Apache-2.0 OR MIT use std::iter; use proc_macro::{TokenStream, TokenTree}; 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 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.10/src/utils.rs000064400000000000000000000024371046102023000140220ustar 00000000000000// SPDX-License-Identifier: Apache-2.0 OR MIT use std::iter::FromIterator; use proc_macro::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream, TokenTree}; use crate::{iter::TokenIter, Result}; pub(crate) fn tt_span(tt: Option<&TokenTree>) -> Span { tt.map_or_else(Span::call_site, TokenTree::span) } pub(crate) fn parse_as_empty(tokens: &mut TokenIter) -> Result<()> { match tokens.next() { Some(tt) => bail!(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)) }