rustversion-1.0.1/.gitignore010066400017500001750000000000361360053766400143400ustar0000000000000000/target **/*.rs.bk Cargo.lock rustversion-1.0.1/.travis.yml010066400017500001750000000003361360053766400144640ustar0000000000000000language: rust rust: - nightly - beta - stable - 1.31.0 script: - cargo test matrix: include: - rust: nightly name: Minimal versions before_script: - cargo update -Z minimal-versions rustversion-1.0.1/Cargo.toml.orig010066400017500001750000000010151360241703600152250ustar0000000000000000[package] name = "rustversion" version = "1.0.1" authors = ["David Tolnay "] 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" [lib] proc-macro = true [badges] travis-ci = { repository = "dtolnay/rustversion" } [dependencies] proc-macro2 = "1.0" quote = "1.0" syn = { version = "1.0.1", features = ["full"] } rustversion-1.0.1/Cargo.toml0000644000000020731360241705200115340ustar00# 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.1" authors = ["David Tolnay "] 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" [lib] proc-macro = true [dependencies.proc-macro2] version = "1.0" [dependencies.quote] version = "1.0" [dependencies.syn] version = "1.0.1" features = ["full"] [badges.travis-ci] repository = "dtolnay/rustversion" rustversion-1.0.1/LICENSE-APACHE010066400017500001750000000251371360053766400143050ustar0000000000000000 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. rustversion-1.0.1/LICENSE-MIT010066400017500001750000000017771360053766400140210ustar0000000000000000Permission 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. rustversion-1.0.1/README.md010066400017500001750000000074551360053766400136430ustar0000000000000000Compiler version cfg ==================== [![Build Status](https://api.travis-ci.com/dtolnay/rustversion.svg?branch=master)](https://travis-ci.com/dtolnay/rustversion) [![Latest Version](https://img.shields.io/crates/v/rustversion.svg)](https://crates.io/crates/rustversion) [![Rust Documentation](https://img.shields.io/badge/api-rustdoc-blue.svg)](https://docs.rs/rustversion) 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" ```
## Selectors - `#[rustversion::stable]`
True on any stable compiler. - `#[rustversion::stable(1.34)]`
True on exactly the specified stable compiler. - `#[rustversion::beta]`
True on any beta compiler. - `#[rustversion::nightly]`
True on any nightly compiler or dev build. - `#[rustversion::nightly(2019-01-01)]`
True on exactly one nightly. - `#[rustversion::since(1.34)]`
True on that stable release and any later compiler, including beta and nightly. - `#[rustversion::since(2019-01-01)]`
True on that nightly and all newer ones. - `#[rustversion::before(`version or date`)]`
Negative of *#[rustversion::since(...)]*. - `#[rustversion::not(`selector`)]`
Negative of any selector; for example *#[rustversion::not(nightly)]*. - `#[rustversion::any(`selectors...`)]`
True if any of the comma-separated selectors is true; for example *#[rustversion::any(stable, beta)]*. - `#[rustversion::all(`selectors...`)]`
True if all of the comma-separated selectors are true; for example *#[rustversion::all(since(1.31), before(1.34))]*. - `#[rustversion::attr(`selector`, `attribute`)]`
For conditional inclusion of attributes; analogous to `cfg_attr`.
## Use cases Providing additional trait impls as types are stabilized in the standard library without breaking compatibility with older compilers; in this case Pin\ 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 MyTrait for Pin

{ /* ... */ } ``` 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::()); } ``` 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 } ```
#### License Licensed under either of Apache License, Version 2.0 or MIT license at your option.
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. rustversion-1.0.1/src/attr.rs010066400017500001750000000015251360053766400144630ustar0000000000000000use crate::expr::Expr; use proc_macro2::TokenStream; use syn::parse::{Parse, ParseStream, Result}; use syn::Token; pub struct Args { pub condition: Expr, pub then: Then, } pub enum Then { Const(Token![const]), Attribute(TokenStream), } impl Parse for Args { fn parse(input: ParseStream) -> Result { let condition: Expr = input.parse()?; input.parse::()?; if input.is_empty() { return Err(input.error("expected one or more attrs")); } let const_token: Option = input.parse()?; let then = if let Some(const_token) = const_token { input.parse::>()?; Then::Const(const_token) } else { input.parse().map(Then::Attribute)? }; Ok(Args { condition, then }) } } rustversion-1.0.1/src/bound.rs010066400017500001750000000046611360053766400146240ustar0000000000000000use crate::date::Date; use crate::version::{Channel::*, Version}; use quote::quote; use std::cmp::Ordering; use syn::parse::{Error, Parse, ParseStream, Result}; use syn::{LitFloat, LitInt, Token}; pub enum Bound { Nightly(Date), Stable(Release), } #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Release { pub minor: u16, pub patch: Option, } impl Parse for Bound { fn parse(input: ParseStream) -> Result { if input.peek2(Token![-]) { input.parse().map(Bound::Nightly) } else { input.parse().map(Bound::Stable) } } } impl Parse for Release { fn parse(input: ParseStream) -> Result { let span = input.cursor().token_stream(); let error = || Error::new_spanned(&span, "expected rustc release number, like 1.31"); let major_minor: LitFloat = input.parse().map_err(|_| error())?; let string = quote!(#major_minor).to_string(); if !string.starts_with("1.") { return Err(error()); } let minor: u16 = string[2..].parse().map_err(|_| error())?; let patch = if input.parse::>()?.is_some() { let int: LitInt = input.parse().map_err(|_| error())?; Some(int.base10_parse().map_err(|_| error())?) } else { None }; Ok(Release { minor, patch }) } } impl PartialEq 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 for Version { fn partial_cmp(&self, rhs: &Bound) -> Option { 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)) } } } } rustversion-1.0.1/src/date.rs010066400017500001750000000041751360053766400144320ustar0000000000000000use crate::time; use std::fmt::{self, Display}; use std::num::ParseIntError; use std::str::FromStr; use syn::parse::{Error, Parse, ParseStream}; use syn::{LitInt, Token}; #[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 struct ParseDateError; impl From for ParseDateError { fn from(_err: ParseIntError) -> Self { ParseDateError } } impl FromStr for Date { type Err = ParseDateError; fn from_str(s: &str) -> Result { let mut date = s.split('-'); let year = date.next().ok_or(ParseDateError)?.parse()?; let month = date.next().ok_or(ParseDateError)?.parse()?; let day = date.next().ok_or(ParseDateError)?.parse()?; match date.next() { None => Ok(Date { year, month, day }), Some(_) => Err(ParseDateError), } } } impl Parse for Date { fn parse(input: ParseStream) -> syn::Result { let span = input.cursor().token_stream(); let error = || { Error::new_spanned( &span, format!("expected nightly date, like {}", time::today()), ) }; let year: LitInt = input.parse().map_err(|_| error())?; input.parse::()?; let month: LitInt = input.parse().map_err(|_| error())?; input.parse::()?; let day: LitInt = input.parse().map_err(|_| error())?; let year = year.base10_parse::().map_err(|_| error())?; let month = month.base10_parse::().map_err(|_| error())?; let day = day.base10_parse::().map_err(|_| error())?; if year >= 3000 || month > 12 || day > 31 { return Err(error()); } Ok(Date { year: year as u16, month: month as u8, day: day as u8, }) } } rustversion-1.0.1/src/expr.rs010066400017500001750000000116411360053766400144670ustar0000000000000000use crate::bound::{Bound, Release}; use crate::date::Date; use crate::version::{Channel, Version}; use syn::parse::{Parse, ParseStream, Result}; use syn::punctuated::Punctuated; use syn::{parenthesized, token, Token}; pub enum Expr { Stable, Beta, Nightly, Date(Date), Since(Bound), Before(Bound), Release(Release), Not(Box), Any(Vec), All(Vec), } 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)), } } } type Exprs = Punctuated; mod keyword { syn::custom_keyword!(stable); syn::custom_keyword!(beta); syn::custom_keyword!(nightly); syn::custom_keyword!(since); syn::custom_keyword!(before); syn::custom_keyword!(not); syn::custom_keyword!(any); syn::custom_keyword!(all); } impl Parse for Expr { fn parse(input: ParseStream) -> Result { let lookahead = input.lookahead1(); if lookahead.peek(keyword::stable) { Self::parse_stable(input) } else if lookahead.peek(keyword::beta) { Self::parse_beta(input) } else if lookahead.peek(keyword::nightly) { Self::parse_nightly(input) } else if lookahead.peek(keyword::since) { Self::parse_since(input) } else if lookahead.peek(keyword::before) { Self::parse_before(input) } else if lookahead.peek(keyword::not) { Self::parse_not(input) } else if lookahead.peek(keyword::any) { Self::parse_any(input) } else if lookahead.peek(keyword::all) { Self::parse_all(input) } else { Err(lookahead.error()) } } } impl Expr { fn parse_nightly(input: ParseStream) -> Result { input.parse::()?; if !input.peek(token::Paren) { return Ok(Expr::Nightly); } let paren; parenthesized!(paren in input); let date: Date = paren.parse()?; paren.parse::>()?; Ok(Expr::Date(date)) } fn parse_beta(input: ParseStream) -> Result { input.parse::()?; Ok(Expr::Beta) } fn parse_stable(input: ParseStream) -> Result { input.parse::()?; if !input.peek(token::Paren) { return Ok(Expr::Stable); } let paren; parenthesized!(paren in input); let release: Release = paren.parse()?; paren.parse::>()?; Ok(Expr::Release(release)) } fn parse_since(input: ParseStream) -> Result { input.parse::()?; let paren; parenthesized!(paren in input); let bound: Bound = paren.parse()?; paren.parse::>()?; Ok(Expr::Since(bound)) } fn parse_before(input: ParseStream) -> Result { input.parse::()?; let paren; parenthesized!(paren in input); let bound: Bound = paren.parse()?; paren.parse::>()?; Ok(Expr::Before(bound)) } fn parse_not(input: ParseStream) -> Result { input.parse::()?; let paren; parenthesized!(paren in input); let expr: Expr = paren.parse()?; paren.parse::>()?; Ok(Expr::Not(Box::new(expr))) } fn parse_any(input: ParseStream) -> Result { input.parse::()?; let paren; parenthesized!(paren in input); let exprs: Exprs = paren.parse_terminated(Expr::parse)?; Ok(Expr::Any(exprs.into_iter().collect())) } fn parse_all(input: ParseStream) -> Result { input.parse::()?; let paren; parenthesized!(paren in input); let exprs: Exprs = paren.parse_terminated(Expr::parse)?; Ok(Expr::All(exprs.into_iter().collect())) } } rustversion-1.0.1/src/lib.rs010066400017500001750000000163371360053766400142660ustar0000000000000000//! 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 //! //!
//! //! # Selectors //! //! -

//! #[rustversion::stable] //! —
//! True on any stable compiler. //!

//! //! -

//! #[rustversion::stable(1.34)] //! —
//! True on exactly the specified stable compiler. //!

//! //! -

//! #[rustversion::beta] //! —
//! True on any beta compiler. //!

//! //! -

//! #[rustversion::nightly] //! —
//! True on any nightly compiler or dev build. //!

//! //! -

//! #[rustversion::nightly(2019-01-01)] //! —
//! True on exactly one nightly. //!

//! //! -

//! #[rustversion::since(1.34)] //! —
//! True on that stable release and any later compiler, including beta and //! nightly. //!

//! //! -

//! #[rustversion::since(2019-01-01)] //! —
//! True on that nightly and all newer ones. //!

//! //! -

//! #[rustversion::before(version or date)] //! —
//! Negative of #[rustversion::since(...)]. //!

//! //! -

//! #[rustversion::not(selector)] //! —
//! Negative of any selector; for example #[rustversion::not(nightly)]. //!

//! //! -

//! #[rustversion::any(selectors...)] //! —
//! True if any of the comma-separated selectors is true; for example //! #[rustversion::any(stable, beta)]. //!

//! //! -

//! #[rustversion::all(selectors...)] //! —
//! True if all of the comma-separated selectors are true; for example //! #[rustversion::all(since(1.31), before(1.34))]. //!

//! //! -

//! #[rustversion::attr(selector, attribute)] //! —
//! For conditional inclusion of attributes; analogous to //! cfg_attr. //!

//! //!
//! //! # Use cases //! //! Providing additional trait impls as types are stabilized in the standard library //! without breaking compatibility with older compilers; in this case Pin\ //! 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 MyTrait for Pin

{ //! /* ... */ //! } //! ``` //! //! 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::()); //! } //! ``` //! //! 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 //! } //! ``` //! //!
extern crate proc_macro; mod attr; mod bound; mod date; mod expr; mod rustc; mod time; mod version; use crate::attr::Then; use crate::expr::Expr; use proc_macro::TokenStream; use proc_macro2::{Ident, Span, TokenStream as TokenStream2}; use quote::quote; use syn::{parse_macro_input, ItemFn, Result}; #[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(top: &str, args: TokenStream, input: TokenStream) -> TokenStream { match try_cfg(top, args, input) { Ok(tokens) => tokens, Err(err) => TokenStream::from(err.to_compile_error()), } } fn try_cfg(top: &str, args: TokenStream, input: TokenStream) -> Result { let args = TokenStream2::from(args); let top = Ident::new(top, Span::call_site()); let mut full_args = quote!(#top); if !args.is_empty() { full_args.extend(quote!((#args))); } let expr: Expr = syn::parse2(full_args)?; let version = rustc::version()?; if expr.eval(version) { Ok(input) } else { Ok(TokenStream::new()) } } #[proc_macro_attribute] pub fn attr(args: TokenStream, input: TokenStream) -> TokenStream { let args = parse_macro_input!(args as attr::Args); match try_attr(args, input) { Ok(tokens) => tokens, Err(err) => TokenStream::from(err.to_compile_error()), } } fn try_attr(args: attr::Args, input: TokenStream) -> Result { let version = rustc::version()?; if !args.condition.eval(version) { return Ok(input); } match args.then { Then::Const(const_token) => { let mut input: ItemFn = syn::parse(input)?; input.sig.constness = Some(const_token); Ok(TokenStream::from(quote!(#input))) } Then::Attribute(then) => { let input = TokenStream2::from(input); Ok(TokenStream::from(quote! { #[cfg_attr(all(), #then)] #input })) } } } rustversion-1.0.1/src/rustc.rs010066400017500001750000000115551360241656600146540ustar0000000000000000use std::env; use std::ffi::OsString; use std::fmt::{self, Display}; use std::io; use std::process::Command; use std::str::FromStr; use std::string::FromUtf8Error; use crate::date::Date; use crate::version::{Channel::*, Version}; use proc_macro2::Span; #[derive(Debug)] pub enum Error { Exec(io::Error), Utf8(FromUtf8Error), Parse(String), } pub type Result = std::result::Result; impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::Error::*; match self { Exec(e) => write!(f, "failed to run `rustc --version`: {}", e), Utf8(e) => write!(f, "failed to parse output of `rustc --version`: {}", e), Parse(string) => write!( f, "unexpected output from `rustc --version`, please file an issue: {:?}", string, ), } } } impl From for Error { fn from(err: FromUtf8Error) -> Self { Error::Utf8(err) } } impl From for syn::Error { fn from(err: Error) -> Self { syn::Error::new(Span::call_site(), err) } } pub fn version() -> Result { let rustc = env::var_os("RUSTC").unwrap_or_else(|| OsString::from("rustc")); let output = Command::new(rustc) .arg("--version") .output() .map_err(Error::Exec)?; let string = String::from_utf8(output.stdout)?; match parse(&string) { Some(version) => Ok(version), None => Err(Error::Parse(string)), } } fn parse(string: &str) -> Option { 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 date = Date::from_str(&date[..date.len() - 1]).ok()?; Nightly(date) } None => Dev, } } Some(_) => return None, }; Some(Version { minor, patch, channel, }) } #[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); } } rustversion-1.0.1/src/time.rs010066400017500001750000000022601360053766400144440ustar0000000000000000use 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 { 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; } } rustversion-1.0.1/src/version.rs010066400017500001750000000004131360053766400151710ustar0000000000000000use 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, } rustversion-1.0.1/.cargo_vcs_info.json0000644000000001121360241705200135260ustar00{ "git": { "sha1": "0c5663313516263059ce9059ef81fc7a1cf655ca" } }