diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 14:29:10 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 14:29:10 +0000 |
commit | 2aa4a82499d4becd2284cdb482213d541b8804dd (patch) | |
tree | b80bf8bf13c3766139fbacc530efd0dd9d54394c /third_party/rust/const_fn | |
parent | Initial commit. (diff) | |
download | firefox-2aa4a82499d4becd2284cdb482213d541b8804dd.tar.xz firefox-2aa4a82499d4becd2284cdb482213d541b8804dd.zip |
Adding upstream version 86.0.1.upstream/86.0.1upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/const_fn')
-rw-r--r-- | third_party/rust/const_fn/.cargo-checksum.json | 1 | ||||
-rw-r--r-- | third_party/rust/const_fn/CHANGELOG.md | 149 | ||||
-rw-r--r-- | third_party/rust/const_fn/Cargo.toml | 30 | ||||
-rw-r--r-- | third_party/rust/const_fn/LICENSE-APACHE | 177 | ||||
-rw-r--r-- | third_party/rust/const_fn/LICENSE-MIT | 23 | ||||
-rw-r--r-- | third_party/rust/const_fn/README.md | 71 | ||||
-rw-r--r-- | third_party/rust/const_fn/build.rs | 102 | ||||
-rw-r--r-- | third_party/rust/const_fn/src/ast.rs | 141 | ||||
-rw-r--r-- | third_party/rust/const_fn/src/error.rs | 37 | ||||
-rw-r--r-- | third_party/rust/const_fn/src/iter.rs | 39 | ||||
-rw-r--r-- | third_party/rust/const_fn/src/lib.rs | 233 | ||||
-rw-r--r-- | third_party/rust/const_fn/src/to_tokens.rs | 36 | ||||
-rw-r--r-- | third_party/rust/const_fn/src/utils.rs | 46 |
13 files changed, 1085 insertions, 0 deletions
diff --git a/third_party/rust/const_fn/.cargo-checksum.json b/third_party/rust/const_fn/.cargo-checksum.json new file mode 100644 index 0000000000..18914223c2 --- /dev/null +++ b/third_party/rust/const_fn/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"3d4c8910c720a6467a5576a3ed910d852e3595b0a55a5e412514eefc481ec8d9","Cargo.toml":"9163a47eff7b4bd7d6ed96159d3b8b8452eb39aeb0b8e694309a99e47ddc99a7","LICENSE-APACHE":"0d542e0c8804e39aa7f37eb00da5a762149dc682d7829451287e11b938e94594","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"e2c098d1b809f792484ca7e4ff21a1992ae83693683ba39d4a0e34ba1be2760f","build.rs":"0095fffab24644ea5b04a6132b0ccb53762435cc637092e6d4c471c4cc66f60b","src/ast.rs":"4d4a1ddb8deefa31c3e798ffe9cb32752f9b5418c61a8e45be32ca0d5f9b63f3","src/error.rs":"9bc6f12801616dc1750346bf4228d1b172bee88777e9c8cb841dd9348fecbcf3","src/iter.rs":"4eccd018075a4f4839adef2e2cf05198780b9b60d6fbfa8188522c2ad8e82cb5","src/lib.rs":"3ad19d38445a06934b60abe94611c77145c0dbcdc28630abb9a5c27c6b6f998f","src/to_tokens.rs":"5e831889f220c5abaf0403e56b485fbbbb1c4516023e82934f69a230d76694bf","src/utils.rs":"b73f44e9260d32d71aa2712b242f8c451317f62ee1523595fca19878ac07dcd4"},"package":"28b9d6de7f49e22cf97ad17fc4036ece69300032f45f78f30b4a4482cdc3f4a6"}
\ No newline at end of file diff --git a/third_party/rust/const_fn/CHANGELOG.md b/third_party/rust/const_fn/CHANGELOG.md new file mode 100644 index 0000000000..b46403ac22 --- /dev/null +++ b/third_party/rust/const_fn/CHANGELOG.md @@ -0,0 +1,149 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +This project adheres to [Semantic Versioning](https://semver.org). + +<!-- +Note: In this file, do not use the hard wrap in the middle of a sentence for compatibility with GitHub comment style markdown rendering. +--> + +## [Unreleased] + +## [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.5...HEAD +[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 diff --git a/third_party/rust/const_fn/Cargo.toml b/third_party/rust/const_fn/Cargo.toml new file mode 100644 index 0000000000..6017735bc2 --- /dev/null +++ b/third_party/rust/const_fn/Cargo.toml @@ -0,0 +1,30 @@ +# 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.5" +authors = ["Taiki Endo <te316e89@gmail.com>"] +exclude = ["/.github", "/scripts"] +description = "An attribute for easy generation of const functions with conditional compilations.\n" +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 diff --git a/third_party/rust/const_fn/LICENSE-APACHE b/third_party/rust/const_fn/LICENSE-APACHE new file mode 100644 index 0000000000..f433b1a53f --- /dev/null +++ b/third_party/rust/const_fn/LICENSE-APACHE @@ -0,0 +1,177 @@ + + 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 diff --git a/third_party/rust/const_fn/LICENSE-MIT b/third_party/rust/const_fn/LICENSE-MIT new file mode 100644 index 0000000000..31aa79387f --- /dev/null +++ b/third_party/rust/const_fn/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/third_party/rust/const_fn/README.md b/third_party/rust/const_fn/README.md new file mode 100644 index 0000000000..18feabed6a --- /dev/null +++ b/third_party/rust/const_fn/README.md @@ -0,0 +1,71 @@ +# \#\[const_fn\] + +[![crates.io](https://img.shields.io/crates/v/const_fn.svg?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)](https://docs.rs/const_fn) +[![license](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg?style=flat-square)](#license) +[![rustc](https://img.shields.io/badge/rustc-1.31+-blue.svg?style=flat-square)](https://www.rust-lang.org) +[![build status](https://img.shields.io/github/workflow/status/taiki-e/const_fn/CI/master?style=flat-square)](https://github.com/taiki-e/const_fn/actions?query=workflow%3ACI+branch%3Amaster) + +An attribute for easy generation of const functions with conditional +compilations. + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +const_fn = "0.4" +``` + +*Compiler support: requires rustc 1.31+* + +## 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) 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. diff --git a/third_party/rust/const_fn/build.rs b/third_party/rust/const_fn/build.rs new file mode 100644 index 0000000000..5aa341f3b9 --- /dev/null +++ b/third_party/rust/const_fn/build.rs @@ -0,0 +1,102 @@ +#![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: PathBuf = env::var_os("RUSTC").unwrap_or_else(|| "rustc".into()).into(); + 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: 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)); + + // 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<Self, String> { + 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) + } +} diff --git a/third_party/rust/const_fn/src/ast.rs b/third_party/rust/const_fn/src/ast.rs new file mode 100644 index 0000000000..3622a2f14c --- /dev/null +++ b/third_party/rust/const_fn/src/ast.rs @@ -0,0 +1,141 @@ +use proc_macro::{Delimiter, Ident, 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<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 = 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" + )); + } + + 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<TokenTree> { + let mut sig = Vec::new(); + let mut has_const = false; + loop { + match input.peek() { + Some(TokenTree::Group(group)) if group.delimiter() == Delimiter::Brace => break, + None => break, + Some(TokenTree::Ident(i)) if !has_const => { + match &*i.to_string() { + "const" => has_const = true, + "async" | "unsafe" | "extern" | "fn" => { + sig.push(TokenTree::Ident(Ident::new("const", i.span()))); + has_const = true; + } + _ => {} + } + sig.push(input.next().unwrap()); + } + Some(_) => sig.push(input.next().unwrap()), + } + } + sig +} + +fn parse_attrs(input: &mut TokenIter) -> 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 { + pub(crate) 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, 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/third_party/rust/const_fn/src/error.rs b/third_party/rust/const_fn/src/error.rs new file mode 100644 index 0000000000..b572d5a778 --- /dev/null +++ b/third_party/rust/const_fn/src/error.rs @@ -0,0 +1,37 @@ +use 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<String>) -> 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 + }), + ]) + } +} diff --git a/third_party/rust/const_fn/src/iter.rs b/third_party/rust/const_fn/src/iter.rs new file mode 100644 index 0000000000..f998dce4d6 --- /dev/null +++ b/third_party/rust/const_fn/src/iter.rs @@ -0,0 +1,39 @@ +// 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<token_stream::IntoIter>, + peeked: Option<TokenTree>, +} + +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<Self::Item> { + 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), + } + } + } +} diff --git a/third_party/rust/const_fn/src/lib.rs b/third_party/rust/const_fn/src/lib.rs new file mode 100644 index 0000000000..cd8e3e8c96 --- /dev/null +++ b/third_party/rust/const_fn/src/lib.rs @@ -0,0 +1,233 @@ +//! 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(test( + no_crate_inject, + attr( + deny(warnings, rust_2018_idioms, single_use_lifetimes), + allow(dead_code, unused_variables) + ) +))] +#![forbid(unsafe_code)] +#![warn(future_incompatible, rust_2018_idioms, single_use_lifetimes, unreachable_pub)] +#![warn(clippy::all, clippy::default_trait_access)] + +// 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<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(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() + } + 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<Arg> { + let mut iter = tokens.into_iter(); + + 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 => 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::<VersionReq>() { + Ok(req) => Ok(Arg::Version(req)), + Err(e) => Err(error!(l.span(), "{}", e)), + }; + } + } + Some(_) => {} + } + + 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<Self, Self::Err> { + let mut pieces = s.split('.'); + let major = pieces + .next() + .ok_or("need to specify the major version")? + .parse::<u32>() + .map_err(|e| e.to_string())?; + let minor = pieces + .next() + .ok_or("need to specify the minor version")? + .parse::<u32>() + .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 }; diff --git a/third_party/rust/const_fn/src/to_tokens.rs b/third_party/rust/const_fn/src/to_tokens.rs new file mode 100644 index 0000000000..771c7f69c5 --- /dev/null +++ b/third_party/rust/const_fn/src/to_tokens.rs @@ -0,0 +1,36 @@ +use 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()); + } +} diff --git a/third_party/rust/const_fn/src/utils.rs b/third_party/rust/const_fn/src/utils.rs new file mode 100644 index 0000000000..e557ea57e0 --- /dev/null +++ b/third_party/rust/const_fn/src/utils.rs @@ -0,0 +1,46 @@ +use 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<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)) +} |