Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Impl UUID macro #543

Merged
merged 7 commits into from Nov 1, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 23 additions & 0 deletions benches/valid_parse_str.rs
Expand Up @@ -37,3 +37,26 @@ fn bench_valid_short(b: &mut Bencher) {
let _ = Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c8");
});
}


#[cfg(feature = "macros")]
mod macro_tests {
use uuid::{uuid, Uuid};
const _: Uuid = uuid!("00000000000000000000000000000000");
const _: Uuid = uuid!("67e55044-10b1-426f-9247-bb680e5fe0c8");
const _: Uuid = uuid!("67e55044-10b1-426f-9247-bb680e5fe0c8");
const _: Uuid = uuid!("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4");
const _: Uuid = uuid!("67e5504410b1426f9247bb680e5fe0c8");
const _: Uuid = uuid!("01020304-1112-2122-3132-414243444546");
const _: Uuid =
uuid!("urn:uuid:67e55044-10b1-426f-9247-bb680e5fe0c8");

// Nil
const _: Uuid = uuid!("00000000000000000000000000000000");
const _: Uuid = uuid!("00000000-0000-0000-0000-000000000000");

// valid hyphenated
const _: Uuid = uuid!("67e55044-10b1-426f-9247-bb680e5fe0c8");
// valid short
const _: Uuid = uuid!("67e5504410b1426f9247bb680e5fe0c8");
}
3 changes: 3 additions & 0 deletions macros/Cargo.toml
Expand Up @@ -7,3 +7,6 @@ edition = "2018"
proc-macro = true

[dependencies]
syn = "1.0.80"
quote = "1.0.10"
proc-macro2 = "1.0.29"
105 changes: 97 additions & 8 deletions macros/src/lib.rs
@@ -1,17 +1,106 @@
use std;
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{quote, quote_spanned};
use std::fmt;
use syn::spanned::Spanned;

#[cfg(any(feature = "std", test))]
#[macro_use]
extern crate std;

#[cfg(all(not(feature = "std"), not(test)))]
#[macro_use]
extern crate core as std;
Comment on lines +7 to +13
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Required to stop shared/error.rs and shared/parser.rs from complaining. I just copy-pasted it from uuid.


#[path = "../../shared/error.rs"]
#[allow(dead_code)]
mod error;

#[path = "../../shared/parser.rs"]
#[allow(dead_code)]
mod parser;

#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
/// Parse [`Uuid`][uuid::Uuid]s from string literals at compile time.
/// ## Usage
/// This macro transforms the string literal representation of a [`Uuid`][uuid::Uuid] into the bytes representation,
/// raising a compilation error if it cannot properly be parsed.
///
/// ## Examples
/// Setting a global constant:
/// ```
/// # use uuid::{uuid, Uuid};
/// pub const SCHEMA_ATTR_CLASS: Uuid = uuid!("00000000-0000-0000-0000-ffff00000000");
/// pub const SCHEMA_ATTR_UUID: Uuid = uuid!("00000000-0000-0000-0000-ffff00000001");
/// pub const SCHEMA_ATTR_NAME: Uuid = uuid!("00000000-0000-0000-0000-ffff00000002");
/// ```
/// Defining a local variable:
/// ```
/// # use uuid::{uuid, Uuid};
/// let uuid: Uuid = uuid!("urn:uuid:F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4");
/// ```
/// ## Compilation Failures
/// Invalid UUIDs are rejected:
/// ```ignore
/// # use uuid::{uuid, Uuid};
/// let uuid: Uuid = uuid!("F9168C5E-ZEB2-4FAA-B6BF-329BF39FA1E4");
/// ```
/// Provides the following compilation error:
/// ```txt
/// error: invalid character: expected an optional prefix of `urn:uuid:` followed by 0123456789abcdefABCDEF-, found Z at 9
/// |
/// | let id: Uuid = uuid!("F9168C5E-ZEB2-4FAA-B6BF-329BF39FA1E4");
/// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/// ```
/// Tokens that aren't string literals are also rejected:
/// ```ignore
/// # use uuid::{uuid, Uuid};
/// let uuid_str: &str = "550e8400e29b41d4a716446655440000";
/// let uuid: Uuid = uuid!(uuid_str);
/// ```
/// Provides the following compilation error:
/// ```txt
/// error: expected string literal
/// |
/// | let uuid: Uuid = uuid!(uuid_str);
/// | ^^^^^^^^
/// ```
///
/// [uuid::Uuid]: https://docs.rs/uuid/*/uuid/struct.Uuid.html
#[proc_macro]
pub fn uuid(input: TokenStream) -> TokenStream {
build_uuid(input.clone()).unwrap_or_else(|e| {
let msg = e.to_string();
TokenStream::from(quote_spanned! {
TokenStream2::from(input).span() =>
compile_error!(#msg)
})
})
}

enum Error {
NonStringLiteral,
UuidParse(error::Error),
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::NonStringLiteral => f.write_str("expected string literal"),
Error::UuidParse(ref e) => write!(f, "{}", e),
}
}
}

fn build_uuid(input: TokenStream) -> Result<TokenStream, Error> {
let uuid_str = match syn::parse::<syn::Lit>(input) {
Ok(syn::Lit::Str(ref literal)) => literal.value(),
_ => return Err(Error::NonStringLiteral),
};

let bytes = parser::parse_str(&uuid_str).map_err(Error::UuidParse)?;

let tokens = bytes
.iter()
.map(|byte| quote! { #byte, })
.collect::<TokenStream2>();

Ok(quote! {::uuid::Uuid::from_bytes([#tokens])}.into())
}