local_fmt_macros_internal/parse/
alloc.rs

1use std::num::IntErrorKind;
2
3use quote::ToTokens;
4use syn::Ident;
5
6use super::{MessageToken, MessageValue};
7
8pub type AllocMessage = MessageToken<AllocMessageValue>;
9
10pub enum AllocMessageValue {
11    AllocText(String),
12    Placeholder(usize),
13    AllocTextIdent(Ident),
14}
15
16impl MessageValue for AllocMessageValue {
17    const MESSAGE_IDENT: &'static str = "AllocMessage";
18    const MESSAGE_ARG_WRAPPER: &'static str = "vec!";
19
20    fn as_arg(&self) -> Option<usize> {
21        match self {
22            AllocMessageValue::Placeholder(n) => Some(*n),
23            _ => None,
24        }
25    }
26
27    fn new_string(s: String) -> Self {
28        Self::AllocText(s)
29    }
30
31    fn new_placeholder_raw(s: &str) -> Result<Self, super::MessageValueError> {
32        let number = s.parse::<usize>();
33        match number {
34            Ok(ok) => Ok(Self::Placeholder(ok)),
35            Err(err) if IntErrorKind::InvalidDigit == *err.kind() => Ok(Self::AllocTextIdent(
36                Ident::new(s, proc_macro2::Span::call_site()),
37            )),
38            Err(err) => {
39                panic!("Invalid placeholder on {{{}}}: {}", s, err);
40            }
41        }
42    }
43}
44
45impl ToTokens for AllocMessageValue {
46    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
47        match self {
48            AllocMessageValue::AllocText(s) => {
49                tokens.extend(quote::quote! {
50                    local_fmt::AllocMessageFormat::AllocText(#s.to_string()),
51                });
52            }
53            AllocMessageValue::Placeholder(n) => {
54                let n = *n;
55                tokens.extend(quote::quote! {
56                    local_fmt::AllocMessageFormat::Placeholder(#n),
57                });
58            }
59            AllocMessageValue::AllocTextIdent(ident) => {
60                tokens.extend(quote::quote! {
61                    local_fmt::AllocMessageFormat::AllocText(#ident),
62                });
63            }
64        }
65    }
66}