diff options
author | Thiébaud Weksteen <tweek@google.com> | 2021-02-23 17:44:35 +0000 |
---|---|---|
committer | Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com> | 2021-02-23 17:44:35 +0000 |
commit | d86583eaca0d4518b2d36bd184c589007f904989 (patch) | |
tree | 29405bec4f7091062dd737d80ccf029b58258ae0 | |
parent | a775add26c5136ad61a2e9ed66f1bdd02bf96e63 (diff) | |
parent | fd7b3562e76a74d7fe898d1624b506a522ddab4c (diff) | |
download | rustversion-d86583eaca0d4518b2d36bd184c589007f904989.tar.gz |
Initial import of 1.0.4 am: 11c5f14abe am: 25041097df am: b2a01c4a54 am: fd7b3562e7
Original change: https://android-review.googlesource.com/c/platform/external/rust/crates/rustversion/+/1598214
MUST ONLY BE SUBMITTED BY AUTOMERGER
Change-Id: I6e21a80b335a30fec9d7f70426e9cd8c895a0e96
40 files changed, 1785 insertions, 0 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json new file mode 100644 index 0000000..1f45e32 --- /dev/null +++ b/.cargo_vcs_info.json @@ -0,0 +1,5 @@ +{ + "git": { + "sha1": "2449cbc9d927411e8c88802b120a002e2e3507aa" + } +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..9105f94 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,30 @@ +name: CI + +on: + push: + pull_request: + schedule: [cron: "40 1 * * *"] + +jobs: + test: + name: Rust ${{matrix.rust}} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + rust: [nightly, beta, stable, 1.31.0] + steps: + - uses: actions/checkout@v2 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{matrix.rust}} + - run: cargo test + + minimal: + name: Minimal versions + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: dtolnay/rust-toolchain@nightly + - run: cargo update -Z minimal-versions + - run: cargo test diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6936990 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/target +**/*.rs.bk +Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..56995ff --- /dev/null +++ b/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 = "rustversion" +version = "1.0.4" +authors = ["David Tolnay <dtolnay@gmail.com>"] +build = "build/build.rs" +description = "Conditional compilation according to rustc compiler version" +documentation = "https://docs.rs/rustversion" +readme = "README.md" +license = "MIT OR Apache-2.0" +repository = "https://github.com/dtolnay/rustversion" +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[lib] +proc-macro = true +[dev-dependencies.trybuild] +version = "1.0.35" diff --git a/Cargo.toml.orig b/Cargo.toml.orig new file mode 100644 index 0000000..268b002 --- /dev/null +++ b/Cargo.toml.orig @@ -0,0 +1,20 @@ +[package] +name = "rustversion" +version = "1.0.4" +authors = ["David Tolnay <dtolnay@gmail.com>"] +edition = "2018" +license = "MIT OR Apache-2.0" +description = "Conditional compilation according to rustc compiler version" +repository = "https://github.com/dtolnay/rustversion" +documentation = "https://docs.rs/rustversion" +readme = "README.md" +build = "build/build.rs" + +[lib] +proc-macro = true + +[dev-dependencies] +trybuild = "1.0.35" + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] @@ -0,0 +1 @@ +LICENSE-APACHE
\ No newline at end of file diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..31aa793 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/METADATA b/METADATA new file mode 100644 index 0000000..eb41a97 --- /dev/null +++ b/METADATA @@ -0,0 +1,20 @@ +name: "rustversion" +description: "Conditional compilation according to rustc compiler version" +third_party { + url { + type: HOMEPAGE + value: "https://crates.io/crates/rustversion" + } + url { + type: ARCHIVE + value: "https://static.crates.io/crates/rustversion/rustversion-1.0.4.crate" + } + version: "1.0.4" + # Dual-licensed, using the least restrictive per go/thirdpartylicenses#same. + license_type: NOTICE + last_upgrade_date { + year: 2021 + month: 2 + day: 19 + } +} diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2 new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/MODULE_LICENSE_APACHE2 @@ -0,0 +1 @@ +include platform/prebuilts/rust:/OWNERS diff --git a/README.md b/README.md new file mode 100644 index 0000000..5b97272 --- /dev/null +++ b/README.md @@ -0,0 +1,139 @@ +Compiler version cfg +==================== + +[<img alt="github" src="https://img.shields.io/badge/github-dtolnay/rustversion-8da0cb?style=for-the-badge&labelColor=555555&logo=github" height="20">](https://github.com/dtolnay/rustversion) +[<img alt="crates.io" src="https://img.shields.io/crates/v/rustversion.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/rustversion) +[<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-rustversion-66c2a5?style=for-the-badge&labelColor=555555&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K" height="20">](https://docs.rs/rustversion) +[<img alt="build status" src="https://img.shields.io/github/workflow/status/dtolnay/rustversion/CI/master?style=for-the-badge" height="20">](https://github.com/dtolnay/rustversion/actions?query=branch%3Amaster) + +This crate provides macros for conditional compilation according to rustc +compiler version, analogous to [`#[cfg(...)]`][cfg] and +[`#[cfg_attr(...)]`][cfg_attr]. + +[cfg]: https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg-attribute +[cfg_attr]: https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg_attr-attribute + +```toml +[dependencies] +rustversion = "1.0" +``` + +<br> + +## Selectors + +- <b>`#[rustversion::stable]`</b> + —<br> + True on any stable compiler. + +- <b>`#[rustversion::stable(1.34)]`</b> + —<br> + True on exactly the specified stable compiler. + +- <b>`#[rustversion::beta]`</b> + —<br> + True on any beta compiler. + +- <b>`#[rustversion::nightly]`</b> + —<br> + True on any nightly compiler or dev build. + +- <b>`#[rustversion::nightly(2019-01-01)]`</b> + —<br> + True on exactly one nightly. + +- <b>`#[rustversion::since(1.34)]`</b> + —<br> + True on that stable release and any later compiler, including beta and + nightly. + +- <b>`#[rustversion::since(2019-01-01)]`</b> + —<br> + True on that nightly and all newer ones. + +- <b>`#[rustversion::before(`</b><i>version or date</i><b>`)]`</b> + —<br> + Negative of *#[rustversion::since(...)]*. + +- <b>`#[rustversion::not(`</b><i>selector</i><b>`)]`</b> + —<br> + Negative of any selector; for example *#[rustversion::not(nightly)]*. + +- <b>`#[rustversion::any(`</b><i>selectors...</i><b>`)]`</b> + —<br> + True if any of the comma-separated selectors is true; for example + *#[rustversion::any(stable, beta)]*. + +- <b>`#[rustversion::all(`</b><i>selectors...</i><b>`)]`</b> + —<br> + True if all of the comma-separated selectors are true; for example + *#[rustversion::all(since(1.31), before(1.34))]*. + +- <b>`#[rustversion::attr(`</b><i>selector</i><b>`, `</b><i>attribute</i><b>`)]`</b> + —<br> + For conditional inclusion of attributes; analogous to `cfg_attr`. + +<br> + +## Use cases + +Providing additional trait impls as types are stabilized in the standard library +without breaking compatibility with older compilers; in this case Pin\<P\> +stabilized in [Rust 1.33][pin]: + +[pin]: https://blog.rust-lang.org/2019/02/28/Rust-1.33.0.html#pinning + +```rust +#[rustversion::since(1.33)] +use std::pin::Pin; + +#[rustversion::since(1.33)] +impl<P: MyTrait> MyTrait for Pin<P> { + /* ... */ +} +``` + +Similar but for language features; the ability to control alignment greater than +1 of packed structs was stabilized in [Rust 1.33][packed]. + +[packed]: https://github.com/rust-lang/rust/blob/master/RELEASES.md#version-1330-2019-02-28 + +```rust +#[rustversion::attr(before(1.33), repr(packed))] +#[rustversion::attr(since(1.33), repr(packed(2)))] +struct Six(i16, i32); + +fn main() { + println!("{}", std::mem::align_of::<Six>()); +} +``` + +Augmenting code with `const` as const impls are stabilized in the standard +library. This use of `const` as an attribute is recognized as a special case by +the rustversion::attr macro. + +```rust +use std::time::Duration; + +#[rustversion::attr(since(1.32), const)] +fn duration_as_days(dur: Duration) -> u64 { + dur.as_secs() / 60 / 60 / 24 +} +``` + +<br> + +#### License + +<sup> +Licensed under either of <a href="LICENSE-APACHE">Apache License, Version +2.0</a> or <a href="LICENSE-MIT">MIT license</a> at your option. +</sup> + +<br> + +<sub> +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in this crate by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. +</sub> diff --git a/build/build.rs b/build/build.rs new file mode 100644 index 0000000..2a8bc4a --- /dev/null +++ b/build/build.rs @@ -0,0 +1,47 @@ +mod rustc; + +use std::env; +use std::ffi::OsString; +use std::fs; +use std::path::Path; +use std::process::{self, Command}; + +fn main() { + let rustc = env::var_os("RUSTC").unwrap_or_else(|| OsString::from("rustc")); + let output = match Command::new(&rustc).arg("--version").output() { + Ok(output) => output, + Err(e) => { + let rustc = rustc.to_string_lossy(); + eprintln!("Error: failed to run `{} --version`: {}", rustc, e); + process::exit(1); + } + }; + + let string = match String::from_utf8(output.stdout) { + Ok(string) => string, + Err(e) => { + let rustc = rustc.to_string_lossy(); + eprintln!( + "Error: failed to parse output of `{} --version`: {}", + rustc, e, + ); + process::exit(1); + } + }; + + let version = match rustc::parse(&string) { + Some(version) => format!("{:#?}\n", version), + None => { + eprintln!( + "Error: unexpected output from `rustc --version`: {:?}\n\n\ + Please file an issue in https://github.com/dtolnay/rustversion", + string + ); + process::exit(1); + } + }; + + let out_dir = env::var_os("OUT_DIR").expect("OUT_DIR not set"); + let out_file = Path::new(&out_dir).join("version.rs"); + fs::write(out_file, version).expect("failed to write version.rs"); +} diff --git a/build/rustc.rs b/build/rustc.rs new file mode 100644 index 0000000..723e6bd --- /dev/null +++ b/build/rustc.rs @@ -0,0 +1,114 @@ +use self::Channel::*; +use std::fmt::{self, Debug}; + +#[cfg_attr(test, derive(PartialEq))] +pub struct Version { + pub minor: u16, + pub patch: u16, + pub channel: Channel, +} + +#[cfg_attr(test, derive(PartialEq))] +pub enum Channel { + Stable, + Beta, + Nightly(Date), + Dev, +} + +#[cfg_attr(test, derive(PartialEq))] +pub struct Date { + pub year: u16, + pub month: u8, + pub day: u8, +} + +pub fn parse(string: &str) -> Option<Version> { + let last_line = string.lines().last().unwrap_or(&string); + let mut words = last_line.trim().split(' '); + + if words.next()? != "rustc" { + return None; + } + + let mut version_channel = words.next()?.split('-'); + let version = version_channel.next()?; + let channel = version_channel.next(); + + let mut digits = version.split('.'); + 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 channel = match channel { + None => Stable, + Some(channel) if channel == "dev" => Dev, + Some(channel) if channel.starts_with("beta") => Beta, + Some(channel) if channel == "nightly" => match words.next() { + Some(hash) => { + if !hash.starts_with('(') { + return None; + } + let date = words.next()?; + if !date.ends_with(')') { + return None; + } + let mut date = date[..date.len() - 1].split('-'); + let year = date.next()?.parse().ok()?; + let month = date.next()?.parse().ok()?; + let day = date.next()?.parse().ok()?; + match date.next() { + None => Nightly(Date { year, month, day }), + Some(_) => return None, + } + } + None => Dev, + }, + Some(_) => return None, + }; + + Some(Version { + minor, + patch, + channel, + }) +} + +impl Debug for Version { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("crate::version::Version") + .field("minor", &self.minor) + .field("patch", &self.patch) + .field("channel", &self.channel) + .finish() + } +} + +impl Debug for Channel { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self { + Channel::Stable => formatter.write_str("crate::version::Channel::Stable"), + Channel::Beta => formatter.write_str("crate::version::Channel::Beta"), + Channel::Nightly(date) => formatter + .debug_tuple("crate::version::Channel::Nightly") + .field(date) + .finish(), + Channel::Dev => formatter.write_str("crate::version::Channel::Dev"), + } + } +} + +impl Debug for Date { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("crate::date::Date") + .field("year", &self.year) + .field("month", &self.month) + .field("day", &self.day) + .finish() + } +} diff --git a/src/attr.rs b/src/attr.rs new file mode 100644 index 0000000..6023d1e --- /dev/null +++ b/src/attr.rs @@ -0,0 +1,35 @@ +use crate::error::{Error, Result}; +use crate::expr::{self, Expr}; +use crate::{iter, token}; +use proc_macro::{Span, TokenStream}; + +pub struct Args { + pub condition: Expr, + pub then: Then, +} + +pub enum Then { + Const(Span), + Attribute(TokenStream), +} + +pub fn parse(input: TokenStream) -> Result<Args> { + let ref mut input = iter::new(input); + let condition = expr::parse(input)?; + + token::parse_punct(input, ',')?; + if input.peek().is_none() { + return Err(Error::new(Span::call_site(), "expected one or more attrs")); + } + + let const_span = token::parse_optional_keyword(input, "const"); + let then = if let Some(const_span) = const_span { + token::parse_optional_punct(input, ','); + token::parse_end(input)?; + Then::Const(const_span) + } else { + Then::Attribute(input.collect()) + }; + + Ok(Args { condition, then }) +} diff --git a/src/bound.rs b/src/bound.rs new file mode 100644 index 0000000..a667a5b --- /dev/null +++ b/src/bound.rs @@ -0,0 +1,63 @@ +use crate::date::{self, Date}; +use crate::error::{Error, Result}; +use crate::iter::Iter; +use crate::release::{self, Release}; +use crate::time; +use crate::version::{Channel::*, Version}; +use proc_macro::{Group, TokenTree}; +use std::cmp::Ordering; + +pub enum Bound { + Nightly(Date), + Stable(Release), +} + +pub fn parse(paren: Group, iter: Iter) -> Result<Bound> { + if let Some(TokenTree::Literal(literal)) = iter.peek() { + let repr = literal.to_string(); + if repr.starts_with(|ch: char| ch.is_ascii_digit()) { + if repr.contains('.') { + return release::parse(paren, iter).map(Bound::Stable); + } else { + return date::parse(paren, iter).map(Bound::Nightly); + } + } + } + let msg = format!( + "expected rustc release number like 1.31, or nightly date like {}", + time::today(), + ); + Err(Error::group(paren, msg)) +} + +impl PartialEq<Bound> for Version { + fn eq(&self, rhs: &Bound) -> bool { + match rhs { + Bound::Nightly(date) => match self.channel { + Stable | Beta | Dev => false, + Nightly(nightly) => nightly == *date, + }, + Bound::Stable(release) => { + self.minor == release.minor + && release.patch.map_or(true, |patch| self.patch == patch) + } + } + } +} + +impl PartialOrd<Bound> for Version { + fn partial_cmp(&self, rhs: &Bound) -> Option<Ordering> { + match rhs { + Bound::Nightly(date) => match self.channel { + Stable | Beta => Some(Ordering::Less), + Nightly(nightly) => Some(nightly.cmp(date)), + Dev => Some(Ordering::Greater), + }, + Bound::Stable(release) => { + let version = (self.minor, self.patch); + let bound = (release.minor, release.patch.unwrap_or(0)); + Some(version.cmp(&bound)) + } + } + } +} diff --git a/src/constfn.rs b/src/constfn.rs new file mode 100644 index 0000000..0e50c03 --- /dev/null +++ b/src/constfn.rs @@ -0,0 +1,58 @@ +use crate::error::{Error, Result}; +use proc_macro::{Ident, Span, TokenStream, TokenTree}; +use std::iter; + +#[derive(PartialOrd, PartialEq)] +enum Qualifiers { + None, + Async, + Unsafe, + Extern, + Abi, +} + +impl Qualifiers { + fn from_ident(ident: &Ident) -> Self { + match ident.to_string().as_str() { + "async" => Qualifiers::Async, + "unsafe" => Qualifiers::Unsafe, + "extern" => Qualifiers::Extern, + _ => Qualifiers::None, + } + } +} + +pub(crate) fn insert_const(input: TokenStream, const_span: Span) -> Result<TokenStream> { + let ref mut input = crate::iter::new(input); + let mut out = TokenStream::new(); + let mut qualifiers = Qualifiers::None; + let mut pending = Vec::new(); + + while let Some(token) = input.next() { + match token { + TokenTree::Ident(ref ident) if ident.to_string() == "fn" => { + let const_ident = Ident::new("const", const_span); + out.extend(iter::once(TokenTree::Ident(const_ident))); + out.extend(pending); + out.extend(iter::once(token)); + out.extend(input); + return Ok(out); + } + TokenTree::Ident(ref ident) if Qualifiers::from_ident(ident) > qualifiers => { + qualifiers = Qualifiers::from_ident(ident); + pending.push(token); + } + TokenTree::Literal(_) if qualifiers == Qualifiers::Extern => { + qualifiers = Qualifiers::Abi; + pending.push(token); + } + _ => { + qualifiers = Qualifiers::None; + out.extend(pending.drain(..)); + out.extend(iter::once(token)); + } + } + } + + Err(Error::new(const_span, "only allowed on a fn item")) +} diff --git a/src/date.rs b/src/date.rs new file mode 100644 index 0000000..5cdb691 --- /dev/null +++ b/src/date.rs @@ -0,0 +1,50 @@ +use crate::error::{Error, Result}; +use crate::iter::Iter; +use crate::{time, token}; +use proc_macro::Group; +use std::fmt::{self, Display}; + +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Date { + pub year: u16, + pub month: u8, + pub day: u8, +} + +impl Display for Date { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!( + formatter, + "{:04}-{:02}-{:02}", + self.year, self.month, self.day, + ) + } +} + +pub fn parse(paren: Group, iter: Iter) -> Result<Date> { + try_parse(iter).map_err(|_| { + let msg = format!("expected nightly date, like {}", time::today()); + Error::group(paren, msg) + }) +} + +fn try_parse(iter: Iter) -> Result<Date, ()> { + let year = token::parse_literal(iter).map_err(drop)?; + token::parse_punct(iter, '-').map_err(drop)?; + let month = token::parse_literal(iter).map_err(drop)?; + token::parse_punct(iter, '-').map_err(drop)?; + let day = token::parse_literal(iter).map_err(drop)?; + + let year = year.to_string().parse::<u64>().map_err(drop)?; + let month = month.to_string().parse::<u64>().map_err(drop)?; + let day = day.to_string().parse::<u64>().map_err(drop)?; + if year >= 3000 || month > 12 || day > 31 { + return Err(()); + } + + Ok(Date { + year: year as u16, + month: month as u8, + day: day as u8, + }) +} diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..a99625b --- /dev/null +++ b/src/error.rs @@ -0,0 +1,56 @@ +use proc_macro::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree}; +use std::fmt::Display; +use std::iter::FromIterator; + +pub type Result<T, E = Error> = std::result::Result<T, E>; + +pub struct Error { + begin: Span, + end: Span, + msg: String, +} + +impl Error { + pub fn new(span: Span, msg: impl Display) -> Self { + Self::new2(span, span, msg) + } + + pub fn new2(begin: Span, end: Span, msg: impl Display) -> Self { + Error { + begin, + end, + msg: msg.to_string(), + } + } + + pub fn group(group: Group, msg: impl Display) -> Self { + let mut iter = group.stream().into_iter(); + let delimiter = group.span(); + let begin = iter.next().map_or(delimiter, |t| t.span()); + let end = iter.last().map_or(begin, |t| t.span()); + Self::new2(begin, end, msg) + } + + pub fn into_compile_error(self) -> TokenStream { + // compile_error! { $msg } + TokenStream::from_iter(vec![ + TokenTree::Ident(Ident::new("compile_error", self.begin)), + TokenTree::Punct({ + let mut punct = Punct::new('!', Spacing::Alone); + punct.set_span(self.begin); + 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.end); + string + })]) + }); + group.set_span(self.end); + group + }), + ]) + } +} diff --git a/src/expr.rs b/src/expr.rs new file mode 100644 index 0000000..45ed7d2 --- /dev/null +++ b/src/expr.rs @@ -0,0 +1,163 @@ +use crate::bound::{self, Bound}; +use crate::date::{self, Date}; +use crate::error::{Error, Result}; +use crate::iter::{self, Iter}; +use crate::release::{self, Release}; +use crate::token; +use crate::version::{Channel, Version}; +use proc_macro::{Ident, Span, TokenTree}; + +pub enum Expr { + Stable, + Beta, + Nightly, + Date(Date), + Since(Bound), + Before(Bound), + Release(Release), + Not(Box<Expr>), + Any(Vec<Expr>), + All(Vec<Expr>), +} + +impl Expr { + pub fn eval(&self, rustc: Version) -> bool { + use self::Expr::*; + + match self { + Stable => rustc.channel == Channel::Stable, + Beta => rustc.channel == Channel::Beta, + Nightly => match rustc.channel { + Channel::Nightly(_) | Channel::Dev => true, + Channel::Stable | Channel::Beta => false, + }, + Date(date) => match rustc.channel { + Channel::Nightly(rustc) => rustc == *date, + Channel::Stable | Channel::Beta | Channel::Dev => false, + }, + Since(bound) => rustc >= *bound, + Before(bound) => rustc < *bound, + Release(release) => { + rustc.channel == Channel::Stable + && rustc.minor == release.minor + && release.patch.map_or(true, |patch| rustc.patch == patch) + } + Not(expr) => !expr.eval(rustc), + Any(exprs) => exprs.iter().any(|e| e.eval(rustc)), + All(exprs) => exprs.iter().all(|e| e.eval(rustc)), + } + } +} + +pub fn parse(iter: Iter) -> Result<Expr> { + match &iter.next() { + Some(TokenTree::Ident(i)) if i.to_string() == "stable" => parse_stable(iter), + Some(TokenTree::Ident(i)) if i.to_string() == "beta" => Ok(Expr::Beta), + Some(TokenTree::Ident(i)) if i.to_string() == "nightly" => parse_nightly(iter), + Some(TokenTree::Ident(i)) if i.to_string() == "since" => parse_since(i, iter), + Some(TokenTree::Ident(i)) if i.to_string() == "before" => parse_before(i, iter), + Some(TokenTree::Ident(i)) if i.to_string() == "not" => parse_not(i, iter), + Some(TokenTree::Ident(i)) if i.to_string() == "any" => parse_any(i, iter), + Some(TokenTree::Ident(i)) if i.to_string() == "all" => parse_all(i, iter), + unexpected => { + let span = unexpected + .as_ref() + .map_or_else(Span::call_site, TokenTree::span); + Err(Error::new(span, "expected one of `stable`, `beta`, `nightly`, `since`, `before`, `not`, `any`, `all`")) + } + } +} + +fn parse_nightly(iter: Iter) -> Result<Expr> { + let paren = match token::parse_optional_paren(iter) { + Some(group) => group, + None => return Ok(Expr::Nightly), + }; + + let ref mut inner = iter::new(paren.stream()); + let date = date::parse(paren, inner)?; + token::parse_optional_punct(inner, ','); + token::parse_end(inner)?; + + Ok(Expr::Date(date)) +} + +fn parse_stable(iter: Iter) -> Result<Expr> { + let paren = match token::parse_optional_paren(iter) { + Some(group) => group, + None => return Ok(Expr::Stable), + }; + + let ref mut inner = iter::new(paren.stream()); + let release = release::parse(paren, inner)?; + token::parse_optional_punct(inner, ','); + token::parse_end(inner)?; + + Ok(Expr::Release(release)) +} + +fn parse_since(introducer: &Ident, iter: Iter) -> Result<Expr> { + let paren = token::parse_paren(introducer, iter)?; + + let ref mut inner = iter::new(paren.stream()); + let bound = bound::parse(paren, inner)?; + token::parse_optional_punct(inner, ','); + token::parse_end(inner)?; + + Ok(Expr::Since(bound)) +} + +fn parse_before(introducer: &Ident, iter: Iter) -> Result<Expr> { + let paren = token::parse_paren(introducer, iter)?; + + let ref mut inner = iter::new(paren.stream()); + let bound = bound::parse(paren, inner)?; + token::parse_optional_punct(inner, ','); + token::parse_end(inner)?; + + Ok(Expr::Before(bound)) +} + +fn parse_not(introducer: &Ident, iter: Iter) -> Result<Expr> { + let paren = token::parse_paren(introducer, iter)?; + + let ref mut inner = iter::new(paren.stream()); + let expr = self::parse(inner)?; + token::parse_optional_punct(inner, ','); + token::parse_end(inner)?; + + Ok(Expr::Not(Box::new(expr))) +} + +fn parse_any(introducer: &Ident, iter: Iter) -> Result<Expr> { + let paren = token::parse_paren(introducer, iter)?; + + let ref mut inner = iter::new(paren.stream()); + let exprs = parse_comma_separated(inner)?; + + Ok(Expr::Any(exprs.into_iter().collect())) +} + +fn parse_all(introducer: &Ident, iter: Iter) -> Result<Expr> { + let paren = token::parse_paren(introducer, iter)?; + + let ref mut inner = iter::new(paren.stream()); + let exprs = parse_comma_separated(inner)?; + + Ok(Expr::All(exprs.into_iter().collect())) +} + +fn parse_comma_separated(iter: Iter) -> Result<Vec<Expr>> { + let mut exprs = Vec::new(); + + while iter.peek().is_some() { + let expr = self::parse(iter)?; + exprs.push(expr); + if iter.peek().is_none() { + break; + } + token::parse_punct(iter, ',')?; + } + + Ok(exprs) +} diff --git a/src/iter.rs b/src/iter.rs new file mode 100644 index 0000000..722013c --- /dev/null +++ b/src/iter.rs @@ -0,0 +1,42 @@ +use proc_macro::{token_stream, Delimiter, TokenStream, TokenTree}; + +pub type Iter<'a> = &'a mut IterImpl; + +pub struct IterImpl { + stack: Vec<token_stream::IntoIter>, + peeked: Option<TokenTree>, +} + +pub fn new(tokens: TokenStream) -> IterImpl { + IterImpl { + stack: vec![tokens.into_iter()], + peeked: None, + } +} + +impl IterImpl { + pub fn peek(&mut self) -> Option<&TokenTree> { + self.peeked = self.next(); + self.peeked.as_ref() + } +} + +impl Iterator for IterImpl { + 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/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..2614105 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,282 @@ +//! [![github]](https://github.com/dtolnay/rustversion) [![crates-io]](https://crates.io/crates/rustversion) [![docs-rs]](https://docs.rs/rustversion) +//! +//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github +//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust +//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K +//! +//! <br> +//! +//! This crate provides macros for conditional compilation according to rustc +//! compiler version, analogous to [`#[cfg(...)]`][cfg] and +//! [`#[cfg_attr(...)]`][cfg_attr]. +//! +//! [cfg]: https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg-attribute +//! [cfg_attr]: https://doc.rust-lang.org/reference/conditional-compilation.html#the-cfg_attr-attribute +//! +//! <br> +//! +//! # Selectors +//! +//! - <p style="margin-left:50px;text-indent:-50px"> +//! <b><code>#[rustversion::stable]</code></b> +//! —<br> +//! True on any stable compiler. +//! </p> +//! +//! - <p style="margin-left:50px;text-indent:-50px"> +//! <b><code>#[rustversion::stable(1.34)]</code></b> +//! —<br> +//! True on exactly the specified stable compiler. +//! </p> +//! +//! - <p style="margin-left:50px;text-indent:-50px"> +//! <b><code>#[rustversion::beta]</code></b> +//! —<br> +//! True on any beta compiler. +//! </p> +//! +//! - <p style="margin-left:50px;text-indent:-50px"> +//! <b><code>#[rustversion::nightly]</code></b> +//! —<br> +//! True on any nightly compiler or dev build. +//! </p> +//! +//! - <p style="margin-left:50px;text-indent:-50px"> +//! <b><code>#[rustversion::nightly(2019-01-01)]</code></b> +//! —<br> +//! True on exactly one nightly. +//! </p> +//! +//! - <p style="margin-left:50px;text-indent:-50px"> +//! <b><code>#[rustversion::since(1.34)]</code></b> +//! —<br> +//! True on that stable release and any later compiler, including beta and +//! nightly. +//! </p> +//! +//! - <p style="margin-left:50px;text-indent:-50px"> +//! <b><code>#[rustversion::since(2019-01-01)]</code></b> +//! —<br> +//! True on that nightly and all newer ones. +//! </p> +//! +//! - <p style="margin-left:50px;text-indent:-50px"> +//! <b><code>#[rustversion::before(</code></b><i>version or date</i><b><code>)]</code></b> +//! —<br> +//! Negative of <i>#[rustversion::since(...)]</i>. +//! </p> +//! +//! - <p style="margin-left:50px;text-indent:-50px"> +//! <b><code>#[rustversion::not(</code></b><i>selector</i><b><code>)]</code></b> +//! —<br> +//! Negative of any selector; for example <i>#[rustversion::not(nightly)]</i>. +//! </p> +//! +//! - <p style="margin-left:50px;text-indent:-50px"> +//! <b><code>#[rustversion::any(</code></b><i>selectors...</i><b><code>)]</code></b> +//! —<br> +//! True if any of the comma-separated selectors is true; for example +//! <i>#[rustversion::any(stable, beta)]</i>. +//! </p> +//! +//! - <p style="margin-left:50px;text-indent:-50px"> +//! <b><code>#[rustversion::all(</code></b><i>selectors...</i><b><code>)]</code></b> +//! —<br> +//! True if all of the comma-separated selectors are true; for example +//! <i>#[rustversion::all(since(1.31), before(1.34))]</i>. +//! </p> +//! +//! - <p style="margin-left:50px;text-indent:-50px"> +//! <b><code>#[rustversion::attr(</code></b><i>selector</i><b><code>, </code></b><i>attribute</i><b><code>)]</code></b> +//! —<br> +//! For conditional inclusion of attributes; analogous to +//! <code>cfg_attr</code>. +//! </p> +//! +//! <br> +//! +//! # Use cases +//! +//! Providing additional trait impls as types are stabilized in the standard library +//! without breaking compatibility with older compilers; in this case Pin\<P\> +//! stabilized in [Rust 1.33][pin]: +//! +//! [pin]: https://blog.rust-lang.org/2019/02/28/Rust-1.33.0.html#pinning +//! +//! ``` +//! # trait MyTrait {} +//! # +//! #[rustversion::since(1.33)] +//! use std::pin::Pin; +//! +//! #[rustversion::since(1.33)] +//! impl<P: MyTrait> MyTrait for Pin<P> { +//! /* ... */ +//! } +//! ``` +//! +//! Similar but for language features; the ability to control alignment greater than +//! 1 of packed structs was stabilized in [Rust 1.33][packed]. +//! +//! [packed]: https://github.com/rust-lang/rust/blob/master/RELEASES.md#version-1330-2019-02-28 +//! +//! ``` +//! #[rustversion::attr(before(1.33), repr(packed))] +//! #[rustversion::attr(since(1.33), repr(packed(2)))] +//! struct Six(i16, i32); +//! +//! fn main() { +//! println!("{}", std::mem::align_of::<Six>()); +//! } +//! ``` +//! +//! Augmenting code with `const` as const impls are stabilized in the standard +//! library. This use of `const` as an attribute is recognized as a special case +//! by the rustversion::attr macro. +//! +//! ``` +//! use std::time::Duration; +//! +//! #[rustversion::attr(since(1.32), const)] +//! fn duration_as_days(dur: Duration) -> u64 { +//! dur.as_secs() / 60 / 60 / 24 +//! } +//! ``` +//! +//! <br> + +extern crate proc_macro; + +mod attr; +mod bound; +mod constfn; +mod date; +mod error; +mod expr; +mod iter; +mod release; +mod time; +mod token; +mod version; + +use crate::attr::Then; +use crate::error::{Error, Result}; +use crate::version::Version; +use proc_macro::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream, TokenTree}; +use std::iter::FromIterator; + +const RUSTVERSION: Version = include!(concat!(env!("OUT_DIR"), "/version.rs")); + +#[proc_macro_attribute] +pub fn stable(args: TokenStream, input: TokenStream) -> TokenStream { + cfg("stable", args, input) +} + +#[proc_macro_attribute] +pub fn beta(args: TokenStream, input: TokenStream) -> TokenStream { + cfg("beta", args, input) +} + +#[proc_macro_attribute] +pub fn nightly(args: TokenStream, input: TokenStream) -> TokenStream { + cfg("nightly", args, input) +} + +#[proc_macro_attribute] +pub fn since(args: TokenStream, input: TokenStream) -> TokenStream { + cfg("since", args, input) +} + +#[proc_macro_attribute] +pub fn before(args: TokenStream, input: TokenStream) -> TokenStream { + cfg("before", args, input) +} + +#[proc_macro_attribute] +pub fn not(args: TokenStream, input: TokenStream) -> TokenStream { + cfg("not", args, input) +} + +#[proc_macro_attribute] +pub fn any(args: TokenStream, input: TokenStream) -> TokenStream { + cfg("any", args, input) +} + +#[proc_macro_attribute] +pub fn all(args: TokenStream, input: TokenStream) -> TokenStream { + cfg("all", args, input) +} + +fn cfg(introducer: &str, args: TokenStream, input: TokenStream) -> TokenStream { + try_cfg(introducer, args, input).unwrap_or_else(Error::into_compile_error) +} + +fn try_cfg(introducer: &str, args: TokenStream, input: TokenStream) -> Result<TokenStream> { + let introducer = Ident::new(introducer, Span::call_site()); + + let mut full_args = TokenStream::from(TokenTree::Ident(introducer)); + if !args.is_empty() { + full_args.extend(std::iter::once(TokenTree::Group(Group::new( + Delimiter::Parenthesis, + args, + )))); + } + + let ref mut full_args = iter::new(full_args); + let expr = expr::parse(full_args)?; + token::parse_end(full_args)?; + + if expr.eval(RUSTVERSION) { + Ok(input) + } else { + Ok(TokenStream::new()) + } +} + +#[proc_macro_attribute] +pub fn attr(args: TokenStream, input: TokenStream) -> TokenStream { + attr::parse(args) + .and_then(|args| try_attr(args, input)) + .unwrap_or_else(Error::into_compile_error) +} + +fn try_attr(args: attr::Args, input: TokenStream) -> Result<TokenStream> { + if !args.condition.eval(RUSTVERSION) { + return Ok(input); + } + + match args.then { + Then::Const(const_token) => constfn::insert_const(input, const_token), + Then::Attribute(then) => { + // #[cfg_attr(all(), #then)] + Ok(TokenStream::from_iter( + vec![ + TokenTree::Punct(Punct::new('#', Spacing::Alone)), + TokenTree::Group(Group::new( + Delimiter::Bracket, + TokenStream::from_iter(vec![ + TokenTree::Ident(Ident::new("cfg_attr", Span::call_site())), + TokenTree::Group(Group::new( + Delimiter::Parenthesis, + TokenStream::from_iter( + vec![ + TokenTree::Ident(Ident::new("all", Span::call_site())), + TokenTree::Group(Group::new( + Delimiter::Parenthesis, + TokenStream::new(), + )), + TokenTree::Punct(Punct::new(',', Spacing::Alone)), + ] + .into_iter() + .chain(then), + ), + )), + ]), + )), + ] + .into_iter() + .chain(input), + )) + } + } +} diff --git a/src/release.rs b/src/release.rs new file mode 100644 index 0000000..3f421c6 --- /dev/null +++ b/src/release.rs @@ -0,0 +1,34 @@ +use crate::error::{Error, Result}; +use crate::iter::Iter; +use crate::token; +use proc_macro::Group; + +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Release { + pub minor: u16, + pub patch: Option<u16>, +} + +pub fn parse(paren: Group, iter: Iter) -> Result<Release> { + try_parse(iter).map_err(|_| Error::group(paren, "expected rustc release number, like 1.31")) +} + +fn try_parse(iter: Iter) -> Result<Release, ()> { + let major_minor = token::parse_literal(iter).map_err(drop)?; + let string = major_minor.to_string(); + + if !string.starts_with("1.") { + return Err(()); + } + + let minor: u16 = string[2..].parse().map_err(drop)?; + + let patch = if token::parse_optional_punct(iter, '.').is_some() { + let int = token::parse_literal(iter).map_err(drop)?; + Some(int.to_string().parse().map_err(drop)?) + } else { + None + }; + + Ok(Release { minor, patch }) +} diff --git a/src/time.rs b/src/time.rs new file mode 100644 index 0000000..1e6dd90 --- /dev/null +++ b/src/time.rs @@ -0,0 +1,44 @@ +use crate::date::Date; +use std::time::{SystemTime, UNIX_EPOCH}; + +// Timestamp of 2016-03-01 00:00:00 in UTC. +const BASE: u64 = 1456790400; +const BASE_YEAR: u16 = 2016; +const BASE_MONTH: u8 = 3; + +// Days between leap days. +const CYCLE: u64 = 365 * 4 + 1; + +const DAYS_BY_MONTH: [u8; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + +pub fn today() -> Date { + let default = Date { + year: 2019, + month: 1, + day: 1, + }; + try_today().unwrap_or(default) +} + +fn try_today() -> Option<Date> { + let now = SystemTime::now(); + let since_epoch = now.duration_since(UNIX_EPOCH).ok()?; + let secs = since_epoch.as_secs(); + + let approx_days = secs.checked_sub(BASE)? / 60 / 60 / 24; + let cycle = approx_days / CYCLE; + let mut rem = approx_days % CYCLE; + + let mut year = BASE_YEAR + cycle as u16 * 4; + let mut month = BASE_MONTH; + loop { + let days_in_month = DAYS_BY_MONTH[month as usize - 1]; + if rem < days_in_month as u64 { + let day = rem as u8 + 1; + return Some(Date { year, month, day }); + } + rem -= days_in_month as u64; + year += (month == 12) as u16; + month = month % 12 + 1; + } +} diff --git a/src/token.rs b/src/token.rs new file mode 100644 index 0000000..ebb6f1c --- /dev/null +++ b/src/token.rs @@ -0,0 +1,78 @@ +use crate::error::{Error, Result}; +use crate::iter::Iter; +use proc_macro::{Delimiter, Group, Ident, Literal, Span, TokenTree}; + +pub fn parse_punct(iter: Iter, ch: char) -> Result<()> { + match iter.next() { + Some(TokenTree::Punct(ref punct)) if punct.as_char() == ch => Ok(()), + unexpected => { + let span = unexpected + .as_ref() + .map_or_else(Span::call_site, TokenTree::span); + Err(Error::new(span, format!("expected `{}`", ch))) + } + } +} + +pub fn parse_optional_punct(iter: Iter, ch: char) -> Option<()> { + match iter.peek() { + Some(TokenTree::Punct(punct)) if punct.as_char() == ch => iter.next().map(drop), + _ => None, + } +} + +pub fn parse_optional_keyword(iter: Iter, keyword: &str) -> Option<Span> { + match iter.peek() { + Some(TokenTree::Ident(ident)) if ident.to_string() == keyword => { + Some(iter.next().unwrap().span()) + } + _ => None, + } +} + +pub fn parse_literal(iter: Iter) -> Result<Literal> { + match iter.next() { + Some(TokenTree::Literal(literal)) => Ok(literal), + unexpected => { + let span = unexpected + .as_ref() + .map_or_else(Span::call_site, TokenTree::span); + Err(Error::new(span, "expected literal")) + } + } +} + +pub fn parse_paren(introducer: &Ident, iter: Iter) -> Result<Group> { + match iter.peek() { + Some(TokenTree::Group(group)) if group.delimiter() == Delimiter::Parenthesis => { + match iter.next() { + Some(TokenTree::Group(group)) => Ok(group), + _ => unreachable!(), + } + } + Some(unexpected) => Err(Error::new(unexpected.span(), "expected `(`")), + None => Err(Error::new( + introducer.span(), + format!("expected `(` after `{}`", introducer), + )), + } +} + +pub fn parse_optional_paren(iter: Iter) -> Option<Group> { + match iter.peek() { + Some(TokenTree::Group(group)) if group.delimiter() == Delimiter::Parenthesis => { + match iter.next() { + Some(TokenTree::Group(group)) => Some(group), + _ => unreachable!(), + } + } + _ => None, + } +} + +pub fn parse_end(iter: Iter) -> Result<()> { + match iter.next() { + None => Ok(()), + Some(unexpected) => Err(Error::new(unexpected.span(), "unexpected token")), + } +} diff --git a/src/version.rs b/src/version.rs new file mode 100644 index 0000000..f4a69f5 --- /dev/null +++ b/src/version.rs @@ -0,0 +1,18 @@ +#![allow(dead_code)] + +use crate::date::Date; + +#[derive(Copy, Clone, Debug, PartialEq)] +pub struct Version { + pub minor: u16, + pub patch: u16, + pub channel: Channel, +} + +#[derive(Copy, Clone, Debug, PartialEq)] +pub enum Channel { + Stable, + Beta, + Nightly(Date), + Dev, +} diff --git a/tests/compiletest.rs b/tests/compiletest.rs new file mode 100644 index 0000000..f9aea23 --- /dev/null +++ b/tests/compiletest.rs @@ -0,0 +1,6 @@ +#[rustversion::attr(not(nightly), ignore)] +#[test] +fn ui() { + let t = trybuild::TestCases::new(); + t.compile_fail("tests/ui/*.rs"); +} diff --git a/tests/test_const.rs b/tests/test_const.rs new file mode 100644 index 0000000..1765c95 --- /dev/null +++ b/tests/test_const.rs @@ -0,0 +1,37 @@ +#[rustversion::attr(all(), const)] +fn _basic() {} +const _BASIC: () = _basic(); + +#[rustversion::attr(all(), const)] +unsafe fn _unsafe() {} +const _UNSAFE: () = unsafe { _unsafe() }; + +macro_rules! item { + ($i:item) => { + #[rustversion::attr(all(), const)] + $i + }; +} + +item! {fn _item() {}} +const _ITEM: () = _item(); + +macro_rules! ident { + ($fn:ident) => { + #[rustversion::attr(all(), const)] + $fn _ident() {} + }; +} + +ident! {fn} +const _IDENT: () = _ident(); + +#[rustversion::attr(all(), const)] +/// doc +fn _doc_below() {} +const _DOC_BELOW: () = _doc_below(); + +/// doc +#[rustversion::attr(all(), const)] +fn _doc_above() {} +const _DOC_ABOVE: () = _doc_above(); diff --git a/tests/test_eval.rs b/tests/test_eval.rs new file mode 100644 index 0000000..c044e85 --- /dev/null +++ b/tests/test_eval.rs @@ -0,0 +1,20 @@ +#[rustversion::any( + stable, + stable(1.34), + stable(1.34.0), + beta, + nightly, + nightly(2020-02-25), + since(1.34), + since(2020-02-25), + before(1.34), + before(2020-02-25), + not(nightly), + all(stable, beta, nightly), +)] +fn success() {} + +#[test] +fn test() { + success(); +} diff --git a/tests/test_parse.rs b/tests/test_parse.rs new file mode 100644 index 0000000..843bd73 --- /dev/null +++ b/tests/test_parse.rs @@ -0,0 +1,84 @@ +include!("../build/rustc.rs"); + +#[test] +fn test_parse() { + let cases = &[ + ( + "rustc 1.0.0 (a59de37e9 2015-05-13) (built 2015-05-14)", + Version { + minor: 0, + patch: 0, + channel: Stable, + }, + ), + ( + "rustc 1.18.0", + Version { + minor: 18, + patch: 0, + channel: Stable, + }, + ), + ( + "rustc 1.24.1 (d3ae9a9e0 2018-02-27)", + Version { + minor: 24, + patch: 1, + channel: Stable, + }, + ), + ( + "rustc 1.35.0-beta.3 (c13114dc8 2019-04-27)", + Version { + minor: 35, + patch: 0, + channel: Beta, + }, + ), + ( + "rustc 1.36.0-nightly (938d4ffe1 2019-04-27)", + Version { + minor: 36, + patch: 0, + channel: Nightly(Date { + year: 2019, + month: 4, + day: 27, + }), + }, + ), + ( + "rustc 1.36.0-dev", + Version { + minor: 36, + patch: 0, + channel: Dev, + }, + ), + ( + "rustc 1.36.0-nightly", + Version { + minor: 36, + patch: 0, + channel: Dev, + }, + ), + ( + "warning: invalid logging spec 'warning', ignoring it + rustc 1.30.0-nightly (3bc2ca7e4 2018-09-20)", + Version { + minor: 30, + patch: 0, + channel: Nightly(Date { + year: 2018, + month: 9, + day: 20, + }), + }, + ), + ]; + + for (string, expected) in cases { + assert_eq!(parse(string).unwrap(), *expected); + } +} diff --git a/tests/ui/bad-bound.rs b/tests/ui/bad-bound.rs new file mode 100644 index 0000000..add8792 --- /dev/null +++ b/tests/ui/bad-bound.rs @@ -0,0 +1,7 @@ +#[rustversion::since(stable)] +struct S; + +#[rustversion::any(since(stable))] +struct S; + +fn main() {} diff --git a/tests/ui/bad-bound.stderr b/tests/ui/bad-bound.stderr new file mode 100644 index 0000000..f8c498c --- /dev/null +++ b/tests/ui/bad-bound.stderr @@ -0,0 +1,11 @@ +error: expected rustc release number like 1.31, or nightly date like 2020-10-26 + --> $DIR/bad-bound.rs:1:22 + | +1 | #[rustversion::since(stable)] + | ^^^^^^ + +error: expected rustc release number like 1.31, or nightly date like 2020-10-26 + --> $DIR/bad-bound.rs:4:26 + | +4 | #[rustversion::any(since(stable))] + | ^^^^^^ diff --git a/tests/ui/bad-date.rs b/tests/ui/bad-date.rs new file mode 100644 index 0000000..0984625 --- /dev/null +++ b/tests/ui/bad-date.rs @@ -0,0 +1,7 @@ +#[rustversion::nightly(stable)] +struct S; + +#[rustversion::any(nightly(stable))] +struct S; + +fn main() {} diff --git a/tests/ui/bad-date.stderr b/tests/ui/bad-date.stderr new file mode 100644 index 0000000..734d788 --- /dev/null +++ b/tests/ui/bad-date.stderr @@ -0,0 +1,11 @@ +error: expected nightly date, like 2020-10-26 + --> $DIR/bad-date.rs:1:24 + | +1 | #[rustversion::nightly(stable)] + | ^^^^^^ + +error: expected nightly date, like 2020-10-26 + --> $DIR/bad-date.rs:4:28 + | +4 | #[rustversion::any(nightly(stable))] + | ^^^^^^ diff --git a/tests/ui/bad-not.rs b/tests/ui/bad-not.rs new file mode 100644 index 0000000..058f340 --- /dev/null +++ b/tests/ui/bad-not.rs @@ -0,0 +1,7 @@ +#[rustversion::any(not)] +struct S; + +#[rustversion::any(not, not)] +struct S; + +fn main() {} diff --git a/tests/ui/bad-not.stderr b/tests/ui/bad-not.stderr new file mode 100644 index 0000000..bfe239b --- /dev/null +++ b/tests/ui/bad-not.stderr @@ -0,0 +1,11 @@ +error: expected `(` after `not` + --> $DIR/bad-not.rs:1:20 + | +1 | #[rustversion::any(not)] + | ^^^ + +error: expected `(` + --> $DIR/bad-not.rs:4:23 + | +4 | #[rustversion::any(not, not)] + | ^ diff --git a/tests/ui/bad-version.rs b/tests/ui/bad-version.rs new file mode 100644 index 0000000..1fe8dba --- /dev/null +++ b/tests/ui/bad-version.rs @@ -0,0 +1,7 @@ +#[rustversion::stable(nightly)] +struct S; + +#[rustversion::any(stable(nightly))] +struct S; + +fn main() {} diff --git a/tests/ui/bad-version.stderr b/tests/ui/bad-version.stderr new file mode 100644 index 0000000..5f7a01f --- /dev/null +++ b/tests/ui/bad-version.stderr @@ -0,0 +1,11 @@ +error: expected rustc release number, like 1.31 + --> $DIR/bad-version.rs:1:23 + | +1 | #[rustversion::stable(nightly)] + | ^^^^^^^ + +error: expected rustc release number, like 1.31 + --> $DIR/bad-version.rs:4:27 + | +4 | #[rustversion::any(stable(nightly))] + | ^^^^^^^ diff --git a/tests/ui/const-not-fn.rs b/tests/ui/const-not-fn.rs new file mode 100644 index 0000000..215df7d --- /dev/null +++ b/tests/ui/const-not-fn.rs @@ -0,0 +1,4 @@ +#[rustversion::attr(all(), const)] +pub struct S; + +fn main() {} diff --git a/tests/ui/const-not-fn.stderr b/tests/ui/const-not-fn.stderr new file mode 100644 index 0000000..7371ff2 --- /dev/null +++ b/tests/ui/const-not-fn.stderr @@ -0,0 +1,5 @@ +error: only allowed on a fn item + --> $DIR/const-not-fn.rs:1:28 + | +1 | #[rustversion::attr(all(), const)] + | ^^^^^ |