aboutsummaryrefslogtreecommitdiff
path: root/rustversion/src
diff options
context:
space:
mode:
Diffstat (limited to 'rustversion/src')
-rw-r--r--rustversion/src/attr.rs35
-rw-r--r--rustversion/src/bound.rs84
-rw-r--r--rustversion/src/date.rs77
-rw-r--r--rustversion/src/expr.rs177
-rw-r--r--rustversion/src/lib.rs254
-rw-r--r--rustversion/src/rustc.rs195
-rw-r--r--rustversion/src/time.rs44
-rw-r--r--rustversion/src/version.rs16
8 files changed, 882 insertions, 0 deletions
diff --git a/rustversion/src/attr.rs b/rustversion/src/attr.rs
new file mode 100644
index 0000000..591b2c0
--- /dev/null
+++ b/rustversion/src/attr.rs
@@ -0,0 +1,35 @@
+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
new file mode 100644
index 0000000..2546637
--- /dev/null
+++ b/rustversion/src/bound.rs
@@ -0,0 +1,84 @@
+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
new file mode 100644
index 0000000..631b762
--- /dev/null
+++ b/rustversion/src/date.rs
@@ -0,0 +1,77 @@
+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
new file mode 100644
index 0000000..2ea91af
--- /dev/null
+++ b/rustversion/src/expr.rs
@@ -0,0 +1,177 @@
+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
new file mode 100644
index 0000000..cf8ed21
--- /dev/null
+++ b/rustversion/src/lib.rs
@@ -0,0 +1,254 @@
+//! 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
new file mode 100644
index 0000000..4e7699d
--- /dev/null
+++ b/rustversion/src/rustc.rs
@@ -0,0 +1,195 @@
+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
new file mode 100644
index 0000000..1e6dd90
--- /dev/null
+++ b/rustversion/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/rustversion/src/version.rs b/rustversion/src/version.rs
new file mode 100644
index 0000000..ab3992f
--- /dev/null
+++ b/rustversion/src/version.rs
@@ -0,0 +1,16 @@
+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,
+}