1use crate::parser::parse_scientific;
4use proc_macro::TokenStream;
5use proc_macro2::{Delimiter, Group, Punct, Spacing, Span, TokenStream as TokenStream2};
6use quote::{quote, ToTokens, TokenStreamExt};
7use syn::parse::{Parse, ParseStream};
8use syn::{parse_macro_input, Error, LitFloat, LitInt, Token};
9
10mod parser;
11
12enum LitIntOrLitFloat {
14 LitInt(LitInt),
15 LitFloat(LitFloat),
16}
17
18impl LitIntOrLitFloat {
19 fn base10_digits(&self) -> &str {
20 match self {
21 LitIntOrLitFloat::LitInt(num) => num.base10_digits(),
22 LitIntOrLitFloat::LitFloat(num) => num.base10_digits(),
23 }
24 }
25
26 fn suffix(&self) -> &str {
27 match self {
28 LitIntOrLitFloat::LitInt(num) => num.suffix(),
29 LitIntOrLitFloat::LitFloat(num) => num.suffix(),
30 }
31 }
32
33 fn span(&self) -> Span {
34 match self {
35 LitIntOrLitFloat::LitInt(num) => num.span(),
36 LitIntOrLitFloat::LitFloat(num) => num.span(),
37 }
38 }
39}
40
41impl Parse for LitIntOrLitFloat {
42 fn parse(input: ParseStream) -> Result<Self, Error> {
43 let lookahead = input.lookahead1();
44 if lookahead.peek(LitInt) {
45 input.parse().map(LitIntOrLitFloat::LitInt)
46 } else if lookahead.peek(LitFloat) {
47 input.parse().map(LitIntOrLitFloat::LitFloat)
48 } else {
49 Err(lookahead.error())
50 }
51 }
52}
53
54struct LitScientific {
56 neg: Option<Token![-]>,
57 num: LitIntOrLitFloat,
58}
59
60impl Parse for LitScientific {
61 fn parse(input: ParseStream) -> Result<Self, Error> {
62 Ok(LitScientific {
63 neg: input.parse()?,
64 num: input.parse()?,
65 })
66 }
67}
68
69struct AsSlice<'a>(&'a [u8]);
71
72impl<'a> ToTokens for AsSlice<'a> {
73 fn to_tokens(&self, stream: &mut TokenStream2) {
74 let mut body_stream = TokenStream2::new();
75 for d in self.0.iter() {
76 d.to_tokens(&mut body_stream);
77 body_stream.append(Punct::new(',', Spacing::Alone));
78 }
79 stream.append(Group::new(Delimiter::Bracket, body_stream));
80 }
81}
82
83#[allow(non_snake_case)]
88#[proc_macro]
89pub fn Scientific(item: TokenStream) -> TokenStream {
90 let LitScientific { neg, num } = parse_macro_input!(item as LitScientific);
91 if !num.suffix().is_empty() {
92 return TokenStream::from(Error::new(num.span(), "No suffix allowed").to_compile_error());
93 }
94 match parse_scientific(num.base10_digits()) {
95 Err(()) => TokenStream::from(Error::new(num.span(), "Parse error").to_compile_error()),
96 Ok(None) => quote!(::scientific::Scientific::ZERO).into(),
97 Ok(Some((mantissa, exponent))) => {
98 let neg = neg.is_some();
99 let len = mantissa.len();
100 let mantissa = AsSlice(&mantissa);
101 quote!(
102 {
103 const MANTISSA: [u8; #len] = #mantissa;
104 ::scientific::Scientific::unchecked_non_zero_static_new(#neg, &MANTISSA, #exponent)
105 }
106 )
107 .into()
108 }
109 }
110}