diff options
Diffstat (limited to 'rustversion')
-rw-r--r-- | rustversion/.gitignore | 3 | ||||
-rw-r--r-- | rustversion/.travis.yml | 17 | ||||
-rw-r--r-- | rustversion/Cargo.toml | 21 | ||||
-rw-r--r-- | rustversion/LICENSE-APACHE | 201 | ||||
-rw-r--r-- | rustversion/LICENSE-MIT | 23 | ||||
-rw-r--r-- | rustversion/README.md | 138 | ||||
-rw-r--r-- | rustversion/src/attr.rs | 35 | ||||
-rw-r--r-- | rustversion/src/bound.rs | 84 | ||||
-rw-r--r-- | rustversion/src/date.rs | 77 | ||||
-rw-r--r-- | rustversion/src/expr.rs | 177 | ||||
-rw-r--r-- | rustversion/src/lib.rs | 254 | ||||
-rw-r--r-- | rustversion/src/rustc.rs | 195 | ||||
-rw-r--r-- | rustversion/src/time.rs | 44 | ||||
-rw-r--r-- | rustversion/src/version.rs | 16 |
14 files changed, 0 insertions, 1285 deletions
diff --git a/rustversion/.gitignore b/rustversion/.gitignore deleted file mode 100644 index 6936990..0000000 --- a/rustversion/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -/target -**/*.rs.bk -Cargo.lock diff --git a/rustversion/.travis.yml b/rustversion/.travis.yml deleted file mode 100644 index 1a615ba..0000000 --- a/rustversion/.travis.yml +++ /dev/null @@ -1,17 +0,0 @@ -language: 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 diff --git a/rustversion/Cargo.toml b/rustversion/Cargo.toml deleted file mode 100644 index 789c5f4..0000000 --- a/rustversion/Cargo.toml +++ /dev/null @@ -1,21 +0,0 @@ -[package] -name = "rustversion" -version = "1.0.1" -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" - -[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"] } diff --git a/rustversion/LICENSE-APACHE b/rustversion/LICENSE-APACHE deleted file mode 100644 index 16fe87b..0000000 --- a/rustversion/LICENSE-APACHE +++ /dev/null @@ -1,201 +0,0 @@ - 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/rustversion/LICENSE-MIT b/rustversion/LICENSE-MIT deleted file mode 100644 index 31aa793..0000000 --- a/rustversion/LICENSE-MIT +++ /dev/null @@ -1,23 +0,0 @@ -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/rustversion/README.md b/rustversion/README.md deleted file mode 100644 index f7fdab1..0000000 --- a/rustversion/README.md +++ /dev/null @@ -1,138 +0,0 @@ -Compiler 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" -``` - -<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/rustversion/src/attr.rs b/rustversion/src/attr.rs deleted file mode 100644 index 591b2c0..0000000 --- a/rustversion/src/attr.rs +++ /dev/null @@ -1,35 +0,0 @@ -use 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<Self> { - let condition: Expr = input.parse()?; - - input.parse::<Token![,]>()?; - if input.is_empty() { - return Err(input.error("expected one or more attrs")); - } - - let const_token: Option<Token![const]> = input.parse()?; - let then = if let Some(const_token) = const_token { - input.parse::<Option<Token![,]>>()?; - Then::Const(const_token) - } else { - input.parse().map(Then::Attribute)? - }; - - Ok(Args { condition, then }) - } -} diff --git a/rustversion/src/bound.rs b/rustversion/src/bound.rs deleted file mode 100644 index 2546637..0000000 --- a/rustversion/src/bound.rs +++ /dev/null @@ -1,84 +0,0 @@ -use 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<u16>, -} - -impl Parse for Bound { - fn parse(input: ParseStream) -> Result<Self> { - if input.peek2(Token![-]) { - input.parse().map(Bound::Nightly) - } else { - input.parse().map(Bound::Stable) - } - } -} - -impl Parse for Release { - fn parse(input: ParseStream) -> Result<Self> { - 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::<Option<Token![.]>>()?.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<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/rustversion/src/date.rs b/rustversion/src/date.rs deleted file mode 100644 index 631b762..0000000 --- a/rustversion/src/date.rs +++ /dev/null @@ -1,77 +0,0 @@ -use 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<ParseIntError> for ParseDateError { - fn from(_err: ParseIntError) -> Self { - ParseDateError - } -} - -impl FromStr for Date { - type Err = ParseDateError; - - fn from_str(s: &str) -> Result<Self, Self::Err> { - 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<Self> { - 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::<Token![-]>()?; - let month: LitInt = input.parse().map_err(|_| error())?; - input.parse::<Token![-]>()?; - let day: LitInt = input.parse().map_err(|_| error())?; - - let year = year.base10_parse::<u64>().map_err(|_| error())?; - let month = month.base10_parse::<u64>().map_err(|_| error())?; - let day = day.base10_parse::<u64>().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, - }) - } -} diff --git a/rustversion/src/expr.rs b/rustversion/src/expr.rs deleted file mode 100644 index 2ea91af..0000000 --- a/rustversion/src/expr.rs +++ /dev/null @@ -1,177 +0,0 @@ -use 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<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)), - } - } -} - -type Exprs = Punctuated<Expr, Token![,]>; - -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<Self> { - 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<Self> { - input.parse::<keyword::nightly>()?; - - if !input.peek(token::Paren) { - return Ok(Expr::Nightly); - } - - let paren; - parenthesized!(paren in input); - let date: Date = paren.parse()?; - paren.parse::<Option<Token![,]>>()?; - - Ok(Expr::Date(date)) - } - - fn parse_beta(input: ParseStream) -> Result<Self> { - input.parse::<keyword::beta>()?; - - Ok(Expr::Beta) - } - - fn parse_stable(input: ParseStream) -> Result<Self> { - input.parse::<keyword::stable>()?; - - if !input.peek(token::Paren) { - return Ok(Expr::Stable); - } - - let paren; - parenthesized!(paren in input); - let release: Release = paren.parse()?; - paren.parse::<Option<Token![,]>>()?; - - Ok(Expr::Release(release)) - } - - fn parse_since(input: ParseStream) -> Result<Self> { - input.parse::<keyword::since>()?; - - let paren; - parenthesized!(paren in input); - let bound: Bound = paren.parse()?; - paren.parse::<Option<Token![,]>>()?; - - Ok(Expr::Since(bound)) - } - - fn parse_before(input: ParseStream) -> Result<Self> { - input.parse::<keyword::before>()?; - - let paren; - parenthesized!(paren in input); - let bound: Bound = paren.parse()?; - paren.parse::<Option<Token![,]>>()?; - - Ok(Expr::Before(bound)) - } - - fn parse_not(input: ParseStream) -> Result<Self> { - input.parse::<keyword::not>()?; - - let paren; - parenthesized!(paren in input); - let expr: Expr = paren.parse()?; - paren.parse::<Option<Token![,]>>()?; - - Ok(Expr::Not(Box::new(expr))) - } - - fn parse_any(input: ParseStream) -> Result<Self> { - input.parse::<keyword::any>()?; - - 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<Self> { - input.parse::<keyword::all>()?; - - let paren; - parenthesized!(paren in input); - let exprs: Exprs = paren.parse_terminated(Expr::parse)?; - - Ok(Expr::All(exprs.into_iter().collect())) - } -} diff --git a/rustversion/src/lib.rs b/rustversion/src/lib.rs deleted file mode 100644 index cf8ed21..0000000 --- a/rustversion/src/lib.rs +++ /dev/null @@ -1,254 +0,0 @@ -//! 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 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<TokenStream> { - 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<TokenStream> { - 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 - })) - } - } -} diff --git a/rustversion/src/rustc.rs b/rustversion/src/rustc.rs deleted file mode 100644 index 4e7699d..0000000 --- a/rustversion/src/rustc.rs +++ /dev/null @@ -1,195 +0,0 @@ -use 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<T> = std::result::Result<T, Error>; - -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<FromUtf8Error> for Error { - fn from(err: FromUtf8Error) -> Self { - Error::Utf8(err) - } -} - -impl From<Error> for syn::Error { - fn from(err: Error) -> Self { - syn::Error::new(Span::call_site(), err) - } -} - -pub fn version() -> Result<Version> { - 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<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 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); - } -} diff --git a/rustversion/src/time.rs b/rustversion/src/time.rs deleted file mode 100644 index 1e6dd90..0000000 --- a/rustversion/src/time.rs +++ /dev/null @@ -1,44 +0,0 @@ -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/rustversion/src/version.rs b/rustversion/src/version.rs deleted file mode 100644 index ab3992f..0000000 --- a/rustversion/src/version.rs +++ /dev/null @@ -1,16 +0,0 @@ -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, -} |