fast_version_derive/
lib.rs

1//! Derive macro defintion for the fast-version crate
2//!
3//! Refer to the [fast-version](https://crates.io/crates/fast-version) for usage and documentation.
4
5use litrs::Literal;
6use quote::quote;
7use std::str::FromStr;
8
9/// Allows compile time generation of Versions from string literals.
10/// ```
11/// # use fast_version_core::version::Version;
12/// # use fast_version_derive::const_version;
13/// const VERSION: Version = const_version!("1.2.3");
14///
15/// assert_eq!(VERSION.major, 1);
16/// assert_eq!(VERSION.minor, 2);
17/// assert_eq!(VERSION.patch, 3);
18/// ```
19#[proc_macro]
20pub fn const_version(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
21    let first_token = input.into_iter().next().expect("expected input into macro");
22
23    match Literal::try_from(first_token) {
24        Err(e) => return e.to_compile_error(),
25        Ok(Literal::String(string)) => {
26            let value = string.value();
27            let version = fast_version_core::version::Version::from_str(value)
28                .expect("Error while parsing string literal into version");
29            let major = version.major;
30            let minor = version.minor;
31            let patch = version.patch;
32            quote! {
33                {
34                    const MAJOR: u64 = #major;
35                    const MINOR: u64 = #minor;
36                    const PATCH: u64 = #patch;
37                    fast_version_core::version::Version::new(MAJOR, MINOR, PATCH)
38                }
39            }
40            .into()
41        }
42        Ok(other) => {
43            panic!("Got non string literal: {}", other);
44        }
45    }
46}