-
Notifications
You must be signed in to change notification settings - Fork 193
/
lib.rs
96 lines (84 loc) · 2.68 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//! Implementation details for the `uuid!` macro.
//!
//! This crate is not meant to be used directly. Instead,
//! you can use the `macros` feature of `uuid`:
//!
//! ```toml
//! [dependencies.uuid]
//! features = ["macros"]
//! ```
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;
#[path = "../../shared/error.rs"]
mod error;
#[path = "../../shared/parser.rs"]
mod parser;
#[proc_macro]
#[doc(hidden)]
pub fn parse_lit(input: TokenStream) -> TokenStream {
build_uuid(input.clone()).unwrap_or_else(|e| {
let msg = e.to_string();
let ts = TokenStream2::from(input);
let span = match e {
Error::UuidParse(error::Error(
error::ErrorKind::InvalidCharacter { found, index, .. },
)) => {
// Hack to find the byte width of the char
// so we can set the span accordingly.
let mut bytes = found as u32;
let mut width = 0;
while bytes != 0 {
bytes >>= 4;
width += 1;
}
let mut s = proc_macro2::Literal::string("");
s.set_span(ts.span());
s.subspan(index + 1..index + width).unwrap()
}
Error::UuidParse(error::Error(
error::ErrorKind::InvalidGroupLength { found, index, .. },
)) => {
let mut s = proc_macro2::Literal::string("");
s.set_span(ts.span());
s.subspan(index..index + found).unwrap()
}
_ => ts.span(),
};
TokenStream::from(quote_spanned! {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 string = match syn::parse::<syn::Lit>(input) {
Ok(syn::Lit::Str(literal)) => literal.value(),
_ => return Err(Error::NonStringLiteral),
};
let bytes = parser::parse_str(&string).map_err(Error::UuidParse)?;
let tokens = bytes
.iter()
.map(|byte| quote! { #byte, })
.collect::<TokenStream2>();
Ok(quote! {[#tokens]}.into())
}