local_fmt_macros_internal/parse/
static_ref.rs1use std::num::IntErrorKind;
2
3use quote::ToTokens;
4use syn::Ident;
5
6use super::{MessageToken, MessageValue};
7
8pub type StaticMessage = MessageToken<StaticMessageValue>;
9
10pub enum StaticMessageValue {
11 StaticText(String),
12 UNumberIdent(Ident),
13 INumberIdent(Ident),
14 Placeholder(usize),
15 StaticTextIdent(Ident),
16}
17
18impl MessageValue for StaticMessageValue {
19 const MESSAGE_IDENT: &'static str = "StaticMessage";
20 const MESSAGE_ARG_WRAPPER: &'static str = "&";
21
22 fn as_arg(&self) -> Option<usize> {
23 match self {
24 StaticMessageValue::Placeholder(n) => Some(*n),
25 _ => None,
26 }
27 }
28
29 fn new_string(s: String) -> Self {
30 Self::StaticText(s)
31 }
32
33 fn new_placeholder_raw(s: &str) -> Result<Self, super::MessageValueError> {
34 if let Some(ident) = s.strip_prefix("u:") {
35 Ok(Self::UNumberIdent(Ident::new(
36 ident,
37 proc_macro2::Span::call_site(),
38 )))
39 } else if let Some(ident) = s.strip_prefix("i:") {
40 Ok(Self::INumberIdent(Ident::new(
41 ident,
42 proc_macro2::Span::call_site(),
43 )))
44 } else {
45 let number = s.parse::<usize>();
46 match number {
47 Ok(ok) => Ok(Self::Placeholder(ok)),
48 Err(err) if IntErrorKind::InvalidDigit == *err.kind() => Ok(Self::StaticTextIdent(
49 Ident::new(s, proc_macro2::Span::call_site()),
50 )),
51 Err(err) => {
52 panic!("Invalid placeholder on {{{}}}: {}", s, err);
53 }
54 }
55 }
56 }
57}
58
59impl ToTokens for StaticMessageValue {
60 fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
61 match self {
62 StaticMessageValue::StaticText(s) => {
63 tokens.extend(quote::quote! {
64 local_fmt::RefMessageFormat::RefText(#s),
65 });
66 }
67 StaticMessageValue::UNumberIdent(ident) => {
68 tokens.extend(quote::quote! {
69 local_fmt::RefMessageFormat::UNumber(#ident as u128),
70 });
71 }
72 StaticMessageValue::INumberIdent(ident) => {
73 tokens.extend(quote::quote! {
74 local_fmt::RefMessageFormat::INumber(#ident as i128),
75 });
76 }
77 StaticMessageValue::Placeholder(n) => {
78 let n = *n;
79 tokens.extend(quote::quote! {
80 local_fmt::RefMessageFormat::Placeholder(#n),
81 });
82 }
83 StaticMessageValue::StaticTextIdent(ident) => {
84 tokens.extend(quote::quote! {
85 local_fmt::RefMessageFormat::RefText(#ident),
86 });
87 }
88 }
89 }
90}